summaryrefslogtreecommitdiff
path: root/includes/db/LoadBalancer.php
blob: 1e8592782645fae8830562ed92703bcf6cb79343 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
<?php
/**
 * Database load balancing.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup Database
 */

/**
 * Database load balancing object
 *
 * @todo document
 * @ingroup Database
 */
class LoadBalancer {
	private $mServers, $mConns, $mLoads, $mGroupLoads;
	private $mErrorConnection;
	private $mReadIndex, $mAllowLagged;
	private $mWaitForPos, $mWaitTimeout;
	private $mLaggedSlaveMode, $mLastError = 'Unknown error';
	private $mParentInfo, $mLagTimes;
	private $mLoadMonitorClass, $mLoadMonitor;

	/**
	 * @param array $params with keys:
	 *    servers           Required. Array of server info structures.
	 *    masterWaitTimeout Replication lag wait timeout
	 *    loadMonitor       Name of a class used to fetch server lag and load.
	 * @throws MWException
	 */
	function __construct( $params ) {
		if ( !isset( $params['servers'] ) ) {
			throw new MWException( __CLASS__ . ': missing servers parameter' );
		}
		$this->mServers = $params['servers'];

		if ( isset( $params['waitTimeout'] ) ) {
			$this->mWaitTimeout = $params['waitTimeout'];
		} else {
			$this->mWaitTimeout = 10;
		}

		$this->mReadIndex = -1;
		$this->mWriteIndex = -1;
		$this->mConns = array(
			'local' => array(),
			'foreignUsed' => array(),
			'foreignFree' => array() );
		$this->mLoads = array();
		$this->mWaitForPos = false;
		$this->mLaggedSlaveMode = false;
		$this->mErrorConnection = false;
		$this->mAllowLagged = false;

		if ( isset( $params['loadMonitor'] ) ) {
			$this->mLoadMonitorClass = $params['loadMonitor'];
		} else {
			$master = reset( $params['servers'] );
			if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
				$this->mLoadMonitorClass = 'LoadMonitor_MySQL';
			} else {
				$this->mLoadMonitorClass = 'LoadMonitor_Null';
			}
		}

		foreach( $params['servers'] as $i => $server ) {
			$this->mLoads[$i] = $server['load'];
			if ( isset( $server['groupLoads'] ) ) {
				foreach ( $server['groupLoads'] as $group => $ratio ) {
					if ( !isset( $this->mGroupLoads[$group] ) ) {
						$this->mGroupLoads[$group] = array();
					}
					$this->mGroupLoads[$group][$i] = $ratio;
				}
			}
		}
	}

	/**
	 * Get a LoadMonitor instance
	 *
	 * @return LoadMonitor
	 */
	function getLoadMonitor() {
		if ( !isset( $this->mLoadMonitor ) ) {
			$class = $this->mLoadMonitorClass;
			$this->mLoadMonitor = new $class( $this );
		}
		return $this->mLoadMonitor;
	}

	/**
	 * Get or set arbitrary data used by the parent object, usually an LBFactory
	 * @param $x
	 * @return Mixed
	 */
	function parentInfo( $x = null ) {
		return wfSetVar( $this->mParentInfo, $x );
	}

	/**
	 * Given an array of non-normalised probabilities, this function will select
	 * an element and return the appropriate key
	 *
	 * @deprecated 1.21, use ArrayUtils::pickRandom()
	 *
	 * @param $weights array
	 *
	 * @return bool|int|string
	 */
	function pickRandom( $weights ) {
		return ArrayUtils::pickRandom( $weights );
	}

	/**
	 * @param $loads array
	 * @param $wiki bool
	 * @return bool|int|string
	 */
	function getRandomNonLagged( $loads, $wiki = false ) {
		# Unset excessively lagged servers
		$lags = $this->getLagTimes( $wiki );
		foreach ( $lags as $i => $lag ) {
			if ( $i != 0 ) {
				if ( $lag === false ) {
					wfDebugLog( 'replication', "Server #$i is not replicating\n" );
					unset( $loads[$i] );
				} elseif ( isset( $this->mServers[$i]['max lag'] ) && $lag > $this->mServers[$i]['max lag'] ) {
					wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)\n" );
					unset( $loads[$i] );
				}
			}
		}

		# Find out if all the slaves with non-zero load are lagged
		$sum = 0;
		foreach ( $loads as $load ) {
			$sum += $load;
		}
		if ( $sum == 0 ) {
			# No appropriate DB servers except maybe the master and some slaves with zero load
			# Do NOT use the master
			# Instead, this function will return false, triggering read-only mode,
			# and a lagged slave will be used instead.
			return false;
		}

		if ( count( $loads ) == 0 ) {
			return false;
		}

		#wfDebugLog( 'connect', var_export( $loads, true ) );

		# Return a random representative of the remainder
		return $this->pickRandom( $loads );
	}

	/**
	 * Get the index of the reader connection, which may be a slave
	 * This takes into account load ratios and lag times. It should
	 * always return a consistent index during a given invocation
	 *
	 * Side effect: opens connections to databases
	 * @param $group bool
	 * @param $wiki bool
	 * @throws MWException
	 * @return bool|int|string
	 */
	function getReaderIndex( $group = false, $wiki = false ) {
		global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;

		# @todo FIXME: For now, only go through all this for mysql databases
		if ( $wgDBtype != 'mysql' ) {
			return $this->getWriterIndex();
		}

		if ( count( $this->mServers ) == 1 ) {
			# Skip the load balancing if there's only one server
			return 0;
		} elseif ( $group === false and $this->mReadIndex >= 0 ) {
			# Shortcut if generic reader exists already
			return $this->mReadIndex;
		}

		wfProfileIn( __METHOD__ );

		$totalElapsed = 0;

		# convert from seconds to microseconds
		$timeout = $wgDBClusterTimeout * 1e6;

		# Find the relevant load array
		if ( $group !== false ) {
			if ( isset( $this->mGroupLoads[$group] ) ) {
				$nonErrorLoads = $this->mGroupLoads[$group];
			} else {
				# No loads for this group, return false and the caller can use some other group
				wfDebug( __METHOD__ . ": no loads for group $group\n" );
				wfProfileOut( __METHOD__ );
				return false;
			}
		} else {
			$nonErrorLoads = $this->mLoads;
		}

		if ( !$nonErrorLoads ) {
			throw new MWException( "Empty server array given to LoadBalancer" );
		}

		# Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
		$this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );

		$laggedSlaveMode = false;

		# First try quickly looking through the available servers for a server that
		# meets our criteria
		do {
			$totalThreadsConnected = 0;
			$overloadedServers = 0;
			$currentLoads = $nonErrorLoads;
			while ( count( $currentLoads ) ) {
				if ( $wgReadOnly || $this->mAllowLagged || $laggedSlaveMode ) {
					$i = $this->pickRandom( $currentLoads );
				} else {
					$i = $this->getRandomNonLagged( $currentLoads, $wiki );
					if ( $i === false && count( $currentLoads ) != 0 ) {
						# All slaves lagged. Switch to read-only mode
						wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode\n" );
						$wgReadOnly = 'The database has been automatically locked ' .
							'while the slave database servers catch up to the master';
						$i = $this->pickRandom( $currentLoads );
						$laggedSlaveMode = true;
					}
				}

				if ( $i === false ) {
					# pickRandom() returned false
					# This is permanent and means the configuration or the load monitor
					# wants us to return false.
					wfDebugLog( 'connect', __METHOD__ . ": pickRandom() returned false\n" );
					wfProfileOut( __METHOD__ );
					return false;
				}

				wfDebugLog( 'connect', __METHOD__ . ": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
				$conn = $this->openConnection( $i, $wiki );

				if ( !$conn ) {
					wfDebugLog( 'connect', __METHOD__ . ": Failed connecting to $i/$wiki\n" );
					unset( $nonErrorLoads[$i] );
					unset( $currentLoads[$i] );
					continue;
				}

				// Perform post-connection backoff
				$threshold = isset( $this->mServers[$i]['max threads'] )
					? $this->mServers[$i]['max threads'] : false;
				$backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );

				// Decrement reference counter, we are finished with this connection.
				// It will be incremented for the caller later.
				if ( $wiki !== false ) {
					$this->reuseConnection( $conn );
				}

				if ( $backoff ) {
					# Post-connection overload, don't use this server for now
					$totalThreadsConnected += $backoff;
					$overloadedServers++;
					unset( $currentLoads[$i] );
				} else {
					# Return this server
					break 2;
				}
			}

			# No server found yet
			$i = false;

			# If all servers were down, quit now
			if ( !count( $nonErrorLoads ) ) {
				wfDebugLog( 'connect', "All servers down\n" );
				break;
			}

			# Some servers must have been overloaded
			if ( $overloadedServers == 0 ) {
				throw new MWException( __METHOD__ . ": unexpectedly found no overloaded servers" );
			}
			# Back off for a while
			# Scale the sleep time by the number of connected threads, to produce a
			# roughly constant global poll rate
			$avgThreads = $totalThreadsConnected / $overloadedServers;
			$totalElapsed += $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
		} while ( $totalElapsed < $timeout );

		if ( $totalElapsed >= $timeout ) {
			wfDebugLog( 'connect', "All servers busy\n" );
			$this->mErrorConnection = false;
			$this->mLastError = 'All servers busy';
		}

		if ( $i !== false ) {
			# Slave connection successful
			# Wait for the session master pos for a short time
			if ( $this->mWaitForPos && $i > 0 ) {
				if ( !$this->doWait( $i ) ) {
					$this->mServers[$i]['slave pos'] = $conn->getSlavePos();
				}
			}
			if ( $this->mReadIndex <= 0 && $this->mLoads[$i] > 0 && $i !== false ) {
				$this->mReadIndex = $i;
			}
		}
		wfProfileOut( __METHOD__ );
		return $i;
	}

	/**
	 * Wait for a specified number of microseconds, and return the period waited
	 * @param $t int
	 * @return int
	 */
	function sleep( $t ) {
		wfProfileIn( __METHOD__ );
		wfDebug( __METHOD__ . ": waiting $t us\n" );
		usleep( $t );
		wfProfileOut( __METHOD__ );
		return $t;
	}

	/**
	 * Set the master wait position
	 * If a DB_SLAVE connection has been opened already, waits
	 * Otherwise sets a variable telling it to wait if such a connection is opened
	 * @param $pos int
	 */
	public function waitFor( $pos ) {
		wfProfileIn( __METHOD__ );
		$this->mWaitForPos = $pos;
		$i = $this->mReadIndex;

		if ( $i > 0 ) {
			if ( !$this->doWait( $i ) ) {
				$this->mServers[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
				$this->mLaggedSlaveMode = true;
			}
		}
		wfProfileOut( __METHOD__ );
	}

	/**
	 * Set the master wait position and wait for ALL slaves to catch up to it
	 * @param $pos int
	 */
	public function waitForAll( $pos ) {
		wfProfileIn( __METHOD__ );
		$this->mWaitForPos = $pos;
		for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
			$this->doWait( $i, true );
		}
		wfProfileOut( __METHOD__ );
	}

	/**
	 * Get any open connection to a given server index, local or foreign
	 * Returns false if there is no connection open
	 *
	 * @param $i int
	 * @return DatabaseBase|bool False on failure
	 */
	function getAnyOpenConnection( $i ) {
		foreach ( $this->mConns as $conns ) {
			if ( !empty( $conns[$i] ) ) {
				return reset( $conns[$i] );
			}
		}
		return false;
	}

	/**
	 * Wait for a given slave to catch up to the master pos stored in $this
	 * @param $index
	 * @param $open bool
	 * @return bool
	 */
	function doWait( $index, $open = false ) {
		# Find a connection to wait on
		$conn = $this->getAnyOpenConnection( $index );
		if ( !$conn ) {
			if ( !$open ) {
				wfDebug( __METHOD__ . ": no connection open\n" );
				return false;
			} else {
				$conn = $this->openConnection( $index );
				if ( !$conn ) {
					wfDebug( __METHOD__ . ": failed to open connection\n" );
					return false;
				}
			}
		}

		wfDebug( __METHOD__ . ": Waiting for slave #$index to catch up...\n" );
		$result = $conn->masterPosWait( $this->mWaitForPos, $this->mWaitTimeout );

		if ( $result == -1 || is_null( $result ) ) {
			# Timed out waiting for slave, use master instead
			wfDebug( __METHOD__ . ": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
			return false;
		} else {
			wfDebug( __METHOD__ . ": Done\n" );
			return true;
		}
	}

	/**
	 * Get a connection by index
	 * This is the main entry point for this class.
	 *
	 * @param $i Integer: server index
	 * @param array $groups query groups
	 * @param bool|string $wiki Wiki ID
	 *
	 * @throws MWException
	 * @return DatabaseBase
	 */
	public function &getConnection( $i, $groups = array(), $wiki = false ) {
		wfProfileIn( __METHOD__ );

		if ( $i == DB_LAST ) {
			throw new MWException( 'Attempt to call ' . __METHOD__ . ' with deprecated server index DB_LAST' );
		} elseif ( $i === null || $i === false ) {
			throw new MWException( 'Attempt to call ' . __METHOD__ . ' with invalid server index' );
		}

		if ( $wiki === wfWikiID() ) {
			$wiki = false;
		}

		# Query groups
		if ( $i == DB_MASTER ) {
			$i = $this->getWriterIndex();
		} elseif ( !is_array( $groups ) ) {
			$groupIndex = $this->getReaderIndex( $groups, $wiki );
			if ( $groupIndex !== false ) {
				$serverName = $this->getServerName( $groupIndex );
				wfDebug( __METHOD__ . ": using server $serverName for group $groups\n" );
				$i = $groupIndex;
			}
		} else {
			foreach ( $groups as $group ) {
				$groupIndex = $this->getReaderIndex( $group, $wiki );
				if ( $groupIndex !== false ) {
					$serverName = $this->getServerName( $groupIndex );
					wfDebug( __METHOD__ . ": using server $serverName for group $group\n" );
					$i = $groupIndex;
					break;
				}
			}
		}

		# Operation-based index
		if ( $i == DB_SLAVE ) {
			$i = $this->getReaderIndex( false, $wiki );
			# Couldn't find a working server in getReaderIndex()?
			if ( $i === false ) {
				$this->mLastError = 'No working slave server: ' . $this->mLastError;
				wfProfileOut( __METHOD__ );
				return $this->reportConnectionError();
			}
		}

		# Now we have an explicit index into the servers array
		$conn = $this->openConnection( $i, $wiki );
		if ( !$conn ) {
			wfProfileOut( __METHOD__ );
			return $this->reportConnectionError();
		}

		wfProfileOut( __METHOD__ );
		return $conn;
	}

	/**
	 * Mark a foreign connection as being available for reuse under a different
	 * DB name or prefix. This mechanism is reference-counted, and must be called
	 * the same number of times as getConnection() to work.
	 *
	 * @param DatabaseBase $conn
	 * @throws MWException
	 */
	public function reuseConnection( $conn ) {
		$serverIndex = $conn->getLBInfo( 'serverIndex' );
		$refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
		$dbName = $conn->getDBname();
		$prefix = $conn->tablePrefix();
		if ( strval( $prefix ) !== '' ) {
			$wiki = "$dbName-$prefix";
		} else {
			$wiki = $dbName;
		}
		if ( $serverIndex === null || $refCount === null ) {
			wfDebug( __METHOD__ . ": this connection was not opened as a foreign connection\n" );
			/**
			 * This can happen in code like:
			 *   foreach ( $dbs as $db ) {
			 *     $conn = $lb->getConnection( DB_SLAVE, array(), $db );
			 *     ...
			 *     $lb->reuseConnection( $conn );
			 *   }
			 * When a connection to the local DB is opened in this way, reuseConnection()
			 * should be ignored
			 */
			return;
		}
		if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
			throw new MWException( __METHOD__ . ": connection not found, has the connection been freed already?" );
		}
		$conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
		if ( $refCount <= 0 ) {
			$this->mConns['foreignFree'][$serverIndex][$wiki] = $conn;
			unset( $this->mConns['foreignUsed'][$serverIndex][$wiki] );
			wfDebug( __METHOD__ . ": freed connection $serverIndex/$wiki\n" );
		} else {
			wfDebug( __METHOD__ . ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
		}
	}

	/**
	 * Open a connection to the server given by the specified index
	 * Index must be an actual index into the array.
	 * If the server is already open, returns it.
	 *
	 * On error, returns false, and the connection which caused the
	 * error will be available via $this->mErrorConnection.
	 *
	 * @param $i Integer server index
	 * @param string $wiki wiki ID to open
	 * @return DatabaseBase
	 *
	 * @access private
	 */
	function openConnection( $i, $wiki = false ) {
		wfProfileIn( __METHOD__ );
		if ( $wiki !== false ) {
			$conn = $this->openForeignConnection( $i, $wiki );
			wfProfileOut( __METHOD__ );
			return $conn;
		}
		if ( isset( $this->mConns['local'][$i][0] ) ) {
			$conn = $this->mConns['local'][$i][0];
		} else {
			$server = $this->mServers[$i];
			$server['serverIndex'] = $i;
			$conn = $this->reallyOpenConnection( $server, false );
			if ( $conn->isOpen() ) {
				wfDebug( "Connected to database $i at {$this->mServers[$i]['host']}\n" );
				$this->mConns['local'][$i][0] = $conn;
			} else {
				wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
				$this->mErrorConnection = $conn;
				$conn = false;
			}
		}
		wfProfileOut( __METHOD__ );
		return $conn;
	}

	/**
	 * Open a connection to a foreign DB, or return one if it is already open.
	 *
	 * Increments a reference count on the returned connection which locks the
	 * connection to the requested wiki. This reference count can be
	 * decremented by calling reuseConnection().
	 *
	 * If a connection is open to the appropriate server already, but with the wrong
	 * database, it will be switched to the right database and returned, as long as
	 * it has been freed first with reuseConnection().
	 *
	 * On error, returns false, and the connection which caused the
	 * error will be available via $this->mErrorConnection.
	 *
	 * @param $i Integer: server index
	 * @param string $wiki wiki ID to open
	 * @return DatabaseBase
	 */
	function openForeignConnection( $i, $wiki ) {
		wfProfileIn( __METHOD__ );
		list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
		if ( isset( $this->mConns['foreignUsed'][$i][$wiki] ) ) {
			// Reuse an already-used connection
			$conn = $this->mConns['foreignUsed'][$i][$wiki];
			wfDebug( __METHOD__ . ": reusing connection $i/$wiki\n" );
		} elseif ( isset( $this->mConns['foreignFree'][$i][$wiki] ) ) {
			// Reuse a free connection for the same wiki
			$conn = $this->mConns['foreignFree'][$i][$wiki];
			unset( $this->mConns['foreignFree'][$i][$wiki] );
			$this->mConns['foreignUsed'][$i][$wiki] = $conn;
			wfDebug( __METHOD__ . ": reusing free connection $i/$wiki\n" );
		} elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
			// Reuse a connection from another wiki
			$conn = reset( $this->mConns['foreignFree'][$i] );
			$oldWiki = key( $this->mConns['foreignFree'][$i] );

			if ( !$conn->selectDB( $dbName ) ) {
				$this->mLastError = "Error selecting database $dbName on server " .
					$conn->getServer() . " from client host " . wfHostname() . "\n";
				$this->mErrorConnection = $conn;
				$conn = false;
			} else {
				$conn->tablePrefix( $prefix );
				unset( $this->mConns['foreignFree'][$i][$oldWiki] );
				$this->mConns['foreignUsed'][$i][$wiki] = $conn;
				wfDebug( __METHOD__ . ": reusing free connection from $oldWiki for $wiki\n" );
			}
		} else {
			// Open a new connection
			$server = $this->mServers[$i];
			$server['serverIndex'] = $i;
			$server['foreignPoolRefCount'] = 0;
			$conn = $this->reallyOpenConnection( $server, $dbName );
			if ( !$conn->isOpen() ) {
				wfDebug( __METHOD__ . ": error opening connection for $i/$wiki\n" );
				$this->mErrorConnection = $conn;
				$conn = false;
			} else {
				$conn->tablePrefix( $prefix );
				$this->mConns['foreignUsed'][$i][$wiki] = $conn;
				wfDebug( __METHOD__ . ": opened new connection for $i/$wiki\n" );
			}
		}

		// Increment reference count
		if ( $conn ) {
			$refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
			$conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
		}
		wfProfileOut( __METHOD__ );
		return $conn;
	}

	/**
	 * Test if the specified index represents an open connection
	 *
	 * @param $index Integer: server index
	 * @access private
	 * @return bool
	 */
	function isOpen( $index ) {
		if( !is_integer( $index ) ) {
			return false;
		}
		return (bool)$this->getAnyOpenConnection( $index );
	}

	/**
	 * Really opens a connection. Uncached.
	 * Returns a Database object whether or not the connection was successful.
	 * @access private
	 *
	 * @param $server
	 * @param $dbNameOverride bool
	 * @throws MWException
	 * @return DatabaseBase
	 */
	function reallyOpenConnection( $server, $dbNameOverride = false ) {
		if( !is_array( $server ) ) {
			throw new MWException( 'You must update your load-balancing configuration. ' .
				'See DefaultSettings.php entry for $wgDBservers.' );
		}

		if ( $dbNameOverride !== false ) {
			$server['dbname'] = $dbNameOverride;
		}

		# Create object
		try {
			$db = DatabaseBase::factory( $server['type'], $server );
		} catch ( DBConnectionError $e ) {
			// FIXME: This is probably the ugliest thing I have ever done to
			// PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
			$db = $e->db;
		}

		$db->setLBInfo( $server );
		if ( isset( $server['fakeSlaveLag'] ) ) {
			$db->setFakeSlaveLag( $server['fakeSlaveLag'] );
		}
		if ( isset( $server['fakeMaster'] ) ) {
			$db->setFakeMaster( true );
		}
		return $db;
	}

	/**
	 * @throws DBConnectionError
	 * @return bool
	 */
	private function reportConnectionError() {
		$conn = $this->mErrorConnection; // The connection which caused the error

		if ( !is_object( $conn ) ) {
			// No last connection, probably due to all servers being too busy
			wfLogDBError( "LB failure with no last connection. Connection error: {$this->mLastError}\n" );

			// If all servers were busy, mLastError will contain something sensible
			throw new DBConnectionError( null, $this->mLastError );
		} else {
			$server = $conn->getProperty( 'mServer' );
			wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
			$conn->reportConnectionError( "{$this->mLastError} ({$server})" ); // throws DBConnectionError
		}
		return false; /* not reached */
	}

	/**
	 * @return int
	 */
	function getWriterIndex() {
		return 0;
	}

	/**
	 * Returns true if the specified index is a valid server index
	 *
	 * @param $i
	 * @return bool
	 */
	function haveIndex( $i ) {
		return array_key_exists( $i, $this->mServers );
	}

	/**
	 * Returns true if the specified index is valid and has non-zero load
	 *
	 * @param $i
	 * @return bool
	 */
	function isNonZeroLoad( $i ) {
		return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
	}

	/**
	 * Get the number of defined servers (not the number of open connections)
	 *
	 * @return int
	 */
	function getServerCount() {
		return count( $this->mServers );
	}

	/**
	 * Get the host name or IP address of the server with the specified index
	 * Prefer a readable name if available.
	 * @param $i
	 * @return string
	 */
	function getServerName( $i ) {
		if ( isset( $this->mServers[$i]['hostName'] ) ) {
			return $this->mServers[$i]['hostName'];
		} elseif ( isset( $this->mServers[$i]['host'] ) ) {
			return $this->mServers[$i]['host'];
		} else {
			return '';
		}
	}

	/**
	 * Return the server info structure for a given index, or false if the index is invalid.
	 * @param $i
	 * @return bool
	 */
	function getServerInfo( $i ) {
		if ( isset( $this->mServers[$i] ) ) {
			return $this->mServers[$i];
		} else {
			return false;
		}
	}

	/**
	 * Sets the server info structure for the given index. Entry at index $i is created if it doesn't exist
	 * @param $i
	 * @param $serverInfo
	 */
	function setServerInfo( $i, $serverInfo ) {
		$this->mServers[$i] = $serverInfo;
	}

	/**
	 * Get the current master position for chronology control purposes
	 * @return mixed
	 */
	function getMasterPos() {
		# If this entire request was served from a slave without opening a connection to the
		# master (however unlikely that may be), then we can fetch the position from the slave.
		$masterConn = $this->getAnyOpenConnection( 0 );
		if ( !$masterConn ) {
			for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
				$conn = $this->getAnyOpenConnection( $i );
				if ( $conn ) {
					wfDebug( "Master pos fetched from slave\n" );
					return $conn->getSlavePos();
				}
			}
		} else {
			wfDebug( "Master pos fetched from master\n" );
			return $masterConn->getMasterPos();
		}
		return false;
	}

	/**
	 * Close all open connections
	 */
	function closeAll() {
		foreach ( $this->mConns as $conns2 ) {
			foreach  ( $conns2 as $conns3 ) {
				foreach ( $conns3 as $conn ) {
					$conn->close();
				}
			}
		}
		$this->mConns = array(
			'local' => array(),
			'foreignFree' => array(),
			'foreignUsed' => array(),
		);
	}

	/**
	 * Deprecated function, typo in function name
	 *
	 * @deprecated in 1.18
	 * @param $conn
	 */
	function closeConnecton( $conn ) {
		wfDeprecated( __METHOD__, '1.18' );
		$this->closeConnection( $conn );
	}

	/**
	 * Close a connection
	 * Using this function makes sure the LoadBalancer knows the connection is closed.
	 * If you use $conn->close() directly, the load balancer won't update its state.
	 * @param $conn DatabaseBase
	 */
	function closeConnection( $conn ) {
		$done = false;
		foreach ( $this->mConns as $i1 => $conns2 ) {
			foreach ( $conns2 as $i2 => $conns3 ) {
				foreach ( $conns3 as $i3 => $candidateConn ) {
					if ( $conn === $candidateConn ) {
						$conn->close();
						unset( $this->mConns[$i1][$i2][$i3] );
						$done = true;
						break;
					}
				}
			}
		}
		if ( !$done ) {
			$conn->close();
		}
	}

	/**
	 * Commit transactions on all open connections
	 */
	function commitAll() {
		foreach ( $this->mConns as $conns2 ) {
			foreach ( $conns2 as $conns3 ) {
				foreach ( $conns3 as $conn ) {
					if ( $conn->trxLevel() ) {
						$conn->commit( __METHOD__, 'flush' );
					}
				}
			}
		}
	}

	/**
	 *  Issue COMMIT only on master, only if queries were done on connection
	 */
	function commitMasterChanges() {
		// Always 0, but who knows.. :)
		$masterIndex = $this->getWriterIndex();
		foreach ( $this->mConns as $conns2 ) {
			if ( empty( $conns2[$masterIndex] ) ) {
				continue;
			}
			foreach ( $conns2[$masterIndex] as $conn ) {
				if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
					$conn->commit( __METHOD__, 'flush' );
				}
			}
		}
	}

	/**
	 * @param $value null
	 * @return Mixed
	 */
	function waitTimeout( $value = null ) {
		return wfSetVar( $this->mWaitTimeout, $value );
	}

	/**
	 * @return bool
	 */
	function getLaggedSlaveMode() {
		return $this->mLaggedSlaveMode;
	}

	/**
	 * Disables/enables lag checks
	 * @param $mode null
	 * @return bool
	 */
	function allowLagged( $mode = null ) {
		if ( $mode === null ) {
			return $this->mAllowLagged;
		}
		$this->mAllowLagged = $mode;
		return $this->mAllowLagged;
	}

	/**
	 * @return bool
	 */
	function pingAll() {
		$success = true;
		foreach ( $this->mConns as $conns2 ) {
			foreach ( $conns2 as $conns3 ) {
				foreach ( $conns3 as $conn ) {
					if ( !$conn->ping() ) {
						$success = false;
					}
				}
			}
		}
		return $success;
	}

	/**
	 * Call a function with each open connection object
	 * @param $callback
	 * @param array $params
	 */
	function forEachOpenConnection( $callback, $params = array() ) {
		foreach ( $this->mConns as $conns2 ) {
			foreach ( $conns2 as $conns3 ) {
				foreach ( $conns3 as $conn ) {
					$mergedParams = array_merge( array( $conn ), $params );
					call_user_func_array( $callback, $mergedParams );
				}
			}
		}
	}

	/**
	 * Get the hostname and lag time of the most-lagged slave.
	 * This is useful for maintenance scripts that need to throttle their updates.
	 * May attempt to open connections to slaves on the default DB. If there is
	 * no lag, the maximum lag will be reported as -1.
	 *
	 * @param string $wiki Wiki ID, or false for the default database
	 *
	 * @return array ( host, max lag, index of max lagged host )
	 */
	function getMaxLag( $wiki = false ) {
		$maxLag = -1;
		$host = '';
		$maxIndex = 0;
		if ( $this->getServerCount() > 1 ) { // no replication = no lag
			foreach ( $this->mServers as $i => $conn ) {
				$conn = false;
				if ( $wiki === false ) {
					$conn = $this->getAnyOpenConnection( $i );
				}
				if ( !$conn ) {
					$conn = $this->openConnection( $i, $wiki );
				}
				if ( !$conn ) {
					continue;
				}
				$lag = $conn->getLag();
				if ( $lag > $maxLag ) {
					$maxLag = $lag;
					$host = $this->mServers[$i]['host'];
					$maxIndex = $i;
				}
			}
		}
		return array( $host, $maxLag, $maxIndex );
	}

	/**
	 * Get lag time for each server
	 * Results are cached for a short time in memcached, and indefinitely in the process cache
	 *
	 * @param $wiki
	 *
	 * @return array
	 */
	function getLagTimes( $wiki = false ) {
		# Try process cache
		if ( isset( $this->mLagTimes ) ) {
			return $this->mLagTimes;
		}
		if ( $this->getServerCount() == 1 ) {
			# No replication
			$this->mLagTimes = array( 0 => 0 );
		} else {
			# Send the request to the load monitor
			$this->mLagTimes = $this->getLoadMonitor()->getLagTimes(
				array_keys( $this->mServers ), $wiki );
		}
		return $this->mLagTimes;
	}

	/**
	 * Get the lag in seconds for a given connection, or zero if this load
	 * balancer does not have replication enabled.
	 *
	 * This should be used in preference to Database::getLag() in cases where
	 * replication may not be in use, since there is no way to determine if
	 * replication is in use at the connection level without running
	 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
	 * function instead of Database::getLag() avoids a fatal error in this
	 * case on many installations.
	 *
	 * @param $conn DatabaseBase
	 *
	 * @return int
	 */
	function safeGetLag( $conn ) {
		if ( $this->getServerCount() == 1 ) {
			return 0;
		} else {
			return $conn->getLag();
		}
	}

	/**
	 * Clear the cache for getLagTimes
	 */
	function clearLagTimeCache() {
		$this->mLagTimes = null;
	}
}