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