8 * Database load balancing object
14 /* private */ var $mServers, $mConns, $mLoads, $mGroupLoads;
15 /* private */ var $mFailFunction, $mErrorConnection;
16 /* private */ var $mReadIndex, $mLastIndex, $mAllowLagged;
17 /* private */ var $mWaitForPos, $mWaitTimeout;
18 /* private */ var $mLaggedSlaveMode, $mLastError = 'Unknown error';
19 /* private */ var $mParentInfo, $mLagTimes;
20 /* private */ var $mLoadMonitorClass, $mLoadMonitor;
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.
29 function __construct( $params )
31 if ( !isset( $params['servers'] ) ) {
32 throw new MWException( __CLASS__
.': missing servers parameter' );
34 $this->mServers
= $params['servers'];
36 if ( isset( $params['failFunction'] ) ) {
37 $this->mFailFunction
= $params['failFunction'];
39 $this->mFailFunction
= false;
41 if ( isset( $params['waitTimeout'] ) ) {
42 $this->mWaitTimeout
= $params['waitTimeout'];
44 $this->mWaitTimeout
= 10;
47 $this->mReadIndex
= -1;
48 $this->mWriteIndex
= -1;
49 $this->mConns
= array(
51 'foreignUsed' => array(),
52 'foreignFree' => array() );
53 $this->mLastIndex
= -1;
54 $this->mLoads
= array();
55 $this->mWaitForPos
= false;
56 $this->mLaggedSlaveMode
= false;
57 $this->mErrorConnection
= false;
58 $this->mAllowLag
= false;
59 $this->mLoadMonitorClass
= isset( $params['loadMonitor'] )
60 ?
$params['loadMonitor'] : 'LoadMonitor_MySQL';
62 foreach( $params['servers'] as $i => $server ) {
63 $this->mLoads
[$i] = $server['load'];
64 if ( isset( $server['groupLoads'] ) ) {
65 foreach ( $server['groupLoads'] as $group => $ratio ) {
66 if ( !isset( $this->mGroupLoads
[$group] ) ) {
67 $this->mGroupLoads
[$group] = array();
69 $this->mGroupLoads
[$group][$i] = $ratio;
75 static function newFromParams( $servers, $failFunction = false, $waitTimeout = 10 )
77 return new LoadBalancer( $servers, $failFunction, $waitTimeout );
81 * Get a LoadMonitor instance
83 function getLoadMonitor() {
84 if ( !isset( $this->mLoadMonitor
) ) {
85 $class = $this->mLoadMonitorClass
;
86 $this->mLoadMonitor
= new $class( $this );
88 return $this->mLoadMonitor
;
92 * Get or set arbitrary data used by the parent object, usually an LBFactory
94 function parentInfo( $x = null ) {
95 return wfSetVar( $this->mParentInfo
, $x );
99 * Given an array of non-normalised probabilities, this function will select
100 * an element and return the appropriate key
102 function pickRandom( $weights )
104 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
108 $sum = array_sum( $weights );
110 # No loads on any of them
111 # In previous versions, this triggered an unweighted random selection,
112 # but this feature has been removed as of April 2006 to allow for strict
113 # separation of query groups.
116 $max = mt_getrandmax();
117 $rand = mt_rand(0, $max) / $max * $sum;
120 foreach ( $weights as $i => $w ) {
122 if ( $sum >= $rand ) {
129 function getRandomNonLagged( $loads, $wiki = false ) {
130 # Unset excessively lagged servers
131 $lags = $this->getLagTimes( $wiki );
132 foreach ( $lags as $i => $lag ) {
133 if ( $i != 0 && isset( $this->mServers
[$i]['max lag'] ) ) {
134 if ( $lag === false ) {
135 wfDebug( "Server #$i is not replicating\n" );
137 } elseif ( $lag > $this->mServers
[$i]['max lag'] ) {
138 wfDebug( "Server #$i is excessively lagged ($lag seconds)\n" );
144 # Find out if all the slaves with non-zero load are lagged
146 foreach ( $loads as $load ) {
150 # No appropriate DB servers except maybe the master and some slaves with zero load
151 # Do NOT use the master
152 # Instead, this function will return false, triggering read-only mode,
153 # and a lagged slave will be used instead.
157 if ( count( $loads ) == 0 ) {
161 #wfDebugLog( 'connect', var_export( $loads, true ) );
163 # Return a random representative of the remainder
164 return $this->pickRandom( $loads );
168 * Get the index of the reader connection, which may be a slave
169 * This takes into account load ratios and lag times. It should
170 * always return a consistent index during a given invocation
172 * Side effect: opens connections to databases
174 function getReaderIndex( $group = false, $wiki = false ) {
175 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
177 # FIXME: For now, only go through all this for mysql databases
178 if ($wgDBtype != 'mysql') {
179 return $this->getWriterIndex();
182 if ( count( $this->mServers
) == 1 ) {
183 # Skip the load balancing if there's only one server
185 } elseif ( $group === false and $this->mReadIndex
>= 0 ) {
186 # Shortcut if generic reader exists already
187 return $this->mReadIndex
;
190 wfProfileIn( __METHOD__
);
194 # convert from seconds to microseconds
195 $timeout = $wgDBClusterTimeout * 1e6
;
197 # Find the relevant load array
198 if ( $group !== false ) {
199 if ( isset( $this->mGroupLoads
[$group] ) ) {
200 $nonErrorLoads = $this->mGroupLoads
[$group];
202 # No loads for this group, return false and the caller can use some other group
203 wfDebug( __METHOD__
.": no loads for group $group\n" );
204 wfProfileOut( __METHOD__
);
208 $nonErrorLoads = $this->mLoads
;
211 if ( !$nonErrorLoads ) {
212 throw new MWException( "Empty server array given to LoadBalancer" );
215 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
216 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
220 $laggedSlaveMode = false;
222 # First try quickly looking through the available servers for a server that
225 $totalThreadsConnected = 0;
226 $overloadedServers = 0;
227 $currentLoads = $nonErrorLoads;
228 while ( count( $currentLoads ) ) {
229 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
230 $i = $this->pickRandom( $currentLoads );
232 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
233 if ( $i === false && count( $currentLoads ) != 0 ) {
234 # All slaves lagged. Switch to read-only mode
235 $wgReadOnly = wfMsgNoDBForContent( 'readonly_lag' );
236 $i = $this->pickRandom( $currentLoads );
237 $laggedSlaveMode = true;
241 if ( $i === false ) {
242 # pickRandom() returned false
243 # This is permanent and means the configuration or the load monitor
244 # wants us to return false.
245 wfDebugLog( 'connect', __METHOD__
.": pickRandom() returned false\n" );
246 wfProfileOut( __METHOD__
);
250 wfDebugLog( 'connect', __METHOD__
.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
251 $conn = $this->openConnection( $i, $wiki );
254 wfDebugLog( 'connect', __METHOD__
.": Failed connecting to $i/$wiki\n" );
255 unset( $nonErrorLoads[$i] );
256 unset( $currentLoads[$i] );
260 // Perform post-connection backoff
261 $threshold = isset( $this->mServers
[$i]['max threads'] )
262 ?
$this->mServers
[$i]['max threads'] : false;
263 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
265 // Decrement reference counter, we are finished with this connection.
266 // It will be incremented for the caller later.
267 if ( $wiki !== false ) {
268 $this->reuseConnection( $conn );
272 # Post-connection overload, don't use this server for now
273 $totalThreadsConnected +
= $backoff;
274 $overloadedServers++
;
275 unset( $currentLoads[$i] );
282 # No server found yet
285 # If all servers were down, quit now
286 if ( !count( $nonErrorLoads ) ) {
287 wfDebugLog( 'connect', "All servers down\n" );
291 # Some servers must have been overloaded
292 if ( $overloadedServers == 0 ) {
293 throw new MWException( __METHOD__
.": unexpectedly found no overloaded servers" );
295 # Back off for a while
296 # Scale the sleep time by the number of connected threads, to produce a
297 # roughly constant global poll rate
298 $avgThreads = $totalThreadsConnected / $overloadedServers;
299 $totalElapsed +
= $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
300 } while ( $totalElapsed < $timeout );
302 if ( $totalElapsed >= $timeout ) {
303 wfDebugLog( 'connect', "All servers busy\n" );
304 $this->mErrorConnection
= false;
305 $this->mLastError
= 'All servers busy';
308 if ( $i !== false ) {
309 # Slave connection successful
310 # Wait for the session master pos for a short time
311 if ( $this->mWaitForPos
&& $i > 0 ) {
312 if ( !$this->doWait( $i ) ) {
313 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
316 if ( $this->mReadIndex
<=0 && $this->mLoads
[$i]>0 && $i !== false ) {
317 $this->mReadIndex
= $i;
320 wfProfileOut( __METHOD__
);
325 * Wait for a specified number of microseconds, and return the period waited
327 function sleep( $t ) {
328 wfProfileIn( __METHOD__
);
329 wfDebug( __METHOD__
.": waiting $t us\n" );
331 wfProfileOut( __METHOD__
);
336 * Get a random server to use in a query group
337 * @deprecated use getReaderIndex
339 function getGroupIndex( $group ) {
340 return $this->getReaderIndex( $group );
344 * Set the master wait position
345 * If a DB_SLAVE connection has been opened already, waits
346 * Otherwise sets a variable telling it to wait if such a connection is opened
348 public function waitFor( $pos ) {
349 wfProfileIn( __METHOD__
);
350 $this->mWaitForPos
= $pos;
351 $i = $this->mReadIndex
;
354 if ( !$this->doWait( $i ) ) {
355 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
356 $this->mLaggedSlaveMode
= true;
359 wfProfileOut( __METHOD__
);
363 * Get any open connection to a given server index, local or foreign
364 * Returns false if there is no connection open
366 function getAnyOpenConnection( $i ) {
367 foreach ( $this->mConns
as $type => $conns ) {
368 if ( !empty( $conns[$i] ) ) {
369 return reset( $conns[$i] );
376 * Wait for a given slave to catch up to the master pos stored in $this
378 function doWait( $index ) {
379 # Find a connection to wait on
380 $conn = $this->getAnyOpenConnection( $index );
382 wfDebug( __METHOD__
. ": no connection open\n" );
386 wfDebug( __METHOD__
.": Waiting for slave #$index to catch up...\n" );
387 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
389 if ( $result == -1 ||
is_null( $result ) ) {
390 # Timed out waiting for slave, use master instead
391 wfDebug( __METHOD__
.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
394 wfDebug( __METHOD__
.": Done\n" );
400 * Get a connection by index
401 * This is the main entry point for this class.
403 public function &getConnection( $i, $groups = array(), $wiki = false ) {
405 wfProfileIn( __METHOD__
);
407 if ( $wiki === wfWikiID() ) {
412 if ( $i == DB_MASTER
) {
413 $i = $this->getWriterIndex();
414 } elseif ( !is_array( $groups ) ) {
415 $groupIndex = $this->getReaderIndex( $groups, $wiki );
416 if ( $groupIndex !== false ) {
417 $serverName = $this->getServerName( $groupIndex );
418 wfDebug( __METHOD__
.": using server $serverName for group $groups\n" );
422 foreach ( $groups as $group ) {
423 $groupIndex = $this->getReaderIndex( $group, $wiki );
424 if ( $groupIndex !== false ) {
425 $serverName = $this->getServerName( $groupIndex );
426 wfDebug( __METHOD__
.": using server $serverName for group $group\n" );
433 # Operation-based index
434 if ( $i == DB_SLAVE
) {
435 $i = $this->getReaderIndex( false, $wiki );
436 } elseif ( $i == DB_LAST
) {
437 # Just use $this->mLastIndex, which should already be set
438 $i = $this->mLastIndex
;
440 # Oh dear, not set, best to use the writer for safety
441 wfDebug( "Warning: DB_LAST used when there was no previous index\n" );
442 $i = $this->getWriterIndex();
445 # Couldn't find a working server in getReaderIndex()?
446 if ( $i === false ) {
447 $this->reportConnectionError( $this->mErrorConnection
);
450 # Now we have an explicit index into the servers array
451 $conn = $this->openConnection( $i, $wiki );
453 $this->reportConnectionError( $this->mErrorConnection
);
456 wfProfileOut( __METHOD__
);
461 * Mark a foreign connection as being available for reuse under a different
462 * DB name or prefix. This mechanism is reference-counted, and must be called
463 * the same number of times as getConnection() to work.
465 public function reuseConnection( $conn ) {
466 $serverIndex = $conn->getLBInfo('serverIndex');
467 $refCount = $conn->getLBInfo('foreignPoolRefCount');
468 $dbName = $conn->getDBname();
469 $prefix = $conn->tablePrefix();
470 if ( strval( $prefix ) !== '' ) {
471 $wiki = "$dbName-$prefix";
475 if ( $serverIndex === null ||
$refCount === null ) {
476 wfDebug( __METHOD__
.": this connection was not opened as a foreign connection\n" );
478 * This can happen in code like:
479 * foreach ( $dbs as $db ) {
480 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
482 * $lb->reuseConnection( $conn );
484 * When a connection to the local DB is opened in this way, reuseConnection()
489 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
490 throw new MWException( __METHOD__
.": connection not found, has the connection been freed already?" );
492 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
493 if ( $refCount <= 0 ) {
494 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
495 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
496 wfDebug( __METHOD__
.": freed connection $serverIndex/$wiki\n" );
498 wfDebug( __METHOD__
.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
503 * Open a connection to the server given by the specified index
504 * Index must be an actual index into the array.
505 * If the server is already open, returns it.
507 * On error, returns false, and the connection which caused the
508 * error will be available via $this->mErrorConnection.
510 * @param integer $i Server index
511 * @param string $wiki Wiki ID to open
516 function openConnection( $i, $wiki = false ) {
517 wfProfileIn( __METHOD__
);
518 if ( $wiki !== false ) {
519 $conn = $this->openForeignConnection( $i, $wiki );
520 wfProfileOut( __METHOD__
);
523 if ( isset( $this->mConns
['local'][$i][0] ) ) {
524 $conn = $this->mConns
['local'][$i][0];
526 $server = $this->mServers
[$i];
527 $server['serverIndex'] = $i;
528 $conn = $this->reallyOpenConnection( $server );
529 if ( $conn->isOpen() ) {
530 $this->mConns
['local'][$i][0] = $conn;
532 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
533 $this->mErrorConnection
= $conn;
537 $this->mLastIndex
= $i;
538 wfProfileOut( __METHOD__
);
543 * Open a connection to a foreign DB, or return one if it is already open.
545 * Increments a reference count on the returned connection which locks the
546 * connection to the requested wiki. This reference count can be
547 * decremented by calling reuseConnection().
549 * If a connection is open to the appropriate server already, but with the wrong
550 * database, it will be switched to the right database and returned, as long as
551 * it has been freed first with reuseConnection().
553 * On error, returns false, and the connection which caused the
554 * error will be available via $this->mErrorConnection.
556 * @param integer $i Server index
557 * @param string $wiki Wiki ID to open
560 function openForeignConnection( $i, $wiki ) {
561 wfProfileIn(__METHOD__
);
562 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
563 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
564 // Reuse an already-used connection
565 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
566 wfDebug( __METHOD__
.": reusing connection $i/$wiki\n" );
567 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
568 // Reuse a free connection for the same wiki
569 $conn = $this->mConns
['foreignFree'][$i][$wiki];
570 unset( $this->mConns
['foreignFree'][$i][$wiki] );
571 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
572 wfDebug( __METHOD__
.": reusing free connection $i/$wiki\n" );
573 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
574 // Reuse a connection from another wiki
575 $conn = reset( $this->mConns
['foreignFree'][$i] );
576 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
578 if ( !$conn->selectDB( $dbName ) ) {
580 $this->mLastError
= "Error selecting database $dbName on server " .
581 $conn->getServer() . " from client host {$wguname['nodename']}\n";
582 $this->mErrorConnection
= $conn;
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" );
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;
601 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
602 wfDebug( __METHOD__
.": opened new connection for $i/$wiki\n" );
606 // Increment reference count
608 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
609 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
611 wfProfileOut(__METHOD__
);
616 * Test if the specified index represents an open connection
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\n" );
650 wfDebug( "Failed\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__
);
664 # Prevent infinite recursion
666 static $reporting = false;
669 if ( !is_object( $conn ) ) {
670 // No last connection, probably due to all servers being too busy
671 $conn = new Database
;
672 if ( $this->mFailFunction
) {
673 $conn->failFunction( $this->mFailFunction
);
674 $conn->reportConnectionError( $this->mLastError
);
676 // If all servers were busy, mLastError will contain something sensible
677 throw new DBConnectionError( $conn, $this->mLastError
);
680 if ( $this->mFailFunction
) {
681 $conn->failFunction( $this->mFailFunction
);
683 $conn->failFunction( false );
685 $server = $conn->getProperty( 'mServer' );
686 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
690 wfProfileOut( __METHOD__
);
693 function getWriterIndex() {
698 * Returns true if the specified index is a valid server index
700 function haveIndex( $i ) {
701 return array_key_exists( $i, $this->mServers
);
705 * Returns true if the specified index is valid and has non-zero load
707 function isNonZeroLoad( $i ) {
708 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
712 * Get the number of defined servers (not the number of open connections)
714 function getServerCount() {
715 return count( $this->mServers
);
719 * Get the host name or IP address of the server with the specified index
720 * Prefer a readable name if available.
722 function getServerName( $i ) {
723 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
724 return $this->mServers
[$i]['hostName'];
725 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
726 return $this->mServers
[$i]['host'];
733 * Return the server info structure for a given index, or false if the index is invalid.
735 function getServerInfo( $i ) {
736 if ( isset( $this->mServers
[$i] ) ) {
737 return $this->mServers
[$i];
744 * Get the current master position for chronology control purposes
747 function getMasterPos() {
748 # If this entire request was served from a slave without opening a connection to the
749 # master (however unlikely that may be), then we can fetch the position from the slave.
750 $masterConn = $this->getAnyOpenConnection( 0 );
751 if ( !$masterConn ) {
752 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
753 $conn = $this->getAnyOpenConnection( $i );
755 wfDebug( "Master pos fetched from slave\n" );
756 return $conn->getSlavePos();
760 wfDebug( "Master pos fetched from master\n" );
761 return $masterConn->getMasterPos();
767 * Close all open connections
769 function closeAll() {
770 foreach ( $this->mConns
as $conns2 ) {
771 foreach ( $conns2 as $conns3 ) {
772 foreach ( $conns3 as $conn ) {
777 $this->mConns
= array(
779 'foreignFree' => array(),
780 'foreignUsed' => array(),
786 * Using this function makes sure the LoadBalancer knows the connection is closed.
787 * If you use $conn->close() directly, the load balancer won't update its state.
789 function closeConnecton( $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 ) {
815 $conn->immediateCommit();
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 $type => $conns2 ) {
826 if ( empty( $conns2[$masterIndex] ) ) {
829 foreach ( $conns2[$masterIndex] as $conn ) {
830 if ( $conn->lastQuery() != '' ) {
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.
885 function getMaxLag() {
888 foreach ( $this->mServers
as $i => $conn ) {
889 $conn = $this->getAnyOpenConnection( $i );
891 $conn = $this->openConnection( $i );
896 $lag = $conn->getLag();
897 if ( $lag > $maxLag ) {
899 $host = $this->mServers
[$i]['host'];
902 return array( $host, $maxLag );
906 * Get lag time for each server
907 * Results are cached for a short time in memcached, and indefinitely in the process cache
909 function getLagTimes( $wiki = false ) {
911 if ( isset( $this->mLagTimes
) ) {
912 return $this->mLagTimes
;
914 # No, send the request to the load monitor
915 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
916 return $this->mLagTimes
;