]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/db/LoadBalancer.php
MediaWiki 1.17.0
[autoinstallsdev/mediawiki.git] / includes / db / LoadBalancer.php
1 <?php
2 /**
3  * Database load balancing
4  *
5  * @file
6  * @ingroup Database
7  */
8
9 /**
10  * Database load balancing object
11  *
12  * @todo document
13  * @ingroup Database
14  */
15 class LoadBalancer {
16         /* private */ var $mServers, $mConns, $mLoads, $mGroupLoads;
17         /* private */ var $mErrorConnection;
18         /* private */ var $mReadIndex, $mAllowLagged;
19         /* private */ var $mWaitForPos, $mWaitTimeout;
20         /* private */ var $mLaggedSlaveMode, $mLastError = 'Unknown error';
21         /* private */ var $mParentInfo, $mLagTimes;
22         /* private */ var $mLoadMonitorClass, $mLoadMonitor;
23
24         /**
25          * @param $params Array with keys:
26          *    servers           Required. Array of server info structures.
27          *    masterWaitTimeout Replication lag wait timeout
28          *    loadMonitor       Name of a class used to fetch server lag and load.
29          */
30         function __construct( $params )
31         {
32                 if ( !isset( $params['servers'] ) ) {
33                         throw new MWException( __CLASS__.': missing servers parameter' );
34                 }
35                 $this->mServers = $params['servers'];
36
37                 if ( isset( $params['waitTimeout'] ) ) {
38                         $this->mWaitTimeout = $params['waitTimeout'];
39                 } else {
40                         $this->mWaitTimeout = 10;
41                 }
42
43                 $this->mReadIndex = -1;
44                 $this->mWriteIndex = -1;
45                 $this->mConns = array(
46                         'local' => array(),
47                         'foreignUsed' => array(),
48                         'foreignFree' => array() );
49                 $this->mLoads = array();
50                 $this->mWaitForPos = false;
51                 $this->mLaggedSlaveMode = false;
52                 $this->mErrorConnection = false;
53                 $this->mAllowLagged = false;
54                 $this->mLoadMonitorClass = isset( $params['loadMonitor'] ) 
55                         ? $params['loadMonitor'] : 'LoadMonitor_MySQL';
56
57                 foreach( $params['servers'] as $i => $server ) {
58                         $this->mLoads[$i] = $server['load'];
59                         if ( isset( $server['groupLoads'] ) ) {
60                                 foreach ( $server['groupLoads'] as $group => $ratio ) {
61                                         if ( !isset( $this->mGroupLoads[$group] ) ) {
62                                                 $this->mGroupLoads[$group] = array();
63                                         }
64                                         $this->mGroupLoads[$group][$i] = $ratio;
65                                 }
66                         }
67                 }
68         }
69
70         /**
71          * Get a LoadMonitor instance
72          */
73         function getLoadMonitor() {
74                 if ( !isset( $this->mLoadMonitor ) ) {
75                         $class = $this->mLoadMonitorClass;
76                         $this->mLoadMonitor = new $class( $this );
77                 }
78                 return $this->mLoadMonitor;
79         }
80
81         /**
82          * Get or set arbitrary data used by the parent object, usually an LBFactory
83          */
84         function parentInfo( $x = null ) {
85                 return wfSetVar( $this->mParentInfo, $x );
86         }
87
88         /**
89          * Given an array of non-normalised probabilities, this function will select
90          * an element and return the appropriate key
91          */
92         function pickRandom( $weights )
93         {
94                 if ( !is_array( $weights ) || count( $weights ) == 0 ) {
95                         return false;
96                 }
97
98                 $sum = array_sum( $weights );
99                 if ( $sum == 0 ) {
100                         # No loads on any of them
101                         # In previous versions, this triggered an unweighted random selection,
102                         # but this feature has been removed as of April 2006 to allow for strict
103                         # separation of query groups.
104                         return false;
105                 }
106                 $max = mt_getrandmax();
107                 $rand = mt_rand(0, $max) / $max * $sum;
108
109                 $sum = 0;
110                 foreach ( $weights as $i => $w ) {
111                         $sum += $w;
112                         if ( $sum >= $rand ) {
113                                 break;
114                         }
115                 }
116                 return $i;
117         }
118
119         function getRandomNonLagged( $loads, $wiki = false ) {
120                 # Unset excessively lagged servers
121                 $lags = $this->getLagTimes( $wiki );
122                 foreach ( $lags as $i => $lag ) {
123                         if ( $i != 0 ) {
124                                 if ( $lag === false ) {
125                                         wfDebug( "Server #$i is not replicating\n" );
126                                         unset( $loads[$i] );
127                                 } elseif ( isset( $this->mServers[$i]['max lag'] ) && $lag > $this->mServers[$i]['max lag'] ) {
128                                         wfDebug( "Server #$i is excessively lagged ($lag seconds)\n" );
129                                         unset( $loads[$i] );
130                                 }
131                         }
132                 }
133
134                 # Find out if all the slaves with non-zero load are lagged
135                 $sum = 0;
136                 foreach ( $loads as $load ) {
137                         $sum += $load;
138                 }
139                 if ( $sum == 0 ) {
140                         # No appropriate DB servers except maybe the master and some slaves with zero load
141                         # Do NOT use the master
142                         # Instead, this function will return false, triggering read-only mode,
143                         # and a lagged slave will be used instead.
144                         return false;
145                 }
146
147                 if ( count( $loads ) == 0 ) {
148                         return false;
149                 }
150
151                 #wfDebugLog( 'connect', var_export( $loads, true ) );
152
153                 # Return a random representative of the remainder
154                 return $this->pickRandom( $loads );
155         }
156
157         /**
158          * Get the index of the reader connection, which may be a slave
159          * This takes into account load ratios and lag times. It should
160          * always return a consistent index during a given invocation
161          *
162          * Side effect: opens connections to databases
163          */
164         function getReaderIndex( $group = false, $wiki = false ) {
165                 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
166
167                 # FIXME: For now, only go through all this for mysql databases
168                 if ($wgDBtype != 'mysql') {
169                         return $this->getWriterIndex();
170                 }
171
172                 if ( count( $this->mServers ) == 1 )  {
173                         # Skip the load balancing if there's only one server
174                         return 0;
175                 } elseif ( $group === false and $this->mReadIndex >= 0 ) {
176                         # Shortcut if generic reader exists already
177                         return $this->mReadIndex;
178                 }
179
180                 wfProfileIn( __METHOD__ );
181
182                 $totalElapsed = 0;
183
184                 # convert from seconds to microseconds
185                 $timeout = $wgDBClusterTimeout * 1e6;
186
187                 # Find the relevant load array
188                 if ( $group !== false ) {
189                         if ( isset( $this->mGroupLoads[$group] ) ) {
190                                 $nonErrorLoads = $this->mGroupLoads[$group];
191                         } else {
192                                 # No loads for this group, return false and the caller can use some other group
193                                 wfDebug( __METHOD__.": no loads for group $group\n" );
194                                 wfProfileOut( __METHOD__ );
195                                 return false;
196                         }
197                 } else {
198                         $nonErrorLoads = $this->mLoads;
199                 }
200
201                 if ( !$nonErrorLoads ) {
202                         throw new MWException( "Empty server array given to LoadBalancer" );
203                 }
204
205                 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
206                 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
207
208                 $laggedSlaveMode = false;
209
210                 # First try quickly looking through the available servers for a server that
211                 # meets our criteria
212                 do {
213                         $totalThreadsConnected = 0;
214                         $overloadedServers = 0;
215                         $currentLoads = $nonErrorLoads;
216                         while ( count( $currentLoads ) ) {
217                                 if ( $wgReadOnly || $this->mAllowLagged || $laggedSlaveMode ) {
218                                         $i = $this->pickRandom( $currentLoads );
219                                 } else {
220                                         $i = $this->getRandomNonLagged( $currentLoads, $wiki );
221                                         if ( $i === false && count( $currentLoads ) != 0 )  {
222                                                 # All slaves lagged. Switch to read-only mode
223                                                 $wgReadOnly = 'The database has been automatically locked ' . 
224                                                         'while the slave database servers catch up to the master';
225                                                 $i = $this->pickRandom( $currentLoads );
226                                                 $laggedSlaveMode = true;
227                                         }
228                                 }
229
230                                 if ( $i === false ) {
231                                         # pickRandom() returned false
232                                         # This is permanent and means the configuration or the load monitor 
233                                         # wants us to return false.
234                                         wfDebugLog( 'connect', __METHOD__.": pickRandom() returned false\n" );
235                                         wfProfileOut( __METHOD__ );
236                                         return false;
237                                 }
238
239                                 wfDebugLog( 'connect', __METHOD__.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
240                                 $conn = $this->openConnection( $i, $wiki );
241
242                                 if ( !$conn ) {
243                                         wfDebugLog( 'connect', __METHOD__.": Failed connecting to $i/$wiki\n" );
244                                         unset( $nonErrorLoads[$i] );
245                                         unset( $currentLoads[$i] );
246                                         continue;
247                                 }
248
249                                 // Perform post-connection backoff
250                                 $threshold = isset( $this->mServers[$i]['max threads'] ) 
251                                         ? $this->mServers[$i]['max threads'] : false;
252                                 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
253
254                                 // Decrement reference counter, we are finished with this connection.
255                                 // It will be incremented for the caller later.
256                                 if ( $wiki !== false ) {
257                                         $this->reuseConnection( $conn );
258                                 }
259                                 
260                                 if ( $backoff ) {
261                                         # Post-connection overload, don't use this server for now
262                                         $totalThreadsConnected += $backoff;
263                                         $overloadedServers++;
264                                         unset( $currentLoads[$i] );
265                                 } else {
266                                         # Return this server
267                                         break 2;
268                                 }
269                         }
270
271                         # No server found yet
272                         $i = false;
273
274                         # If all servers were down, quit now
275                         if ( !count( $nonErrorLoads ) ) {
276                                 wfDebugLog( 'connect', "All servers down\n" );
277                                 break;
278                         }
279
280                         # Some servers must have been overloaded
281                         if ( $overloadedServers == 0 ) {
282                                 throw new MWException( __METHOD__.": unexpectedly found no overloaded servers" );
283                         }
284                         # Back off for a while
285                         # Scale the sleep time by the number of connected threads, to produce a
286                         # roughly constant global poll rate
287                         $avgThreads = $totalThreadsConnected / $overloadedServers;
288                         $totalElapsed += $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
289                 } while ( $totalElapsed < $timeout );
290
291                 if ( $totalElapsed >= $timeout ) {
292                         wfDebugLog( 'connect', "All servers busy\n" );
293                         $this->mErrorConnection = false;
294                         $this->mLastError = 'All servers busy';
295                 }
296
297                 if ( $i !== false ) {
298                         # Slave connection successful
299                         # Wait for the session master pos for a short time
300                         if ( $this->mWaitForPos && $i > 0 ) {
301                                 if ( !$this->doWait( $i ) ) {
302                                         $this->mServers[$i]['slave pos'] = $conn->getSlavePos();
303                                 }
304                         }
305                         if ( $this->mReadIndex <=0 && $this->mLoads[$i]>0 && $i !== false ) {
306                                 $this->mReadIndex = $i;
307                         }
308                 }
309                 wfProfileOut( __METHOD__ );
310                 return $i;
311         }
312
313         /**
314          * Wait for a specified number of microseconds, and return the period waited
315          */
316         function sleep( $t ) {
317                 wfProfileIn( __METHOD__ );
318                 wfDebug( __METHOD__.": waiting $t us\n" );
319                 usleep( $t );
320                 wfProfileOut( __METHOD__ );
321                 return $t;
322         }
323
324         /**
325          * Set the master wait position
326          * If a DB_SLAVE connection has been opened already, waits
327          * Otherwise sets a variable telling it to wait if such a connection is opened
328          */
329         public function waitFor( $pos ) {
330                 wfProfileIn( __METHOD__ );
331                 $this->mWaitForPos = $pos;
332                 $i = $this->mReadIndex;
333
334                 if ( $i > 0 ) {
335                         if ( !$this->doWait( $i ) ) {
336                                 $this->mServers[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
337                                 $this->mLaggedSlaveMode = true;
338                         }
339                 }
340                 wfProfileOut( __METHOD__ );
341         }
342         
343         /**
344          * Set the master wait position and wait for ALL slaves to catch up to it
345          */
346         public function waitForAll( $pos ) {
347                 wfProfileIn( __METHOD__ );
348                 $this->mWaitForPos = $pos;
349                 for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
350                         $this->doWait( $i );
351                 }
352                 wfProfileOut( __METHOD__ );
353         }
354
355         /**
356          * Get any open connection to a given server index, local or foreign
357          * Returns false if there is no connection open
358          */
359         function getAnyOpenConnection( $i ) {
360                 foreach ( $this->mConns as $conns ) {
361                         if ( !empty( $conns[$i] ) ) {
362                                 return reset( $conns[$i] );
363                         }
364                 }
365                 return false;
366         }
367
368         /**
369          * Wait for a given slave to catch up to the master pos stored in $this
370          */
371         function doWait( $index ) {
372                 # Find a connection to wait on
373                 $conn = $this->getAnyOpenConnection( $index );
374                 if ( !$conn ) {
375                         wfDebug( __METHOD__ . ": no connection open\n" );
376                         return false;
377                 }
378
379                 wfDebug( __METHOD__.": Waiting for slave #$index to catch up...\n" );
380                 $result = $conn->masterPosWait( $this->mWaitForPos, $this->mWaitTimeout );
381
382                 if ( $result == -1 || is_null( $result ) ) {
383                         # Timed out waiting for slave, use master instead
384                         wfDebug( __METHOD__.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
385                         return false;
386                 } else {
387                         wfDebug( __METHOD__.": Done\n" );
388                         return true;
389                 }
390         }
391
392         /**
393          * Get a connection by index
394          * This is the main entry point for this class.
395          * 
396          * @param $i Integer: server index
397          * @param $groups Array: query groups
398          * @param $wiki String: wiki ID
399          * 
400          * @return DatabaseBase
401          */
402         public function &getConnection( $i, $groups = array(), $wiki = false ) {
403                 wfProfileIn( __METHOD__ );
404
405                 if ( $i == DB_LAST ) {
406                         throw new MWException( 'Attempt to call ' . __METHOD__ . ' with deprecated server index DB_LAST' );
407                 } elseif ( $i === null || $i === false ) {
408                         throw new MWException( 'Attempt to call ' . __METHOD__ . ' with invalid server index' );
409                 }
410
411                 if ( $wiki === wfWikiID() ) {
412                         $wiki = false;
413                 }
414
415                 # Query groups
416                 if ( $i == DB_MASTER ) {
417                         $i = $this->getWriterIndex();
418                 } elseif ( !is_array( $groups ) ) {
419                         $groupIndex = $this->getReaderIndex( $groups, $wiki );
420                         if ( $groupIndex !== false ) {
421                                 $serverName = $this->getServerName( $groupIndex );
422                                 wfDebug( __METHOD__.": using server $serverName for group $groups\n" );
423                                 $i = $groupIndex;
424                         }
425                 } else {
426                         foreach ( $groups as $group ) {
427                                 $groupIndex = $this->getReaderIndex( $group, $wiki );
428                                 if ( $groupIndex !== false ) {
429                                         $serverName = $this->getServerName( $groupIndex );
430                                         wfDebug( __METHOD__.": using server $serverName for group $group\n" );
431                                         $i = $groupIndex;
432                                         break;
433                                 }
434                         }
435                 }
436
437                 # Operation-based index
438                 if ( $i == DB_SLAVE ) {
439                         $i = $this->getReaderIndex( false, $wiki );
440                         # Couldn't find a working server in getReaderIndex()?
441                         if ( $i === false ) {
442                                 $this->mLastError = 'No working slave server: ' . $this->mLastError;
443                                 $this->reportConnectionError( $this->mErrorConnection );
444                                 wfProfileOut( __METHOD__ );
445                                 return false;
446                         }
447                 }
448
449                 # Now we have an explicit index into the servers array
450                 $conn = $this->openConnection( $i, $wiki );
451                 if ( !$conn ) {
452                         $this->reportConnectionError( $this->mErrorConnection );
453                 }
454
455                 wfProfileOut( __METHOD__ );
456                 return $conn;
457         }
458
459         /**
460          * Mark a foreign connection as being available for reuse under a different
461          * DB name or prefix. This mechanism is reference-counted, and must be called
462          * the same number of times as getConnection() to work.
463          */
464         public function reuseConnection( $conn ) {
465                 $serverIndex = $conn->getLBInfo('serverIndex');
466                 $refCount = $conn->getLBInfo('foreignPoolRefCount');
467                 $dbName = $conn->getDBname();
468                 $prefix = $conn->tablePrefix();
469                 if ( strval( $prefix ) !== '' ) {
470                         $wiki = "$dbName-$prefix";
471                 } else {
472                         $wiki = $dbName;
473                 }
474                 if ( $serverIndex === null || $refCount === null ) {
475                         wfDebug( __METHOD__.": this connection was not opened as a foreign connection\n" );
476                         /**
477                          * This can happen in code like:
478                          *   foreach ( $dbs as $db ) {
479                          *     $conn = $lb->getConnection( DB_SLAVE, array(), $db );
480                          *     ...
481                          *     $lb->reuseConnection( $conn );
482                          *   }
483                          * When a connection to the local DB is opened in this way, reuseConnection()
484                          * should be ignored
485                          */
486                         return;
487                 }
488                 if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
489                         throw new MWException( __METHOD__.": connection not found, has the connection been freed already?" );
490                 }
491                 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
492                 if ( $refCount <= 0 ) {
493                         $this->mConns['foreignFree'][$serverIndex][$wiki] = $conn;
494                         unset( $this->mConns['foreignUsed'][$serverIndex][$wiki] );
495                         wfDebug( __METHOD__.": freed connection $serverIndex/$wiki\n" );
496                 } else {
497                         wfDebug( __METHOD__.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
498                 }
499         }
500
501         /**
502          * Open a connection to the server given by the specified index
503          * Index must be an actual index into the array.
504          * If the server is already open, returns it.
505          *
506          * On error, returns false, and the connection which caused the
507          * error will be available via $this->mErrorConnection.
508          *
509          * @param $i Integer: server index
510          * @param $wiki String: wiki ID to open
511          * @return DatabaseBase
512          *
513          * @access private
514          */
515         function openConnection( $i, $wiki = false ) {
516                 wfProfileIn( __METHOD__ );
517                 if ( $wiki !== false ) {
518                         $conn = $this->openForeignConnection( $i, $wiki );
519                         wfProfileOut( __METHOD__);
520                         return $conn;
521                 }
522                 if ( isset( $this->mConns['local'][$i][0] ) ) {
523                         $conn = $this->mConns['local'][$i][0];
524                 } else {
525                         $server = $this->mServers[$i];
526                         $server['serverIndex'] = $i;
527                         $conn = $this->reallyOpenConnection( $server, false );
528                         if ( $conn->isOpen() ) {
529                                 $this->mConns['local'][$i][0] = $conn;
530                         } else {
531                                 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
532                                 $this->mErrorConnection = $conn;
533                                 $conn = false;
534                         }
535                 }
536                 wfProfileOut( __METHOD__ );
537                 return $conn;
538         }
539
540         /**
541          * Open a connection to a foreign DB, or return one if it is already open.
542          *
543          * Increments a reference count on the returned connection which locks the
544          * connection to the requested wiki. This reference count can be
545          * decremented by calling reuseConnection().
546          *
547          * If a connection is open to the appropriate server already, but with the wrong
548          * database, it will be switched to the right database and returned, as long as
549          * it has been freed first with reuseConnection().
550          *
551          * On error, returns false, and the connection which caused the
552          * error will be available via $this->mErrorConnection.
553          *
554          * @param $i Integer: server index
555          * @param $wiki String: wiki ID to open
556          * @return DatabaseBase
557          */
558         function openForeignConnection( $i, $wiki ) {
559                 wfProfileIn(__METHOD__);
560                 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
561                 if ( isset( $this->mConns['foreignUsed'][$i][$wiki] ) ) {
562                         // Reuse an already-used connection
563                         $conn = $this->mConns['foreignUsed'][$i][$wiki];
564                         wfDebug( __METHOD__.": reusing connection $i/$wiki\n" );
565                 } elseif ( isset( $this->mConns['foreignFree'][$i][$wiki] ) ) {
566                         // Reuse a free connection for the same wiki
567                         $conn = $this->mConns['foreignFree'][$i][$wiki];
568                         unset( $this->mConns['foreignFree'][$i][$wiki] );
569                         $this->mConns['foreignUsed'][$i][$wiki] = $conn;
570                         wfDebug( __METHOD__.": reusing free connection $i/$wiki\n" );
571                 } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
572                         // Reuse a connection from another wiki
573                         $conn = reset( $this->mConns['foreignFree'][$i] );
574                         $oldWiki = key( $this->mConns['foreignFree'][$i] );
575
576                         if ( !$conn->selectDB( $dbName ) ) {
577                                 $this->mLastError = "Error selecting database $dbName on server " .
578                                         $conn->getServer() . " from client host " . wfHostname() . "\n";
579                                 $this->mErrorConnection = $conn;
580                                 $conn = false;
581                         } else {
582                                 $conn->tablePrefix( $prefix );
583                                 unset( $this->mConns['foreignFree'][$i][$oldWiki] );
584                                 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
585                                 wfDebug( __METHOD__.": reusing free connection from $oldWiki for $wiki\n" );
586                         }
587                 } else {
588                         // Open a new connection
589                         $server = $this->mServers[$i];
590                         $server['serverIndex'] = $i;
591                         $server['foreignPoolRefCount'] = 0;
592                         $conn = $this->reallyOpenConnection( $server, $dbName );
593                         if ( !$conn->isOpen() ) {
594                                 wfDebug( __METHOD__.": error opening connection for $i/$wiki\n" );
595                                 $this->mErrorConnection = $conn;
596                                 $conn = false;
597                         } else {
598                                 $conn->tablePrefix( $prefix );
599                                 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
600                                 wfDebug( __METHOD__.": opened new connection for $i/$wiki\n" );
601                         }
602                 }
603
604                 // Increment reference count
605                 if ( $conn ) {
606                         $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
607                         $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
608                 }
609                 wfProfileOut(__METHOD__);
610                 return $conn;
611         }
612
613         /**
614          * Test if the specified index represents an open connection
615          *
616          * @param $index Integer: server index
617          * @access private
618          */
619         function isOpen( $index ) {
620                 if( !is_integer( $index ) ) {
621                         return false;
622                 }
623                 return (bool)$this->getAnyOpenConnection( $index );
624         }
625
626         /**
627          * Really opens a connection. Uncached.
628          * Returns a Database object whether or not the connection was successful.
629          * @access private
630          */
631         function reallyOpenConnection( $server, $dbNameOverride = false ) {
632                 if( !is_array( $server ) ) {
633                         throw new MWException( 'You must update your load-balancing configuration. See DefaultSettings.php entry for $wgDBservers.' );
634                 }
635
636                 $host = $server['host'];
637                 $dbname = $server['dbname'];
638
639                 if ( $dbNameOverride !== false ) {
640                         $server['dbname'] = $dbname = $dbNameOverride;
641                 }
642
643                 # Create object
644                 wfDebug( "Connecting to $host $dbname...\n" );
645                 try {
646                         $db = DatabaseBase::newFromType( $server['type'], $server );
647                 } catch ( DBConnectionError $e ) {
648                         // FIXME: This is probably the ugliest thing I have ever done to 
649                         // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
650                         $db = $e->db;
651                 }
652                 if ( $db->isOpen() ) {
653                         wfDebug( "Connected to $host $dbname.\n" );
654                 } else {
655                         wfDebug( "Connection failed to $host $dbname.\n" );
656                 }
657                 $db->setLBInfo( $server );
658                 if ( isset( $server['fakeSlaveLag'] ) ) {
659                         $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
660                 }
661                 if ( isset( $server['fakeMaster'] ) ) {
662                         $db->setFakeMaster( true );
663                 }
664                 return $db;
665         }
666
667         function reportConnectionError( &$conn ) {
668                 wfProfileIn( __METHOD__ );
669
670                 if ( !is_object( $conn ) ) {
671                         // No last connection, probably due to all servers being too busy
672                         wfLogDBError( "LB failure with no last connection\n" );
673                         $conn = new Database;
674                         // If all servers were busy, mLastError will contain something sensible
675                         throw new DBConnectionError( $conn, $this->mLastError );
676                 } else {
677                         $server = $conn->getProperty( 'mServer' );
678                         wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
679                         $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
680                 }
681                 wfProfileOut( __METHOD__ );
682         }
683
684         function getWriterIndex() {
685                 return 0;
686         }
687
688         /**
689          * Returns true if the specified index is a valid server index
690          */
691         function haveIndex( $i ) {
692                 return array_key_exists( $i, $this->mServers );
693         }
694
695         /**
696          * Returns true if the specified index is valid and has non-zero load
697          */
698         function isNonZeroLoad( $i ) {
699                 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
700         }
701
702         /**
703          * Get the number of defined servers (not the number of open connections)
704          */
705         function getServerCount() {
706                 return count( $this->mServers );
707         }
708
709         /**
710          * Get the host name or IP address of the server with the specified index
711          * Prefer a readable name if available.
712          */
713         function getServerName( $i ) {
714                 if ( isset( $this->mServers[$i]['hostName'] ) ) {
715                         return $this->mServers[$i]['hostName'];
716                 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
717                         return $this->mServers[$i]['host'];
718                 } else {
719                         return '';
720                 }
721         }
722
723         /**
724          * Return the server info structure for a given index, or false if the index is invalid.
725          */
726         function getServerInfo( $i ) {
727                 if ( isset( $this->mServers[$i] ) ) {
728                         return $this->mServers[$i];
729                 } else {
730                         return false;
731                 }
732         }
733
734         /**
735          * Get the current master position for chronology control purposes
736          * @return mixed
737          */
738         function getMasterPos() {
739                 # If this entire request was served from a slave without opening a connection to the
740                 # master (however unlikely that may be), then we can fetch the position from the slave.
741                 $masterConn = $this->getAnyOpenConnection( 0 );
742                 if ( !$masterConn ) {
743                         for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
744                                 $conn = $this->getAnyOpenConnection( $i );
745                                 if ( $conn ) {
746                                         wfDebug( "Master pos fetched from slave\n" );
747                                         return $conn->getSlavePos();
748                                 }
749                         }
750                 } else {
751                         wfDebug( "Master pos fetched from master\n" );
752                         return $masterConn->getMasterPos();
753                 }
754                 return false;
755         }
756
757         /**
758          * Close all open connections
759          */
760         function closeAll() {
761                 foreach ( $this->mConns as $conns2 ) {
762                         foreach  ( $conns2 as $conns3 ) {
763                                 foreach ( $conns3 as $conn ) {
764                                         $conn->close();
765                                 }
766                         }
767                 }
768                 $this->mConns = array(
769                         'local' => array(),
770                         'foreignFree' => array(),
771                         'foreignUsed' => array(),
772                 );
773         }
774
775         /**
776          * Deprecated function, typo in function name
777          */
778         function closeConnecton( $conn ) {
779                 $this->closeConnection( $conn );
780         }
781
782         /**
783          * Close a connection
784          * Using this function makes sure the LoadBalancer knows the connection is closed.
785          * If you use $conn->close() directly, the load balancer won't update its state.
786          * @param  $conn
787          * @return void
788          */
789         function closeConnection( $conn ) {
790                 $done = false;
791                 foreach ( $this->mConns as $i1 => $conns2 ) {
792                         foreach ( $conns2 as $i2 => $conns3 ) {
793                                 foreach ( $conns3 as $i3 => $candidateConn ) {
794                                         if ( $conn === $candidateConn ) {
795                                                 $conn->close();
796                                                 unset( $this->mConns[$i1][$i2][$i3] );
797                                                 $done = true;
798                                                 break;
799                                         }
800                                 }
801                         }
802                 }
803                 if ( !$done ) {
804                         $conn->close();
805                 }
806         }
807
808         /**
809          * Commit transactions on all open connections
810          */
811         function commitAll() {
812                 foreach ( $this->mConns as $conns2 ) {
813                         foreach ( $conns2 as $conns3 ) {
814                                 foreach ( $conns3 as $conn ) {
815                                         $conn->commit();
816                                 }
817                         }
818                 }
819         }
820
821         /* Issue COMMIT only on master, only if queries were done on connection */
822         function commitMasterChanges() {
823                 // Always 0, but who knows.. :)
824                 $masterIndex = $this->getWriterIndex();
825                 foreach ( $this->mConns as $conns2 ) {
826                         if ( empty( $conns2[$masterIndex] ) ) {
827                                 continue;
828                         }
829                         foreach ( $conns2[$masterIndex] as $conn ) {
830                                 if ( $conn->doneWrites() ) {
831                                         $conn->commit();
832                                 }
833                         }
834                 }
835         }
836
837         function waitTimeout( $value = null ) {
838                 return wfSetVar( $this->mWaitTimeout, $value );
839         }
840
841         function getLaggedSlaveMode() {
842                 return $this->mLaggedSlaveMode;
843         }
844
845         /* Disables/enables lag checks */
846         function allowLagged($mode=null) {
847                 if ($mode===null)
848                         return $this->mAllowLagged;
849                 $this->mAllowLagged=$mode;
850         }
851
852         function pingAll() {
853                 $success = true;
854                 foreach ( $this->mConns as $conns2 ) {
855                         foreach ( $conns2 as $conns3 ) {
856                                 foreach ( $conns3 as $conn ) {
857                                         if ( !$conn->ping() ) {
858                                                 $success = false;
859                                         }
860                                 }
861                         }
862                 }
863                 return $success;
864         }
865
866         /**
867          * Call a function with each open connection object
868          */
869         function forEachOpenConnection( $callback, $params = array() ) {
870                 foreach ( $this->mConns as $conns2 ) {
871                         foreach ( $conns2 as $conns3 ) {
872                                 foreach ( $conns3 as $conn ) {
873                                         $mergedParams = array_merge( array( $conn ), $params );
874                                         call_user_func_array( $callback, $mergedParams );
875                                 }
876                         }
877                 }
878         }
879
880         /**
881          * Get the hostname and lag time of the most-lagged slave.
882          * This is useful for maintenance scripts that need to throttle their updates.
883          * May attempt to open connections to slaves on the default DB.
884          * @param $wiki string Wiki ID, or false for the default database
885          */
886         function getMaxLag( $wiki = false ) {
887                 $maxLag = -1;
888                 $host = '';
889                 foreach ( $this->mServers as $i => $conn ) {
890                         $conn = false;
891                         if ( $wiki === false ) {
892                                 $conn = $this->getAnyOpenConnection( $i );
893                         }
894                         if ( !$conn ) {
895                                 $conn = $this->openConnection( $i, $wiki );
896                         }
897                         if ( !$conn ) {
898                                 continue;
899                         }
900                         $lag = $conn->getLag();
901                         if ( $lag > $maxLag ) {
902                                 $maxLag = $lag;
903                                 $host = $this->mServers[$i]['host'];
904                         }
905                 }
906                 return array( $host, $maxLag );
907         }
908
909         /**
910          * Get lag time for each server
911          * Results are cached for a short time in memcached, and indefinitely in the process cache
912          */
913         function getLagTimes( $wiki = false ) {
914                 # Try process cache
915                 if ( isset( $this->mLagTimes ) ) {
916                         return $this->mLagTimes;
917                 }
918                 # No, send the request to the load monitor
919                 $this->mLagTimes = $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $wiki );
920                 return $this->mLagTimes;
921         }
922
923         /**
924          * Clear the cache for getLagTimes
925          */
926         function clearLagTimeCache() {
927                 $this->mLagTimes = null;
928         }
929 }