3 * Database load balancing
10 * Database load balancing object
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;
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.
30 function __construct( $params )
32 if ( !isset( $params['servers'] ) ) {
33 throw new MWException( __CLASS__.': missing servers parameter' );
35 $this->mServers = $params['servers'];
37 if ( isset( $params['waitTimeout'] ) ) {
38 $this->mWaitTimeout = $params['waitTimeout'];
40 $this->mWaitTimeout = 10;
43 $this->mReadIndex = -1;
44 $this->mWriteIndex = -1;
45 $this->mConns = 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';
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();
64 $this->mGroupLoads[$group][$i] = $ratio;
71 * Get a LoadMonitor instance
73 function getLoadMonitor() {
74 if ( !isset( $this->mLoadMonitor ) ) {
75 $class = $this->mLoadMonitorClass;
76 $this->mLoadMonitor = new $class( $this );
78 return $this->mLoadMonitor;
82 * Get or set arbitrary data used by the parent object, usually an LBFactory
84 function parentInfo( $x = null ) {
85 return wfSetVar( $this->mParentInfo, $x );
89 * Given an array of non-normalised probabilities, this function will select
90 * an element and return the appropriate key
92 function pickRandom( $weights )
94 if ( !is_array( $weights ) || count( $weights ) == 0 ) {
98 $sum = array_sum( $weights );
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.
106 $max = mt_getrandmax();
107 $rand = mt_rand(0, $max) / $max * $sum;
110 foreach ( $weights as $i => $w ) {
112 if ( $sum >= $rand ) {
119 function getRandomNonLagged( $loads, $wiki = false ) {
120 # Unset excessively lagged servers
121 $lags = $this->getLagTimes( $wiki );
122 foreach ( $lags as $i => $lag ) {
124 if ( $lag === false ) {
125 wfDebug( "Server #$i is not replicating\n" );
127 } elseif ( isset( $this->mServers[$i]['max lag'] ) && $lag > $this->mServers[$i]['max lag'] ) {
128 wfDebug( "Server #$i is excessively lagged ($lag seconds)\n" );
134 # Find out if all the slaves with non-zero load are lagged
136 foreach ( $loads as $load ) {
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.
147 if ( count( $loads ) == 0 ) {
151 #wfDebugLog( 'connect', var_export( $loads, true ) );
153 # Return a random representative of the remainder
154 return $this->pickRandom( $loads );
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
162 * Side effect: opens connections to databases
164 function getReaderIndex( $group = false, $wiki = false ) {
165 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
167 # FIXME: For now, only go through all this for mysql databases
168 if ($wgDBtype != 'mysql') {
169 return $this->getWriterIndex();
172 if ( count( $this->mServers ) == 1 ) {
173 # Skip the load balancing if there's only one server
175 } elseif ( $group === false and $this->mReadIndex >= 0 ) {
176 # Shortcut if generic reader exists already
177 return $this->mReadIndex;
180 wfProfileIn( __METHOD__ );
184 # convert from seconds to microseconds
185 $timeout = $wgDBClusterTimeout * 1e6;
187 # Find the relevant load array
188 if ( $group !== false ) {
189 if ( isset( $this->mGroupLoads[$group] ) ) {
190 $nonErrorLoads = $this->mGroupLoads[$group];
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__ );
198 $nonErrorLoads = $this->mLoads;
201 if ( !$nonErrorLoads ) {
202 throw new MWException( "Empty server array given to LoadBalancer" );
205 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
206 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
208 $laggedSlaveMode = false;
210 # First try quickly looking through the available servers for a server that
213 $totalThreadsConnected = 0;
214 $overloadedServers = 0;
215 $currentLoads = $nonErrorLoads;
216 while ( count( $currentLoads ) ) {
217 if ( $wgReadOnly || $this->mAllowLagged || $laggedSlaveMode ) {
218 $i = $this->pickRandom( $currentLoads );
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;
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__ );
239 wfDebugLog( 'connect', __METHOD__.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
240 $conn = $this->openConnection( $i, $wiki );
243 wfDebugLog( 'connect', __METHOD__.": Failed connecting to $i/$wiki\n" );
244 unset( $nonErrorLoads[$i] );
245 unset( $currentLoads[$i] );
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 );
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 );
261 # Post-connection overload, don't use this server for now
262 $totalThreadsConnected += $backoff;
263 $overloadedServers++;
264 unset( $currentLoads[$i] );
271 # No server found yet
274 # If all servers were down, quit now
275 if ( !count( $nonErrorLoads ) ) {
276 wfDebugLog( 'connect', "All servers down\n" );
280 # Some servers must have been overloaded
281 if ( $overloadedServers == 0 ) {
282 throw new MWException( __METHOD__.": unexpectedly found no overloaded servers" );
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 );
291 if ( $totalElapsed >= $timeout ) {
292 wfDebugLog( 'connect', "All servers busy\n" );
293 $this->mErrorConnection = false;
294 $this->mLastError = 'All servers busy';
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();
305 if ( $this->mReadIndex <=0 && $this->mLoads[$i]>0 && $i !== false ) {
306 $this->mReadIndex = $i;
309 wfProfileOut( __METHOD__ );
314 * Wait for a specified number of microseconds, and return the period waited
316 function sleep( $t ) {
317 wfProfileIn( __METHOD__ );
318 wfDebug( __METHOD__.": waiting $t us\n" );
320 wfProfileOut( __METHOD__ );
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
329 public function waitFor( $pos ) {
330 wfProfileIn( __METHOD__ );
331 $this->mWaitForPos = $pos;
332 $i = $this->mReadIndex;
335 if ( !$this->doWait( $i ) ) {
336 $this->mServers[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
337 $this->mLaggedSlaveMode = true;
340 wfProfileOut( __METHOD__ );
344 * Set the master wait position and wait for ALL slaves to catch up to it
346 public function waitForAll( $pos ) {
347 wfProfileIn( __METHOD__ );
348 $this->mWaitForPos = $pos;
349 for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
352 wfProfileOut( __METHOD__ );
356 * Get any open connection to a given server index, local or foreign
357 * Returns false if there is no connection open
359 function getAnyOpenConnection( $i ) {
360 foreach ( $this->mConns as $conns ) {
361 if ( !empty( $conns[$i] ) ) {
362 return reset( $conns[$i] );
369 * Wait for a given slave to catch up to the master pos stored in $this
371 function doWait( $index ) {
372 # Find a connection to wait on
373 $conn = $this->getAnyOpenConnection( $index );
375 wfDebug( __METHOD__ . ": no connection open\n" );
379 wfDebug( __METHOD__.": Waiting for slave #$index to catch up...\n" );
380 $result = $conn->masterPosWait( $this->mWaitForPos, $this->mWaitTimeout );
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" );
387 wfDebug( __METHOD__.": Done\n" );
393 * Get a connection by index
394 * This is the main entry point for this class.
396 * @param $i Integer: server index
397 * @param $groups Array: query groups
398 * @param $wiki String: wiki ID
400 * @return DatabaseBase
402 public function &getConnection( $i, $groups = array(), $wiki = false ) {
403 wfProfileIn( __METHOD__ );
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' );
411 if ( $wiki === wfWikiID() ) {
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" );
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" );
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__ );
449 # Now we have an explicit index into the servers array
450 $conn = $this->openConnection( $i, $wiki );
452 $this->reportConnectionError( $this->mErrorConnection );
455 wfProfileOut( __METHOD__ );
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.
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";
474 if ( $serverIndex === null || $refCount === null ) {
475 wfDebug( __METHOD__.": this connection was not opened as a foreign connection\n" );
477 * This can happen in code like:
478 * foreach ( $dbs as $db ) {
479 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
481 * $lb->reuseConnection( $conn );
483 * When a connection to the local DB is opened in this way, reuseConnection()
488 if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
489 throw new MWException( __METHOD__.": connection not found, has the connection been freed already?" );
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" );
497 wfDebug( __METHOD__.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
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.
506 * On error, returns false, and the connection which caused the
507 * error will be available via $this->mErrorConnection.
509 * @param $i Integer: server index
510 * @param $wiki String: wiki ID to open
511 * @return DatabaseBase
515 function openConnection( $i, $wiki = false ) {
516 wfProfileIn( __METHOD__ );
517 if ( $wiki !== false ) {
518 $conn = $this->openForeignConnection( $i, $wiki );
519 wfProfileOut( __METHOD__);
522 if ( isset( $this->mConns['local'][$i][0] ) ) {
523 $conn = $this->mConns['local'][$i][0];
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;
531 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
532 $this->mErrorConnection = $conn;
536 wfProfileOut( __METHOD__ );
541 * Open a connection to a foreign DB, or return one if it is already open.
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().
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().
551 * On error, returns false, and the connection which caused the
552 * error will be available via $this->mErrorConnection.
554 * @param $i Integer: server index
555 * @param $wiki String: wiki ID to open
556 * @return DatabaseBase
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] );
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;
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" );
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;
598 $conn->tablePrefix( $prefix );
599 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
600 wfDebug( __METHOD__.": opened new connection for $i/$wiki\n" );
604 // Increment reference count
606 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
607 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
609 wfProfileOut(__METHOD__);
614 * Test if the specified index represents an open connection
616 * @param $index Integer: server index
619 function isOpen( $index ) {
620 if( !is_integer( $index ) ) {
623 return (bool)$this->getAnyOpenConnection( $index );
627 * Really opens a connection. Uncached.
628 * Returns a Database object whether or not the connection was successful.
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.' );
636 $host = $server['host'];
637 $dbname = $server['dbname'];
639 if ( $dbNameOverride !== false ) {
640 $server['dbname'] = $dbname = $dbNameOverride;
644 wfDebug( "Connecting to $host $dbname...\n" );
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
652 if ( $db->isOpen() ) {
653 wfDebug( "Connected to $host $dbname.\n" );
655 wfDebug( "Connection failed to $host $dbname.\n" );
657 $db->setLBInfo( $server );
658 if ( isset( $server['fakeSlaveLag'] ) ) {
659 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
661 if ( isset( $server['fakeMaster'] ) ) {
662 $db->setFakeMaster( true );
667 function reportConnectionError( &$conn ) {
668 wfProfileIn( __METHOD__ );
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 );
677 $server = $conn->getProperty( 'mServer' );
678 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
679 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
681 wfProfileOut( __METHOD__ );
684 function getWriterIndex() {
689 * Returns true if the specified index is a valid server index
691 function haveIndex( $i ) {
692 return array_key_exists( $i, $this->mServers );
696 * Returns true if the specified index is valid and has non-zero load
698 function isNonZeroLoad( $i ) {
699 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
703 * Get the number of defined servers (not the number of open connections)
705 function getServerCount() {
706 return count( $this->mServers );
710 * Get the host name or IP address of the server with the specified index
711 * Prefer a readable name if available.
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'];
724 * Return the server info structure for a given index, or false if the index is invalid.
726 function getServerInfo( $i ) {
727 if ( isset( $this->mServers[$i] ) ) {
728 return $this->mServers[$i];
735 * Get the current master position for chronology control purposes
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 );
746 wfDebug( "Master pos fetched from slave\n" );
747 return $conn->getSlavePos();
751 wfDebug( "Master pos fetched from master\n" );
752 return $masterConn->getMasterPos();
758 * Close all open connections
760 function closeAll() {
761 foreach ( $this->mConns as $conns2 ) {
762 foreach ( $conns2 as $conns3 ) {
763 foreach ( $conns3 as $conn ) {
768 $this->mConns = array(
770 'foreignFree' => array(),
771 'foreignUsed' => array(),
776 * Deprecated function, typo in function name
778 function closeConnecton( $conn ) {
779 $this->closeConnection( $conn );
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.
789 function closeConnection( $conn ) {
791 foreach ( $this->mConns as $i1 => $conns2 ) {
792 foreach ( $conns2 as $i2 => $conns3 ) {
793 foreach ( $conns3 as $i3 => $candidateConn ) {
794 if ( $conn === $candidateConn ) {
796 unset( $this->mConns[$i1][$i2][$i3] );
809 * Commit transactions on all open connections
811 function commitAll() {
812 foreach ( $this->mConns as $conns2 ) {
813 foreach ( $conns2 as $conns3 ) {
814 foreach ( $conns3 as $conn ) {
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] ) ) {
829 foreach ( $conns2[$masterIndex] as $conn ) {
830 if ( $conn->doneWrites() ) {
837 function waitTimeout( $value = null ) {
838 return wfSetVar( $this->mWaitTimeout, $value );
841 function getLaggedSlaveMode() {
842 return $this->mLaggedSlaveMode;
845 /* Disables/enables lag checks */
846 function allowLagged($mode=null) {
848 return $this->mAllowLagged;
849 $this->mAllowLagged=$mode;
854 foreach ( $this->mConns as $conns2 ) {
855 foreach ( $conns2 as $conns3 ) {
856 foreach ( $conns3 as $conn ) {
857 if ( !$conn->ping() ) {
867 * Call a function with each open connection object
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 );
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
886 function getMaxLag( $wiki = false ) {
889 foreach ( $this->mServers as $i => $conn ) {
891 if ( $wiki === false ) {
892 $conn = $this->getAnyOpenConnection( $i );
895 $conn = $this->openConnection( $i, $wiki );
900 $lag = $conn->getLag();
901 if ( $lag > $maxLag ) {
903 $host = $this->mServers[$i]['host'];
906 return array( $host, $maxLag );
910 * Get lag time for each server
911 * Results are cached for a short time in memcached, and indefinitely in the process cache
913 function getLagTimes( $wiki = false ) {
915 if ( isset( $this->mLagTimes ) ) {
916 return $this->mLagTimes;
918 # No, send the request to the load monitor
919 $this->mLagTimes = $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $wiki );
920 return $this->mLagTimes;
924 * Clear the cache for getLagTimes
926 function clearLagTimeCache() {
927 $this->mLagTimes = null;