3 * Database load balancing
10 * Database load balancing object
16 /* private */ var $mServers, $mConns, $mLoads, $mGroupLoads;
17 /* private */ var $mFailFunction, $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 * failFunction Deprecated, use exceptions instead.
28 * masterWaitTimeout Replication lag wait timeout
29 * loadMonitor Name of a class used to fetch server lag and load.
31 function __construct( $params )
33 if ( !isset( $params['servers'] ) ) {
34 throw new MWException( __CLASS__
.': missing servers parameter' );
36 $this->mServers
= $params['servers'];
38 if ( isset( $params['waitTimeout'] ) ) {
39 $this->mWaitTimeout
= $params['waitTimeout'];
41 $this->mWaitTimeout
= 10;
44 $this->mReadIndex
= -1;
45 $this->mWriteIndex
= -1;
46 $this->mConns
= array(
48 'foreignUsed' => array(),
49 'foreignFree' => array() );
50 $this->mLoads
= array();
51 $this->mWaitForPos
= false;
52 $this->mLaggedSlaveMode
= false;
53 $this->mErrorConnection
= false;
54 $this->mAllowLag
= false;
55 $this->mLoadMonitorClass
= isset( $params['loadMonitor'] )
56 ?
$params['loadMonitor'] : 'LoadMonitor_MySQL';
58 foreach( $params['servers'] as $i => $server ) {
59 $this->mLoads
[$i] = $server['load'];
60 if ( isset( $server['groupLoads'] ) ) {
61 foreach ( $server['groupLoads'] as $group => $ratio ) {
62 if ( !isset( $this->mGroupLoads
[$group] ) ) {
63 $this->mGroupLoads
[$group] = array();
65 $this->mGroupLoads
[$group][$i] = $ratio;
71 static function newFromParams( $servers, $failFunction = false, $waitTimeout = 10 )
73 return new LoadBalancer( $servers, $failFunction, $waitTimeout );
77 * Get a LoadMonitor instance
79 function getLoadMonitor() {
80 if ( !isset( $this->mLoadMonitor
) ) {
81 $class = $this->mLoadMonitorClass
;
82 $this->mLoadMonitor
= new $class( $this );
84 return $this->mLoadMonitor
;
88 * Get or set arbitrary data used by the parent object, usually an LBFactory
90 function parentInfo( $x = null ) {
91 return wfSetVar( $this->mParentInfo
, $x );
95 * Given an array of non-normalised probabilities, this function will select
96 * an element and return the appropriate key
98 function pickRandom( $weights )
100 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
104 $sum = array_sum( $weights );
106 # No loads on any of them
107 # In previous versions, this triggered an unweighted random selection,
108 # but this feature has been removed as of April 2006 to allow for strict
109 # separation of query groups.
112 $max = mt_getrandmax();
113 $rand = mt_rand(0, $max) / $max * $sum;
116 foreach ( $weights as $i => $w ) {
118 if ( $sum >= $rand ) {
125 function getRandomNonLagged( $loads, $wiki = false ) {
126 # Unset excessively lagged servers
127 $lags = $this->getLagTimes( $wiki );
128 foreach ( $lags as $i => $lag ) {
129 if ( $i != 0 && isset( $this->mServers
[$i]['max lag'] ) ) {
130 if ( $lag === false ) {
131 wfDebug( "Server #$i is not replicating\n" );
133 } elseif ( $lag > $this->mServers
[$i]['max lag'] ) {
134 wfDebug( "Server #$i is excessively lagged ($lag seconds)\n" );
140 # Find out if all the slaves with non-zero load are lagged
142 foreach ( $loads as $load ) {
146 # No appropriate DB servers except maybe the master and some slaves with zero load
147 # Do NOT use the master
148 # Instead, this function will return false, triggering read-only mode,
149 # and a lagged slave will be used instead.
153 if ( count( $loads ) == 0 ) {
157 #wfDebugLog( 'connect', var_export( $loads, true ) );
159 # Return a random representative of the remainder
160 return $this->pickRandom( $loads );
164 * Get the index of the reader connection, which may be a slave
165 * This takes into account load ratios and lag times. It should
166 * always return a consistent index during a given invocation
168 * Side effect: opens connections to databases
170 function getReaderIndex( $group = false, $wiki = false ) {
171 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
173 # FIXME: For now, only go through all this for mysql databases
174 if ($wgDBtype != 'mysql') {
175 return $this->getWriterIndex();
178 if ( count( $this->mServers
) == 1 ) {
179 # Skip the load balancing if there's only one server
181 } elseif ( $group === false and $this->mReadIndex
>= 0 ) {
182 # Shortcut if generic reader exists already
183 return $this->mReadIndex
;
186 wfProfileIn( __METHOD__
);
190 # convert from seconds to microseconds
191 $timeout = $wgDBClusterTimeout * 1e6
;
193 # Find the relevant load array
194 if ( $group !== false ) {
195 if ( isset( $this->mGroupLoads
[$group] ) ) {
196 $nonErrorLoads = $this->mGroupLoads
[$group];
198 # No loads for this group, return false and the caller can use some other group
199 wfDebug( __METHOD__
.": no loads for group $group\n" );
200 wfProfileOut( __METHOD__
);
204 $nonErrorLoads = $this->mLoads
;
207 if ( !$nonErrorLoads ) {
208 throw new MWException( "Empty server array given to LoadBalancer" );
211 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
212 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
214 $laggedSlaveMode = false;
216 # First try quickly looking through the available servers for a server that
219 $totalThreadsConnected = 0;
220 $overloadedServers = 0;
221 $currentLoads = $nonErrorLoads;
222 while ( count( $currentLoads ) ) {
223 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
224 $i = $this->pickRandom( $currentLoads );
226 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
227 if ( $i === false && count( $currentLoads ) != 0 ) {
228 # All slaves lagged. Switch to read-only mode
229 $wgReadOnly = wfMsgNoDBForContent( 'readonly_lag' );
230 $i = $this->pickRandom( $currentLoads );
231 $laggedSlaveMode = true;
235 if ( $i === false ) {
236 # pickRandom() returned false
237 # This is permanent and means the configuration or the load monitor
238 # wants us to return false.
239 wfDebugLog( 'connect', __METHOD__
.": pickRandom() returned false\n" );
240 wfProfileOut( __METHOD__
);
244 wfDebugLog( 'connect', __METHOD__
.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
245 $conn = $this->openConnection( $i, $wiki );
248 wfDebugLog( 'connect', __METHOD__
.": Failed connecting to $i/$wiki\n" );
249 unset( $nonErrorLoads[$i] );
250 unset( $currentLoads[$i] );
254 // Perform post-connection backoff
255 $threshold = isset( $this->mServers
[$i]['max threads'] )
256 ?
$this->mServers
[$i]['max threads'] : false;
257 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
259 // Decrement reference counter, we are finished with this connection.
260 // It will be incremented for the caller later.
261 if ( $wiki !== false ) {
262 $this->reuseConnection( $conn );
266 # Post-connection overload, don't use this server for now
267 $totalThreadsConnected +
= $backoff;
268 $overloadedServers++
;
269 unset( $currentLoads[$i] );
276 # No server found yet
279 # If all servers were down, quit now
280 if ( !count( $nonErrorLoads ) ) {
281 wfDebugLog( 'connect', "All servers down\n" );
285 # Some servers must have been overloaded
286 if ( $overloadedServers == 0 ) {
287 throw new MWException( __METHOD__
.": unexpectedly found no overloaded servers" );
289 # Back off for a while
290 # Scale the sleep time by the number of connected threads, to produce a
291 # roughly constant global poll rate
292 $avgThreads = $totalThreadsConnected / $overloadedServers;
293 $totalElapsed +
= $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
294 } while ( $totalElapsed < $timeout );
296 if ( $totalElapsed >= $timeout ) {
297 wfDebugLog( 'connect', "All servers busy\n" );
298 $this->mErrorConnection
= false;
299 $this->mLastError
= 'All servers busy';
302 if ( $i !== false ) {
303 # Slave connection successful
304 # Wait for the session master pos for a short time
305 if ( $this->mWaitForPos
&& $i > 0 ) {
306 if ( !$this->doWait( $i ) ) {
307 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
310 if ( $this->mReadIndex
<=0 && $this->mLoads
[$i]>0 && $i !== false ) {
311 $this->mReadIndex
= $i;
314 wfProfileOut( __METHOD__
);
319 * Wait for a specified number of microseconds, and return the period waited
321 function sleep( $t ) {
322 wfProfileIn( __METHOD__
);
323 wfDebug( __METHOD__
.": waiting $t us\n" );
325 wfProfileOut( __METHOD__
);
330 * Get a random server to use in a query group
331 * @deprecated use getReaderIndex
333 function getGroupIndex( $group ) {
334 return $this->getReaderIndex( $group );
338 * Set the master wait position
339 * If a DB_SLAVE connection has been opened already, waits
340 * Otherwise sets a variable telling it to wait if such a connection is opened
342 public function waitFor( $pos ) {
343 wfProfileIn( __METHOD__
);
344 $this->mWaitForPos
= $pos;
345 $i = $this->mReadIndex
;
348 if ( !$this->doWait( $i ) ) {
349 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
350 $this->mLaggedSlaveMode
= true;
353 wfProfileOut( __METHOD__
);
357 * Get any open connection to a given server index, local or foreign
358 * Returns false if there is no connection open
360 function getAnyOpenConnection( $i ) {
361 foreach ( $this->mConns
as $conns ) {
362 if ( !empty( $conns[$i] ) ) {
363 return reset( $conns[$i] );
370 * Wait for a given slave to catch up to the master pos stored in $this
372 function doWait( $index ) {
373 # Find a connection to wait on
374 $conn = $this->getAnyOpenConnection( $index );
376 wfDebug( __METHOD__
. ": no connection open\n" );
380 wfDebug( __METHOD__
.": Waiting for slave #$index to catch up...\n" );
381 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
383 if ( $result == -1 ||
is_null( $result ) ) {
384 # Timed out waiting for slave, use master instead
385 wfDebug( __METHOD__
.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
388 wfDebug( __METHOD__
.": Done\n" );
394 * Get a connection by index
395 * This is the main entry point for this class.
397 * @param $i Integer: server index
398 * @param $groups Array: query groups
399 * @param $wiki String: wiki ID
401 * @return DatabaseBase
403 public function &getConnection( $i, $groups = array(), $wiki = false ) {
404 wfProfileIn( __METHOD__
);
406 if ( $i == DB_LAST
) {
407 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with deprecated server index DB_LAST' );
408 } elseif ( $i === null ||
$i === false ) {
409 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with invalid server index' );
412 if ( $wiki === wfWikiID() ) {
417 if ( $i == DB_MASTER
) {
418 $i = $this->getWriterIndex();
419 } elseif ( !is_array( $groups ) ) {
420 $groupIndex = $this->getReaderIndex( $groups, $wiki );
421 if ( $groupIndex !== false ) {
422 $serverName = $this->getServerName( $groupIndex );
423 wfDebug( __METHOD__
.": using server $serverName for group $groups\n" );
427 foreach ( $groups as $group ) {
428 $groupIndex = $this->getReaderIndex( $group, $wiki );
429 if ( $groupIndex !== false ) {
430 $serverName = $this->getServerName( $groupIndex );
431 wfDebug( __METHOD__
.": using server $serverName for group $group\n" );
438 # Operation-based index
439 if ( $i == DB_SLAVE
) {
440 $i = $this->getReaderIndex( false, $wiki );
441 # Couldn't find a working server in getReaderIndex()?
442 if ( $i === false ) {
443 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
444 $this->reportConnectionError( $this->mErrorConnection
);
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.' );
637 if ( $dbNameOverride !== false ) {
638 $dbname = $dbNameOverride;
641 # Get class for this database type
642 $class = 'Database' . ucfirst( $type );
645 wfDebug( "Connecting to $host $dbname...\n" );
646 $db = new $class( $host, $user, $password, $dbname, 1, $flags );
647 if ( $db->isOpen() ) {
648 wfDebug( "Connected to $host $dbname.\n" );
650 wfDebug( "Connection failed to $host $dbname.\n" );
652 $db->setLBInfo( $server );
653 if ( isset( $server['fakeSlaveLag'] ) ) {
654 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
656 if ( isset( $server['fakeMaster'] ) ) {
657 $db->setFakeMaster( true );
662 function reportConnectionError( &$conn ) {
663 wfProfileIn( __METHOD__
);
665 if ( !is_object( $conn ) ) {
666 // No last connection, probably due to all servers being too busy
667 wfLogDBError( "LB failure with no last connection\n" );
668 $conn = new Database
;
669 // If all servers were busy, mLastError will contain something sensible
670 throw new DBConnectionError( $conn, $this->mLastError
);
672 $server = $conn->getProperty( 'mServer' );
673 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
674 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
676 wfProfileOut( __METHOD__
);
679 function getWriterIndex() {
684 * Returns true if the specified index is a valid server index
686 function haveIndex( $i ) {
687 return array_key_exists( $i, $this->mServers
);
691 * Returns true if the specified index is valid and has non-zero load
693 function isNonZeroLoad( $i ) {
694 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
698 * Get the number of defined servers (not the number of open connections)
700 function getServerCount() {
701 return count( $this->mServers
);
705 * Get the host name or IP address of the server with the specified index
706 * Prefer a readable name if available.
708 function getServerName( $i ) {
709 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
710 return $this->mServers
[$i]['hostName'];
711 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
712 return $this->mServers
[$i]['host'];
719 * Return the server info structure for a given index, or false if the index is invalid.
721 function getServerInfo( $i ) {
722 if ( isset( $this->mServers
[$i] ) ) {
723 return $this->mServers
[$i];
730 * Get the current master position for chronology control purposes
733 function getMasterPos() {
734 # If this entire request was served from a slave without opening a connection to the
735 # master (however unlikely that may be), then we can fetch the position from the slave.
736 $masterConn = $this->getAnyOpenConnection( 0 );
737 if ( !$masterConn ) {
738 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
739 $conn = $this->getAnyOpenConnection( $i );
741 wfDebug( "Master pos fetched from slave\n" );
742 return $conn->getSlavePos();
746 wfDebug( "Master pos fetched from master\n" );
747 return $masterConn->getMasterPos();
753 * Close all open connections
755 function closeAll() {
756 foreach ( $this->mConns
as $conns2 ) {
757 foreach ( $conns2 as $conns3 ) {
758 foreach ( $conns3 as $conn ) {
763 $this->mConns
= array(
765 'foreignFree' => array(),
766 'foreignUsed' => array(),
772 * Using this function makes sure the LoadBalancer knows the connection is closed.
773 * If you use $conn->close() directly, the load balancer won't update its state.
775 function closeConnecton( $conn ) {
777 foreach ( $this->mConns
as $i1 => $conns2 ) {
778 foreach ( $conns2 as $i2 => $conns3 ) {
779 foreach ( $conns3 as $i3 => $candidateConn ) {
780 if ( $conn === $candidateConn ) {
782 unset( $this->mConns
[$i1][$i2][$i3] );
795 * Commit transactions on all open connections
797 function commitAll() {
798 foreach ( $this->mConns
as $conns2 ) {
799 foreach ( $conns2 as $conns3 ) {
800 foreach ( $conns3 as $conn ) {
807 /* Issue COMMIT only on master, only if queries were done on connection */
808 function commitMasterChanges() {
809 // Always 0, but who knows.. :)
810 $masterIndex = $this->getWriterIndex();
811 foreach ( $this->mConns
as $conns2 ) {
812 if ( empty( $conns2[$masterIndex] ) ) {
815 foreach ( $conns2[$masterIndex] as $conn ) {
816 if ( $conn->doneWrites() ) {
823 function waitTimeout( $value = null ) {
824 return wfSetVar( $this->mWaitTimeout
, $value );
827 function getLaggedSlaveMode() {
828 return $this->mLaggedSlaveMode
;
831 /* Disables/enables lag checks */
832 function allowLagged($mode=null) {
834 return $this->mAllowLagged
;
835 $this->mAllowLagged
=$mode;
840 foreach ( $this->mConns
as $conns2 ) {
841 foreach ( $conns2 as $conns3 ) {
842 foreach ( $conns3 as $conn ) {
843 if ( !$conn->ping() ) {
853 * Call a function with each open connection object
855 function forEachOpenConnection( $callback, $params = array() ) {
856 foreach ( $this->mConns
as $conns2 ) {
857 foreach ( $conns2 as $conns3 ) {
858 foreach ( $conns3 as $conn ) {
859 $mergedParams = array_merge( array( $conn ), $params );
860 call_user_func_array( $callback, $mergedParams );
867 * Get the hostname and lag time of the most-lagged slave.
868 * This is useful for maintenance scripts that need to throttle their updates.
869 * May attempt to open connections to slaves on the default DB.
870 * @param $wiki string Wiki ID, or false for the default database
872 function getMaxLag( $wiki = false ) {
875 foreach ( $this->mServers
as $i => $conn ) {
877 if ( $wiki === false ) {
878 $conn = $this->getAnyOpenConnection( $i );
881 $conn = $this->openConnection( $i, $wiki );
886 $lag = $conn->getLag();
887 if ( $lag > $maxLag ) {
889 $host = $this->mServers
[$i]['host'];
892 return array( $host, $maxLag );
896 * Get lag time for each server
897 * Results are cached for a short time in memcached, and indefinitely in the process cache
899 function getLagTimes( $wiki = false ) {
901 if ( isset( $this->mLagTimes
) ) {
902 return $this->mLagTimes
;
904 # No, send the request to the load monitor
905 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
906 return $this->mLagTimes
;
910 * Clear the cache for getLagTimes
912 function clearLagTimeCache() {
913 $this->mLagTimes
= null;