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 = wfMsgNoDBForContent( 'readonly_lag' );
224 $i = $this->pickRandom( $currentLoads );
225 $laggedSlaveMode = true;
229 if ( $i === false ) {
230 # pickRandom() returned false
231 # This is permanent and means the configuration or the load monitor
232 # wants us to return false.
233 wfDebugLog( 'connect', __METHOD__
.": pickRandom() returned false\n" );
234 wfProfileOut( __METHOD__
);
238 wfDebugLog( 'connect', __METHOD__
.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
239 $conn = $this->openConnection( $i, $wiki );
242 wfDebugLog( 'connect', __METHOD__
.": Failed connecting to $i/$wiki\n" );
243 unset( $nonErrorLoads[$i] );
244 unset( $currentLoads[$i] );
248 // Perform post-connection backoff
249 $threshold = isset( $this->mServers
[$i]['max threads'] )
250 ?
$this->mServers
[$i]['max threads'] : false;
251 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
253 // Decrement reference counter, we are finished with this connection.
254 // It will be incremented for the caller later.
255 if ( $wiki !== false ) {
256 $this->reuseConnection( $conn );
260 # Post-connection overload, don't use this server for now
261 $totalThreadsConnected +
= $backoff;
262 $overloadedServers++
;
263 unset( $currentLoads[$i] );
270 # No server found yet
273 # If all servers were down, quit now
274 if ( !count( $nonErrorLoads ) ) {
275 wfDebugLog( 'connect', "All servers down\n" );
279 # Some servers must have been overloaded
280 if ( $overloadedServers == 0 ) {
281 throw new MWException( __METHOD__
.": unexpectedly found no overloaded servers" );
283 # Back off for a while
284 # Scale the sleep time by the number of connected threads, to produce a
285 # roughly constant global poll rate
286 $avgThreads = $totalThreadsConnected / $overloadedServers;
287 $totalElapsed +
= $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
288 } while ( $totalElapsed < $timeout );
290 if ( $totalElapsed >= $timeout ) {
291 wfDebugLog( 'connect', "All servers busy\n" );
292 $this->mErrorConnection
= false;
293 $this->mLastError
= 'All servers busy';
296 if ( $i !== false ) {
297 # Slave connection successful
298 # Wait for the session master pos for a short time
299 if ( $this->mWaitForPos
&& $i > 0 ) {
300 if ( !$this->doWait( $i ) ) {
301 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
304 if ( $this->mReadIndex
<=0 && $this->mLoads
[$i]>0 && $i !== false ) {
305 $this->mReadIndex
= $i;
308 wfProfileOut( __METHOD__
);
313 * Wait for a specified number of microseconds, and return the period waited
315 function sleep( $t ) {
316 wfProfileIn( __METHOD__
);
317 wfDebug( __METHOD__
.": waiting $t us\n" );
319 wfProfileOut( __METHOD__
);
324 * Set the master wait position
325 * If a DB_SLAVE connection has been opened already, waits
326 * Otherwise sets a variable telling it to wait if such a connection is opened
328 public function waitFor( $pos ) {
329 wfProfileIn( __METHOD__
);
330 $this->mWaitForPos
= $pos;
331 $i = $this->mReadIndex
;
334 if ( !$this->doWait( $i ) ) {
335 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
336 $this->mLaggedSlaveMode
= true;
339 wfProfileOut( __METHOD__
);
343 * Get any open connection to a given server index, local or foreign
344 * Returns false if there is no connection open
346 function getAnyOpenConnection( $i ) {
347 foreach ( $this->mConns
as $conns ) {
348 if ( !empty( $conns[$i] ) ) {
349 return reset( $conns[$i] );
356 * Wait for a given slave to catch up to the master pos stored in $this
358 function doWait( $index ) {
359 # Find a connection to wait on
360 $conn = $this->getAnyOpenConnection( $index );
362 wfDebug( __METHOD__
. ": no connection open\n" );
366 wfDebug( __METHOD__
.": Waiting for slave #$index to catch up...\n" );
367 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
369 if ( $result == -1 ||
is_null( $result ) ) {
370 # Timed out waiting for slave, use master instead
371 wfDebug( __METHOD__
.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
374 wfDebug( __METHOD__
.": Done\n" );
380 * Get a connection by index
381 * This is the main entry point for this class.
383 * @param $i Integer: server index
384 * @param $groups Array: query groups
385 * @param $wiki String: wiki ID
387 * @return DatabaseBase
389 public function &getConnection( $i, $groups = array(), $wiki = false ) {
390 wfProfileIn( __METHOD__
);
392 if ( $i == DB_LAST
) {
393 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with deprecated server index DB_LAST' );
394 } elseif ( $i === null ||
$i === false ) {
395 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with invalid server index' );
398 if ( $wiki === wfWikiID() ) {
403 if ( $i == DB_MASTER
) {
404 $i = $this->getWriterIndex();
405 } elseif ( !is_array( $groups ) ) {
406 $groupIndex = $this->getReaderIndex( $groups, $wiki );
407 if ( $groupIndex !== false ) {
408 $serverName = $this->getServerName( $groupIndex );
409 wfDebug( __METHOD__
.": using server $serverName for group $groups\n" );
413 foreach ( $groups as $group ) {
414 $groupIndex = $this->getReaderIndex( $group, $wiki );
415 if ( $groupIndex !== false ) {
416 $serverName = $this->getServerName( $groupIndex );
417 wfDebug( __METHOD__
.": using server $serverName for group $group\n" );
424 # Operation-based index
425 if ( $i == DB_SLAVE
) {
426 $i = $this->getReaderIndex( false, $wiki );
427 # Couldn't find a working server in getReaderIndex()?
428 if ( $i === false ) {
429 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
430 $this->reportConnectionError( $this->mErrorConnection
);
431 wfProfileOut( __METHOD__
);
436 # Now we have an explicit index into the servers array
437 $conn = $this->openConnection( $i, $wiki );
439 $this->reportConnectionError( $this->mErrorConnection
);
442 wfProfileOut( __METHOD__
);
447 * Mark a foreign connection as being available for reuse under a different
448 * DB name or prefix. This mechanism is reference-counted, and must be called
449 * the same number of times as getConnection() to work.
451 public function reuseConnection( $conn ) {
452 $serverIndex = $conn->getLBInfo('serverIndex');
453 $refCount = $conn->getLBInfo('foreignPoolRefCount');
454 $dbName = $conn->getDBname();
455 $prefix = $conn->tablePrefix();
456 if ( strval( $prefix ) !== '' ) {
457 $wiki = "$dbName-$prefix";
461 if ( $serverIndex === null ||
$refCount === null ) {
462 wfDebug( __METHOD__
.": this connection was not opened as a foreign connection\n" );
464 * This can happen in code like:
465 * foreach ( $dbs as $db ) {
466 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
468 * $lb->reuseConnection( $conn );
470 * When a connection to the local DB is opened in this way, reuseConnection()
475 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
476 throw new MWException( __METHOD__
.": connection not found, has the connection been freed already?" );
478 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
479 if ( $refCount <= 0 ) {
480 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
481 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
482 wfDebug( __METHOD__
.": freed connection $serverIndex/$wiki\n" );
484 wfDebug( __METHOD__
.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
489 * Open a connection to the server given by the specified index
490 * Index must be an actual index into the array.
491 * If the server is already open, returns it.
493 * On error, returns false, and the connection which caused the
494 * error will be available via $this->mErrorConnection.
496 * @param $i Integer: server index
497 * @param $wiki String: wiki ID to open
498 * @return DatabaseBase
502 function openConnection( $i, $wiki = false ) {
503 wfProfileIn( __METHOD__
);
504 if ( $wiki !== false ) {
505 $conn = $this->openForeignConnection( $i, $wiki );
506 wfProfileOut( __METHOD__
);
509 if ( isset( $this->mConns
['local'][$i][0] ) ) {
510 $conn = $this->mConns
['local'][$i][0];
512 $server = $this->mServers
[$i];
513 $server['serverIndex'] = $i;
514 $conn = $this->reallyOpenConnection( $server, false );
515 if ( $conn->isOpen() ) {
516 $this->mConns
['local'][$i][0] = $conn;
518 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
519 $this->mErrorConnection
= $conn;
523 wfProfileOut( __METHOD__
);
528 * Open a connection to a foreign DB, or return one if it is already open.
530 * Increments a reference count on the returned connection which locks the
531 * connection to the requested wiki. This reference count can be
532 * decremented by calling reuseConnection().
534 * If a connection is open to the appropriate server already, but with the wrong
535 * database, it will be switched to the right database and returned, as long as
536 * it has been freed first with reuseConnection().
538 * On error, returns false, and the connection which caused the
539 * error will be available via $this->mErrorConnection.
541 * @param $i Integer: server index
542 * @param $wiki String: wiki ID to open
543 * @return DatabaseBase
545 function openForeignConnection( $i, $wiki ) {
546 wfProfileIn(__METHOD__
);
547 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
548 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
549 // Reuse an already-used connection
550 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
551 wfDebug( __METHOD__
.": reusing connection $i/$wiki\n" );
552 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
553 // Reuse a free connection for the same wiki
554 $conn = $this->mConns
['foreignFree'][$i][$wiki];
555 unset( $this->mConns
['foreignFree'][$i][$wiki] );
556 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
557 wfDebug( __METHOD__
.": reusing free connection $i/$wiki\n" );
558 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
559 // Reuse a connection from another wiki
560 $conn = reset( $this->mConns
['foreignFree'][$i] );
561 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
563 if ( !$conn->selectDB( $dbName ) ) {
564 $this->mLastError
= "Error selecting database $dbName on server " .
565 $conn->getServer() . " from client host " . wfHostname() . "\n";
566 $this->mErrorConnection
= $conn;
569 $conn->tablePrefix( $prefix );
570 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
571 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
572 wfDebug( __METHOD__
.": reusing free connection from $oldWiki for $wiki\n" );
575 // Open a new connection
576 $server = $this->mServers
[$i];
577 $server['serverIndex'] = $i;
578 $server['foreignPoolRefCount'] = 0;
579 $conn = $this->reallyOpenConnection( $server, $dbName );
580 if ( !$conn->isOpen() ) {
581 wfDebug( __METHOD__
.": error opening connection for $i/$wiki\n" );
582 $this->mErrorConnection
= $conn;
585 $conn->tablePrefix( $prefix );
586 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
587 wfDebug( __METHOD__
.": opened new connection for $i/$wiki\n" );
591 // Increment reference count
593 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
594 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
596 wfProfileOut(__METHOD__
);
601 * Test if the specified index represents an open connection
603 * @param $index Integer: server index
606 function isOpen( $index ) {
607 if( !is_integer( $index ) ) {
610 return (bool)$this->getAnyOpenConnection( $index );
614 * Really opens a connection. Uncached.
615 * Returns a Database object whether or not the connection was successful.
618 function reallyOpenConnection( $server, $dbNameOverride = false ) {
619 if( !is_array( $server ) ) {
620 throw new MWException( 'You must update your load-balancing configuration. ' .
621 'See DefaultSettings.php entry for $wgDBservers.' );
624 $host = $server['host'];
625 $dbname = $server['dbname'];
627 if ( $dbNameOverride !== false ) {
628 $server['dbname'] = $dbname = $dbNameOverride;
632 wfDebug( "Connecting to $host $dbname...\n" );
633 $db = DatabaseBase
::newFromType( $server['type'], $server );
634 if ( $db->isOpen() ) {
635 wfDebug( "Connected to $host $dbname.\n" );
637 wfDebug( "Connection failed to $host $dbname.\n" );
639 $db->setLBInfo( $server );
640 if ( isset( $server['fakeSlaveLag'] ) ) {
641 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
643 if ( isset( $server['fakeMaster'] ) ) {
644 $db->setFakeMaster( true );
649 function reportConnectionError( &$conn ) {
650 wfProfileIn( __METHOD__
);
652 if ( !is_object( $conn ) ) {
653 // No last connection, probably due to all servers being too busy
654 wfLogDBError( "LB failure with no last connection\n" );
655 $conn = new Database
;
656 // If all servers were busy, mLastError will contain something sensible
657 throw new DBConnectionError( $conn, $this->mLastError
);
659 $server = $conn->getProperty( 'mServer' );
660 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
661 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
663 wfProfileOut( __METHOD__
);
666 function getWriterIndex() {
671 * Returns true if the specified index is a valid server index
673 function haveIndex( $i ) {
674 return array_key_exists( $i, $this->mServers
);
678 * Returns true if the specified index is valid and has non-zero load
680 function isNonZeroLoad( $i ) {
681 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
685 * Get the number of defined servers (not the number of open connections)
687 function getServerCount() {
688 return count( $this->mServers
);
692 * Get the host name or IP address of the server with the specified index
693 * Prefer a readable name if available.
695 function getServerName( $i ) {
696 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
697 return $this->mServers
[$i]['hostName'];
698 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
699 return $this->mServers
[$i]['host'];
706 * Return the server info structure for a given index, or false if the index is invalid.
708 function getServerInfo( $i ) {
709 if ( isset( $this->mServers
[$i] ) ) {
710 return $this->mServers
[$i];
717 * Get the current master position for chronology control purposes
720 function getMasterPos() {
721 # If this entire request was served from a slave without opening a connection to the
722 # master (however unlikely that may be), then we can fetch the position from the slave.
723 $masterConn = $this->getAnyOpenConnection( 0 );
724 if ( !$masterConn ) {
725 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
726 $conn = $this->getAnyOpenConnection( $i );
728 wfDebug( "Master pos fetched from slave\n" );
729 return $conn->getSlavePos();
733 wfDebug( "Master pos fetched from master\n" );
734 return $masterConn->getMasterPos();
740 * Close all open connections
742 function closeAll() {
743 foreach ( $this->mConns
as $conns2 ) {
744 foreach ( $conns2 as $conns3 ) {
745 foreach ( $conns3 as $conn ) {
750 $this->mConns
= array(
752 'foreignFree' => array(),
753 'foreignUsed' => array(),
758 * Deprecated function, typo in function name
760 function closeConnecton( $conn ) {
761 $this->closeConnection( $conn );
766 * Using this function makes sure the LoadBalancer knows the connection is closed.
767 * If you use $conn->close() directly, the load balancer won't update its state.
771 function closeConnection( $conn ) {
773 foreach ( $this->mConns
as $i1 => $conns2 ) {
774 foreach ( $conns2 as $i2 => $conns3 ) {
775 foreach ( $conns3 as $i3 => $candidateConn ) {
776 if ( $conn === $candidateConn ) {
778 unset( $this->mConns
[$i1][$i2][$i3] );
791 * Commit transactions on all open connections
793 function commitAll() {
794 foreach ( $this->mConns
as $conns2 ) {
795 foreach ( $conns2 as $conns3 ) {
796 foreach ( $conns3 as $conn ) {
803 /* Issue COMMIT only on master, only if queries were done on connection */
804 function commitMasterChanges() {
805 // Always 0, but who knows.. :)
806 $masterIndex = $this->getWriterIndex();
807 foreach ( $this->mConns
as $conns2 ) {
808 if ( empty( $conns2[$masterIndex] ) ) {
811 foreach ( $conns2[$masterIndex] as $conn ) {
812 if ( $conn->doneWrites() ) {
819 function waitTimeout( $value = null ) {
820 return wfSetVar( $this->mWaitTimeout
, $value );
823 function getLaggedSlaveMode() {
824 return $this->mLaggedSlaveMode
;
827 /* Disables/enables lag checks */
828 function allowLagged($mode=null) {
830 return $this->mAllowLagged
;
831 $this->mAllowLagged
=$mode;
836 foreach ( $this->mConns
as $conns2 ) {
837 foreach ( $conns2 as $conns3 ) {
838 foreach ( $conns3 as $conn ) {
839 if ( !$conn->ping() ) {
849 * Call a function with each open connection object
851 function forEachOpenConnection( $callback, $params = array() ) {
852 foreach ( $this->mConns
as $conns2 ) {
853 foreach ( $conns2 as $conns3 ) {
854 foreach ( $conns3 as $conn ) {
855 $mergedParams = array_merge( array( $conn ), $params );
856 call_user_func_array( $callback, $mergedParams );
863 * Get the hostname and lag time of the most-lagged slave.
864 * This is useful for maintenance scripts that need to throttle their updates.
865 * May attempt to open connections to slaves on the default DB.
866 * @param $wiki string Wiki ID, or false for the default database
868 function getMaxLag( $wiki = false ) {
871 foreach ( $this->mServers
as $i => $conn ) {
873 if ( $wiki === false ) {
874 $conn = $this->getAnyOpenConnection( $i );
877 $conn = $this->openConnection( $i, $wiki );
882 $lag = $conn->getLag();
883 if ( $lag > $maxLag ) {
885 $host = $this->mServers
[$i]['host'];
888 return array( $host, $maxLag );
892 * Get lag time for each server
893 * Results are cached for a short time in memcached, and indefinitely in the process cache
895 function getLagTimes( $wiki = false ) {
897 if ( isset( $this->mLagTimes
) ) {
898 return $this->mLagTimes
;
900 # No, send the request to the load monitor
901 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
902 return $this->mLagTimes
;
906 * Clear the cache for getLagTimes
908 function clearLagTimeCache() {
909 $this->mLagTimes
= null;