8 * Database load balancing object
16 /* private */ var $mServers, $mConns, $mLoads, $mGroupLoads;
17 /* private */ var $mFailFunction, $mErrorConnection;
18 /* private */ var $mReadIndex, $mLastIndex, $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 array $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['failFunction'] ) ) {
39 $this->mFailFunction
= $params['failFunction'];
41 $this->mFailFunction
= false;
43 if ( isset( $params['waitTimeout'] ) ) {
44 $this->mWaitTimeout
= $params['waitTimeout'];
46 $this->mWaitTimeout
= 10;
49 $this->mReadIndex
= -1;
50 $this->mWriteIndex
= -1;
51 $this->mConns
= array(
53 'foreignUsed' => array(),
54 'foreignFree' => array() );
55 $this->mLastIndex
= -1;
56 $this->mLoads
= array();
57 $this->mWaitForPos
= false;
58 $this->mLaggedSlaveMode
= false;
59 $this->mErrorConnection
= false;
60 $this->mAllowLag
= false;
61 $this->mLoadMonitorClass
= isset( $params['loadMonitor'] )
62 ?
$params['loadMonitor'] : 'LoadMonitor_MySQL';
64 foreach( $params['servers'] as $i => $server ) {
65 $this->mLoads
[$i] = $server['load'];
66 if ( isset( $server['groupLoads'] ) ) {
67 foreach ( $server['groupLoads'] as $group => $ratio ) {
68 if ( !isset( $this->mGroupLoads
[$group] ) ) {
69 $this->mGroupLoads
[$group] = array();
71 $this->mGroupLoads
[$group][$i] = $ratio;
77 static function newFromParams( $servers, $failFunction = false, $waitTimeout = 10 )
79 return new LoadBalancer( $servers, $failFunction, $waitTimeout );
83 * Get a LoadMonitor instance
85 function getLoadMonitor() {
86 if ( !isset( $this->mLoadMonitor
) ) {
87 $class = $this->mLoadMonitorClass
;
88 $this->mLoadMonitor
= new $class( $this );
90 return $this->mLoadMonitor
;
94 * Get or set arbitrary data used by the parent object, usually an LBFactory
96 function parentInfo( $x = null ) {
97 return wfSetVar( $this->mParentInfo
, $x );
101 * Given an array of non-normalised probabilities, this function will select
102 * an element and return the appropriate key
104 function pickRandom( $weights )
106 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
110 $sum = array_sum( $weights );
112 # No loads on any of them
113 # In previous versions, this triggered an unweighted random selection,
114 # but this feature has been removed as of April 2006 to allow for strict
115 # separation of query groups.
118 $max = mt_getrandmax();
119 $rand = mt_rand(0, $max) / $max * $sum;
122 foreach ( $weights as $i => $w ) {
124 if ( $sum >= $rand ) {
131 function getRandomNonLagged( $loads, $wiki = false ) {
132 # Unset excessively lagged servers
133 $lags = $this->getLagTimes( $wiki );
134 foreach ( $lags as $i => $lag ) {
135 if ( $i != 0 && isset( $this->mServers
[$i]['max lag'] ) ) {
136 if ( $lag === false ) {
137 wfDebug( "Server #$i is not replicating\n" );
139 } elseif ( $lag > $this->mServers
[$i]['max lag'] ) {
140 wfDebug( "Server #$i is excessively lagged ($lag seconds)\n" );
146 # Find out if all the slaves with non-zero load are lagged
148 foreach ( $loads as $load ) {
152 # No appropriate DB servers except maybe the master and some slaves with zero load
153 # Do NOT use the master
154 # Instead, this function will return false, triggering read-only mode,
155 # and a lagged slave will be used instead.
159 if ( count( $loads ) == 0 ) {
163 #wfDebugLog( 'connect', var_export( $loads, true ) );
165 # Return a random representative of the remainder
166 return $this->pickRandom( $loads );
170 * Get the index of the reader connection, which may be a slave
171 * This takes into account load ratios and lag times. It should
172 * always return a consistent index during a given invocation
174 * Side effect: opens connections to databases
176 function getReaderIndex( $group = false, $wiki = false, $attempts = false ) {
177 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
179 # FIXME: For now, only go through all this for mysql databases
180 if ($wgDBtype != 'mysql') {
181 return $this->getWriterIndex();
184 if ( count( $this->mServers
) == 1 ) {
185 # Skip the load balancing if there's only one server
187 } elseif ( $group === false and $this->mReadIndex
>= 0 ) {
188 # Shortcut if generic reader exists already
189 return $this->mReadIndex
;
192 wfProfileIn( __METHOD__
);
196 # convert from seconds to microseconds
197 $timeout = $wgDBClusterTimeout * 1e6
;
199 # Find the relevant load array
200 if ( $group !== false ) {
201 if ( isset( $this->mGroupLoads
[$group] ) ) {
202 $nonErrorLoads = $this->mGroupLoads
[$group];
204 # No loads for this group, return false and the caller can use some other group
205 wfDebug( __METHOD__
.": no loads for group $group\n" );
206 wfProfileOut( __METHOD__
);
210 $nonErrorLoads = $this->mLoads
;
213 if ( !$nonErrorLoads ) {
214 throw new MWException( "Empty server array given to LoadBalancer" );
217 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
218 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
222 $laggedSlaveMode = false;
224 # First try quickly looking through the available servers for a server that
227 $totalThreadsConnected = 0;
228 $overloadedServers = 0;
229 $currentLoads = $nonErrorLoads;
230 while ( count( $currentLoads ) ) {
231 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
232 $i = $this->pickRandom( $currentLoads );
234 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
235 if ( $i === false && count( $currentLoads ) != 0 ) {
236 # All slaves lagged. Switch to read-only mode
237 $wgReadOnly = wfMsgNoDBForContent( 'readonly_lag' );
238 $i = $this->pickRandom( $currentLoads );
239 $laggedSlaveMode = true;
243 if ( $i === false ) {
244 # pickRandom() returned false
245 # This is permanent and means the configuration or the load monitor
246 # wants us to return false.
247 wfDebugLog( 'connect', __METHOD__
.": pickRandom() returned false\n" );
248 wfProfileOut( __METHOD__
);
252 wfDebugLog( 'connect', __METHOD__
.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
253 $conn = $this->openConnection( $i, $wiki, $attempts );
256 wfDebugLog( 'connect', __METHOD__
.": Failed connecting to $i/$wiki\n" );
257 unset( $nonErrorLoads[$i] );
258 unset( $currentLoads[$i] );
262 // Perform post-connection backoff
263 $threshold = isset( $this->mServers
[$i]['max threads'] )
264 ?
$this->mServers
[$i]['max threads'] : false;
265 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
267 // Decrement reference counter, we are finished with this connection.
268 // It will be incremented for the caller later.
269 if ( $wiki !== false ) {
270 $this->reuseConnection( $conn );
274 # Post-connection overload, don't use this server for now
275 $totalThreadsConnected +
= $backoff;
276 $overloadedServers++
;
277 unset( $currentLoads[$i] );
284 # No server found yet
287 # If all servers were down, quit now
288 if ( !count( $nonErrorLoads ) ) {
289 wfDebugLog( 'connect', "All servers down\n" );
293 # Some servers must have been overloaded
294 if ( $overloadedServers == 0 ) {
295 throw new MWException( __METHOD__
.": unexpectedly found no overloaded servers" );
297 # Back off for a while
298 # Scale the sleep time by the number of connected threads, to produce a
299 # roughly constant global poll rate
300 $avgThreads = $totalThreadsConnected / $overloadedServers;
301 $totalElapsed +
= $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
302 } while ( $totalElapsed < $timeout );
304 if ( $totalElapsed >= $timeout ) {
305 wfDebugLog( 'connect', "All servers busy\n" );
306 $this->mErrorConnection
= false;
307 $this->mLastError
= 'All servers busy';
310 if ( $i !== false ) {
311 # Slave connection successful
312 # Wait for the session master pos for a short time
313 if ( $this->mWaitForPos
&& $i > 0 ) {
314 if ( !$this->doWait( $i ) ) {
315 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
318 if ( $this->mReadIndex
<=0 && $this->mLoads
[$i]>0 && $i !== false ) {
319 $this->mReadIndex
= $i;
322 wfProfileOut( __METHOD__
);
327 * Wait for a specified number of microseconds, and return the period waited
329 function sleep( $t ) {
330 wfProfileIn( __METHOD__
);
331 wfDebug( __METHOD__
.": waiting $t us\n" );
333 wfProfileOut( __METHOD__
);
338 * Get a random server to use in a query group
339 * @deprecated use getReaderIndex
341 function getGroupIndex( $group ) {
342 return $this->getReaderIndex( $group );
346 * Set the master wait position
347 * If a DB_SLAVE connection has been opened already, waits
348 * Otherwise sets a variable telling it to wait if such a connection is opened
350 public function waitFor( $pos ) {
351 wfProfileIn( __METHOD__
);
352 $this->mWaitForPos
= $pos;
353 $i = $this->mReadIndex
;
356 if ( !$this->doWait( $i ) ) {
357 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
358 $this->mLaggedSlaveMode
= true;
361 wfProfileOut( __METHOD__
);
365 * Get any open connection to a given server index, local or foreign
366 * Returns false if there is no connection open
368 function getAnyOpenConnection( $i ) {
369 foreach ( $this->mConns
as $type => $conns ) {
370 if ( !empty( $conns[$i] ) ) {
371 return reset( $conns[$i] );
378 * Wait for a given slave to catch up to the master pos stored in $this
380 function doWait( $index ) {
381 # Find a connection to wait on
382 $conn = $this->getAnyOpenConnection( $index );
384 wfDebug( __METHOD__
. ": no connection open\n" );
388 wfDebug( __METHOD__
.": Waiting for slave #$index to catch up...\n" );
389 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
391 if ( $result == -1 ||
is_null( $result ) ) {
392 # Timed out waiting for slave, use master instead
393 wfDebug( __METHOD__
.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
396 wfDebug( __METHOD__
.": Done\n" );
402 * Get a connection by index
403 * This is the main entry point for this class.
404 * @param int $i Database
405 * @param array $groups Query groups
406 * @param string $wiki Wiki ID
407 * @param int $attempts Max DB connect attempts
410 public function &getConnection( $i, $groups = array(), $wiki = false, $attempts = false, $flags = 0 ) {
412 wfProfileIn( __METHOD__
);
414 if ( $wiki === wfWikiID() ) {
419 if ( $i == DB_MASTER
) {
420 $i = $this->getWriterIndex();
421 } elseif ( !is_array( $groups ) ) {
422 $groupIndex = $this->getReaderIndex( $groups, $wiki );
423 if ( $groupIndex !== false ) {
424 $serverName = $this->getServerName( $groupIndex );
425 wfDebug( __METHOD__
.": using server $serverName for group $groups\n" );
429 foreach ( $groups as $group ) {
430 $groupIndex = $this->getReaderIndex( $group, $wiki );
431 if ( $groupIndex !== false ) {
432 $serverName = $this->getServerName( $groupIndex );
433 wfDebug( __METHOD__
.": using server $serverName for group $group\n" );
440 # Operation-based index
441 if ( $i == DB_SLAVE
) {
442 $i = $this->getReaderIndex( false, $wiki, $attempts );
443 } elseif ( $i == DB_LAST
) {
444 # Just use $this->mLastIndex, which should already be set
445 $i = $this->mLastIndex
;
447 # Oh dear, not set, best to use the writer for safety
448 wfDebug( "Warning: DB_LAST used when there was no previous index\n" );
449 $i = $this->getWriterIndex();
452 # Couldn't find a working server in getReaderIndex()?
453 if ( $i === false ) {
454 if( $flags && self
::GRACEFUL
) {
457 $this->reportConnectionError( $this->mErrorConnection
);
460 # Now we have an explicit index into the servers array
461 $conn = $this->openConnection( $i, $wiki, $attempts );
462 if ( !$conn && !($flags & self
::GRACEFUL
) ) {
463 $this->reportConnectionError( $this->mErrorConnection
);
466 wfProfileOut( __METHOD__
);
471 * Mark a foreign connection as being available for reuse under a different
472 * DB name or prefix. This mechanism is reference-counted, and must be called
473 * the same number of times as getConnection() to work.
475 public function reuseConnection( $conn ) {
476 $serverIndex = $conn->getLBInfo('serverIndex');
477 $refCount = $conn->getLBInfo('foreignPoolRefCount');
478 $dbName = $conn->getDBname();
479 $prefix = $conn->tablePrefix();
480 if ( strval( $prefix ) !== '' ) {
481 $wiki = "$dbName-$prefix";
485 if ( $serverIndex === null ||
$refCount === null ) {
486 wfDebug( __METHOD__
.": this connection was not opened as a foreign connection\n" );
488 * This can happen in code like:
489 * foreach ( $dbs as $db ) {
490 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
492 * $lb->reuseConnection( $conn );
494 * When a connection to the local DB is opened in this way, reuseConnection()
499 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
500 throw new MWException( __METHOD__
.": connection not found, has the connection been freed already?" );
502 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
503 if ( $refCount <= 0 ) {
504 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
505 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
506 wfDebug( __METHOD__
.": freed connection $serverIndex/$wiki\n" );
508 wfDebug( __METHOD__
.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
513 * Open a connection to the server given by the specified index
514 * Index must be an actual index into the array.
515 * If the server is already open, returns it.
517 * On error, returns false, and the connection which caused the
518 * error will be available via $this->mErrorConnection.
520 * @param integer $i Server index
521 * @param string $wiki Wiki ID to open
522 * @param int $attempts Maximum connection attempts
527 function openConnection( $i, $wiki = false, $attempts = false ) {
528 wfProfileIn( __METHOD__
);
529 if ( $wiki !== false ) {
530 $conn = $this->openForeignConnection( $i, $wiki );
531 wfProfileOut( __METHOD__
);
534 if ( isset( $this->mConns
['local'][$i][0] ) ) {
535 $conn = $this->mConns
['local'][$i][0];
537 $server = $this->mServers
[$i];
538 $server['serverIndex'] = $i;
539 $conn = $this->reallyOpenConnection( $server, false, $attempts );
540 if ( $conn->isOpen() ) {
541 $this->mConns
['local'][$i][0] = $conn;
543 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
544 $this->mErrorConnection
= $conn;
548 $this->mLastIndex
= $i;
549 wfProfileOut( __METHOD__
);
554 * Open a connection to a foreign DB, or return one if it is already open.
556 * Increments a reference count on the returned connection which locks the
557 * connection to the requested wiki. This reference count can be
558 * decremented by calling reuseConnection().
560 * If a connection is open to the appropriate server already, but with the wrong
561 * database, it will be switched to the right database and returned, as long as
562 * it has been freed first with reuseConnection().
564 * On error, returns false, and the connection which caused the
565 * error will be available via $this->mErrorConnection.
567 * @param integer $i Server index
568 * @param string $wiki Wiki ID to open
571 function openForeignConnection( $i, $wiki ) {
572 wfProfileIn(__METHOD__
);
573 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
574 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
575 // Reuse an already-used connection
576 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
577 wfDebug( __METHOD__
.": reusing connection $i/$wiki\n" );
578 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
579 // Reuse a free connection for the same wiki
580 $conn = $this->mConns
['foreignFree'][$i][$wiki];
581 unset( $this->mConns
['foreignFree'][$i][$wiki] );
582 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
583 wfDebug( __METHOD__
.": reusing free connection $i/$wiki\n" );
584 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
585 // Reuse a connection from another wiki
586 $conn = reset( $this->mConns
['foreignFree'][$i] );
587 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
589 if ( !$conn->selectDB( $dbName ) ) {
591 $this->mLastError
= "Error selecting database $dbName on server " .
592 $conn->getServer() . " from client host {$wguname['nodename']}\n";
593 $this->mErrorConnection
= $conn;
596 $conn->tablePrefix( $prefix );
597 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
598 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
599 wfDebug( __METHOD__
.": reusing free connection from $oldWiki for $wiki\n" );
602 // Open a new connection
603 $server = $this->mServers
[$i];
604 $server['serverIndex'] = $i;
605 $server['foreignPoolRefCount'] = 0;
606 $conn = $this->reallyOpenConnection( $server, $dbName );
607 if ( !$conn->isOpen() ) {
608 wfDebug( __METHOD__
.": error opening connection for $i/$wiki\n" );
609 $this->mErrorConnection
= $conn;
612 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
613 wfDebug( __METHOD__
.": opened new connection for $i/$wiki\n" );
617 // Increment reference count
619 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
620 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
622 wfProfileOut(__METHOD__
);
627 * Test if the specified index represents an open connection
630 function isOpen( $index ) {
631 if( !is_integer( $index ) ) {
634 return (bool)$this->getAnyOpenConnection( $index );
638 * Really opens a connection. Uncached.
639 * Returns a Database object whether or not the connection was successful.
642 function reallyOpenConnection( $server, $dbNameOverride = false, $attempts = false ) {
643 if( !is_array( $server ) ) {
644 throw new MWException( 'You must update your load-balancing configuration. See DefaultSettings.php entry for $wgDBservers.' );
648 if ( $dbNameOverride !== false ) {
649 $dbname = $dbNameOverride;
652 # Get class for this database type
653 $class = 'Database' . ucfirst( $type );
656 wfDebug( "Connecting to $host $dbname...\n" );
657 $db = new $class( $host, $user, $password, $dbname, 1, $flags, 'get from global', $attempts );
658 if ( $db->isOpen() ) {
659 wfDebug( "Connected\n" );
661 wfDebug( "Failed\n" );
663 $db->setLBInfo( $server );
664 if ( isset( $server['fakeSlaveLag'] ) ) {
665 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
667 if ( isset( $server['fakeMaster'] ) ) {
668 $db->setFakeMaster( true );
673 function reportConnectionError( &$conn ) {
674 wfProfileIn( __METHOD__
);
675 # Prevent infinite recursion
677 static $reporting = false;
680 if ( !is_object( $conn ) ) {
681 // No last connection, probably due to all servers being too busy
682 $conn = new Database
;
683 if ( $this->mFailFunction
) {
684 $conn->failFunction( $this->mFailFunction
);
685 $conn->reportConnectionError( $this->mLastError
);
687 // If all servers were busy, mLastError will contain something sensible
688 throw new DBConnectionError( $conn, $this->mLastError
);
691 if ( $this->mFailFunction
) {
692 $conn->failFunction( $this->mFailFunction
);
694 $conn->failFunction( false );
696 $server = $conn->getProperty( 'mServer' );
697 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
701 wfProfileOut( __METHOD__
);
704 function getWriterIndex() {
709 * Returns true if the specified index is a valid server index
711 function haveIndex( $i ) {
712 return array_key_exists( $i, $this->mServers
);
716 * Returns true if the specified index is valid and has non-zero load
718 function isNonZeroLoad( $i ) {
719 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
723 * Get the number of defined servers (not the number of open connections)
725 function getServerCount() {
726 return count( $this->mServers
);
730 * Get the host name or IP address of the server with the specified index
731 * Prefer a readable name if available.
733 function getServerName( $i ) {
734 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
735 return $this->mServers
[$i]['hostName'];
736 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
737 return $this->mServers
[$i]['host'];
744 * Return the server info structure for a given index, or false if the index is invalid.
746 function getServerInfo( $i ) {
747 if ( isset( $this->mServers
[$i] ) ) {
748 return $this->mServers
[$i];
755 * Get the current master position for chronology control purposes
758 function getMasterPos() {
759 # If this entire request was served from a slave without opening a connection to the
760 # master (however unlikely that may be), then we can fetch the position from the slave.
761 $masterConn = $this->getAnyOpenConnection( 0 );
762 if ( !$masterConn ) {
763 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
764 $conn = $this->getAnyOpenConnection( $i );
766 wfDebug( "Master pos fetched from slave\n" );
767 return $conn->getSlavePos();
771 wfDebug( "Master pos fetched from master\n" );
772 return $masterConn->getMasterPos();
778 * Close all open connections
780 function closeAll() {
781 foreach ( $this->mConns
as $conns2 ) {
782 foreach ( $conns2 as $conns3 ) {
783 foreach ( $conns3 as $conn ) {
788 $this->mConns
= array(
790 'foreignFree' => array(),
791 'foreignUsed' => array(),
797 * Using this function makes sure the LoadBalancer knows the connection is closed.
798 * If you use $conn->close() directly, the load balancer won't update its state.
800 function closeConnecton( $conn ) {
802 foreach ( $this->mConns
as $i1 => $conns2 ) {
803 foreach ( $conns2 as $i2 => $conns3 ) {
804 foreach ( $conns3 as $i3 => $candidateConn ) {
805 if ( $conn === $candidateConn ) {
807 unset( $this->mConns
[$i1][$i2][$i3] );
820 * Commit transactions on all open connections
822 function commitAll() {
823 foreach ( $this->mConns
as $conns2 ) {
824 foreach ( $conns2 as $conns3 ) {
825 foreach ( $conns3 as $conn ) {
826 $conn->immediateCommit();
832 /* Issue COMMIT only on master, only if queries were done on connection */
833 function commitMasterChanges() {
834 // Always 0, but who knows.. :)
835 $masterIndex = $this->getWriterIndex();
836 foreach ( $this->mConns
as $type => $conns2 ) {
837 if ( empty( $conns2[$masterIndex] ) ) {
840 foreach ( $conns2[$masterIndex] as $conn ) {
841 if ( $conn->lastQuery() != '' ) {
848 function waitTimeout( $value = NULL ) {
849 return wfSetVar( $this->mWaitTimeout
, $value );
852 function getLaggedSlaveMode() {
853 return $this->mLaggedSlaveMode
;
856 /* Disables/enables lag checks */
857 function allowLagged($mode=null) {
859 return $this->mAllowLagged
;
860 $this->mAllowLagged
=$mode;
865 foreach ( $this->mConns
as $conns2 ) {
866 foreach ( $conns2 as $conns3 ) {
867 foreach ( $conns3 as $conn ) {
868 if ( !$conn->ping() ) {
878 * Call a function with each open connection object
880 function forEachOpenConnection( $callback, $params = array() ) {
881 foreach ( $this->mConns
as $conns2 ) {
882 foreach ( $conns2 as $conns3 ) {
883 foreach ( $conns3 as $conn ) {
884 $mergedParams = array_merge( array( $conn ), $params );
885 call_user_func_array( $callback, $mergedParams );
892 * Get the hostname and lag time of the most-lagged slave.
893 * This is useful for maintenance scripts that need to throttle their updates.
894 * May attempt to open connections to slaves on the default DB.
896 function getMaxLag() {
899 foreach ( $this->mServers
as $i => $conn ) {
900 $conn = $this->getAnyOpenConnection( $i );
902 $conn = $this->openConnection( $i );
907 $lag = $conn->getLag();
908 if ( $lag > $maxLag ) {
910 $host = $this->mServers
[$i]['host'];
913 return array( $host, $maxLag );
917 * Get lag time for each server
918 * Results are cached for a short time in memcached, and indefinitely in the process cache
920 function getLagTimes( $wiki = false ) {
922 if ( isset( $this->mLagTimes
) ) {
923 return $this->mLagTimes
;
925 # No, send the request to the load monitor
926 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
927 return $this->mLagTimes
;