8 * Database load balancing object
14 /* private */ var $mServers, $mConns, $mLoads, $mGroupLoads;
15 /* private */ var $mFailFunction, $mErrorConnection;
16 /* private */ var $mReadIndex, $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->mLoads
= array();
54 $this->mWaitForPos
= false;
55 $this->mLaggedSlaveMode
= false;
56 $this->mErrorConnection
= false;
57 $this->mAllowLag
= false;
58 $this->mLoadMonitorClass
= isset( $params['loadMonitor'] )
59 ?
$params['loadMonitor'] : 'LoadMonitor_MySQL';
61 foreach( $params['servers'] as $i => $server ) {
62 $this->mLoads
[$i] = $server['load'];
63 if ( isset( $server['groupLoads'] ) ) {
64 foreach ( $server['groupLoads'] as $group => $ratio ) {
65 if ( !isset( $this->mGroupLoads
[$group] ) ) {
66 $this->mGroupLoads
[$group] = array();
68 $this->mGroupLoads
[$group][$i] = $ratio;
74 static function newFromParams( $servers, $failFunction = false, $waitTimeout = 10 )
76 return new LoadBalancer( $servers, $failFunction, $waitTimeout );
80 * Get a LoadMonitor instance
82 function getLoadMonitor() {
83 if ( !isset( $this->mLoadMonitor
) ) {
84 $class = $this->mLoadMonitorClass
;
85 $this->mLoadMonitor
= new $class( $this );
87 return $this->mLoadMonitor
;
91 * Get or set arbitrary data used by the parent object, usually an LBFactory
93 function parentInfo( $x = null ) {
94 return wfSetVar( $this->mParentInfo
, $x );
98 * Given an array of non-normalised probabilities, this function will select
99 * an element and return the appropriate key
101 function pickRandom( $weights )
103 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
107 $sum = array_sum( $weights );
109 # No loads on any of them
110 # In previous versions, this triggered an unweighted random selection,
111 # but this feature has been removed as of April 2006 to allow for strict
112 # separation of query groups.
115 $max = mt_getrandmax();
116 $rand = mt_rand(0, $max) / $max * $sum;
119 foreach ( $weights as $i => $w ) {
121 if ( $sum >= $rand ) {
128 function getRandomNonLagged( $loads, $wiki = false ) {
129 # Unset excessively lagged servers
130 $lags = $this->getLagTimes( $wiki );
131 foreach ( $lags as $i => $lag ) {
132 if ( $i != 0 && isset( $this->mServers
[$i]['max lag'] ) ) {
133 if ( $lag === false ) {
134 wfDebug( "Server #$i is not replicating\n" );
136 } elseif ( $lag > $this->mServers
[$i]['max lag'] ) {
137 wfDebug( "Server #$i is excessively lagged ($lag seconds)\n" );
143 # Find out if all the slaves with non-zero load are lagged
145 foreach ( $loads as $load ) {
149 # No appropriate DB servers except maybe the master and some slaves with zero load
150 # Do NOT use the master
151 # Instead, this function will return false, triggering read-only mode,
152 # and a lagged slave will be used instead.
156 if ( count( $loads ) == 0 ) {
160 #wfDebugLog( 'connect', var_export( $loads, true ) );
162 # Return a random representative of the remainder
163 return $this->pickRandom( $loads );
167 * Get the index of the reader connection, which may be a slave
168 * This takes into account load ratios and lag times. It should
169 * always return a consistent index during a given invocation
171 * Side effect: opens connections to databases
173 function getReaderIndex( $group = false, $wiki = false ) {
174 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
176 # FIXME: For now, only go through all this for mysql databases
177 if ($wgDBtype != 'mysql') {
178 return $this->getWriterIndex();
181 if ( count( $this->mServers
) == 1 ) {
182 # Skip the load balancing if there's only one server
184 } elseif ( $group === false and $this->mReadIndex
>= 0 ) {
185 # Shortcut if generic reader exists already
186 return $this->mReadIndex
;
189 wfProfileIn( __METHOD__
);
193 # convert from seconds to microseconds
194 $timeout = $wgDBClusterTimeout * 1e6
;
196 # Find the relevant load array
197 if ( $group !== false ) {
198 if ( isset( $this->mGroupLoads
[$group] ) ) {
199 $nonErrorLoads = $this->mGroupLoads
[$group];
201 # No loads for this group, return false and the caller can use some other group
202 wfDebug( __METHOD__
.": no loads for group $group\n" );
203 wfProfileOut( __METHOD__
);
207 $nonErrorLoads = $this->mLoads
;
210 if ( !$nonErrorLoads ) {
211 throw new MWException( "Empty server array given to LoadBalancer" );
214 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
215 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
219 $laggedSlaveMode = false;
221 # First try quickly looking through the available servers for a server that
224 $totalThreadsConnected = 0;
225 $overloadedServers = 0;
226 $currentLoads = $nonErrorLoads;
227 while ( count( $currentLoads ) ) {
228 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
229 $i = $this->pickRandom( $currentLoads );
231 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
232 if ( $i === false && count( $currentLoads ) != 0 ) {
233 # All slaves lagged. Switch to read-only mode
234 $wgReadOnly = wfMsgNoDBForContent( 'readonly_lag' );
235 $i = $this->pickRandom( $currentLoads );
236 $laggedSlaveMode = true;
240 if ( $i === false ) {
241 # pickRandom() returned false
242 # This is permanent and means the configuration or the load monitor
243 # wants us to return false.
244 wfDebugLog( 'connect', __METHOD__
.": pickRandom() returned false\n" );
245 wfProfileOut( __METHOD__
);
249 wfDebugLog( 'connect', __METHOD__
.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
250 $conn = $this->openConnection( $i, $wiki );
253 wfDebugLog( 'connect', __METHOD__
.": Failed connecting to $i/$wiki\n" );
254 unset( $nonErrorLoads[$i] );
255 unset( $currentLoads[$i] );
259 // Perform post-connection backoff
260 $threshold = isset( $this->mServers
[$i]['max threads'] )
261 ?
$this->mServers
[$i]['max threads'] : false;
262 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
264 // Decrement reference counter, we are finished with this connection.
265 // It will be incremented for the caller later.
266 if ( $wiki !== false ) {
267 $this->reuseConnection( $conn );
271 # Post-connection overload, don't use this server for now
272 $totalThreadsConnected +
= $backoff;
273 $overloadedServers++
;
274 unset( $currentLoads[$i] );
281 # No server found yet
284 # If all servers were down, quit now
285 if ( !count( $nonErrorLoads ) ) {
286 wfDebugLog( 'connect', "All servers down\n" );
290 # Some servers must have been overloaded
291 if ( $overloadedServers == 0 ) {
292 throw new MWException( __METHOD__
.": unexpectedly found no overloaded servers" );
294 # Back off for a while
295 # Scale the sleep time by the number of connected threads, to produce a
296 # roughly constant global poll rate
297 $avgThreads = $totalThreadsConnected / $overloadedServers;
298 $totalElapsed +
= $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
299 } while ( $totalElapsed < $timeout );
301 if ( $totalElapsed >= $timeout ) {
302 wfDebugLog( 'connect', "All servers busy\n" );
303 $this->mErrorConnection
= false;
304 $this->mLastError
= 'All servers busy';
307 if ( $i !== false ) {
308 # Slave connection successful
309 # Wait for the session master pos for a short time
310 if ( $this->mWaitForPos
&& $i > 0 ) {
311 if ( !$this->doWait( $i ) ) {
312 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
315 if ( $this->mReadIndex
<=0 && $this->mLoads
[$i]>0 && $i !== false ) {
316 $this->mReadIndex
= $i;
319 wfProfileOut( __METHOD__
);
324 * Wait for a specified number of microseconds, and return the period waited
326 function sleep( $t ) {
327 wfProfileIn( __METHOD__
);
328 wfDebug( __METHOD__
.": waiting $t us\n" );
330 wfProfileOut( __METHOD__
);
335 * Get a random server to use in a query group
336 * @deprecated use getReaderIndex
338 function getGroupIndex( $group ) {
339 return $this->getReaderIndex( $group );
343 * Set the master wait position
344 * If a DB_SLAVE connection has been opened already, waits
345 * Otherwise sets a variable telling it to wait if such a connection is opened
347 public function waitFor( $pos ) {
348 wfProfileIn( __METHOD__
);
349 $this->mWaitForPos
= $pos;
350 $i = $this->mReadIndex
;
353 if ( !$this->doWait( $i ) ) {
354 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
355 $this->mLaggedSlaveMode
= true;
358 wfProfileOut( __METHOD__
);
362 * Get any open connection to a given server index, local or foreign
363 * Returns false if there is no connection open
365 function getAnyOpenConnection( $i ) {
366 foreach ( $this->mConns
as $type => $conns ) {
367 if ( !empty( $conns[$i] ) ) {
368 return reset( $conns[$i] );
375 * Wait for a given slave to catch up to the master pos stored in $this
377 function doWait( $index ) {
378 # Find a connection to wait on
379 $conn = $this->getAnyOpenConnection( $index );
381 wfDebug( __METHOD__
. ": no connection open\n" );
385 wfDebug( __METHOD__
.": Waiting for slave #$index to catch up...\n" );
386 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
388 if ( $result == -1 ||
is_null( $result ) ) {
389 # Timed out waiting for slave, use master instead
390 wfDebug( __METHOD__
.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
393 wfDebug( __METHOD__
.": Done\n" );
399 * Get a connection by index
400 * This is the main entry point for this class.
401 * @param int $i Database
402 * @param array $groups Query groups
403 * @param string $wiki Wiki ID
405 public function &getConnection( $i, $groups = array(), $wiki = false ) {
407 wfProfileIn( __METHOD__
);
409 if ( $i == DB_LAST
) {
410 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with deprecated server index DB_LAST' );
411 } elseif ( $i === null ||
$i === false ) {
412 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with invalid server index' );
415 if ( $wiki === wfWikiID() ) {
420 if ( $i == DB_MASTER
) {
421 $i = $this->getWriterIndex();
422 } elseif ( !is_array( $groups ) ) {
423 $groupIndex = $this->getReaderIndex( $groups, $wiki );
424 if ( $groupIndex !== false ) {
425 $serverName = $this->getServerName( $groupIndex );
426 wfDebug( __METHOD__
.": using server $serverName for group $groups\n" );
430 foreach ( $groups as $group ) {
431 $groupIndex = $this->getReaderIndex( $group, $wiki );
432 if ( $groupIndex !== false ) {
433 $serverName = $this->getServerName( $groupIndex );
434 wfDebug( __METHOD__
.": using server $serverName for group $group\n" );
441 # Operation-based index
442 if ( $i == DB_SLAVE
) {
443 $i = $this->getReaderIndex( false, $wiki );
444 # Couldn't find a working server in getReaderIndex()?
445 if ( $i === false ) {
446 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
447 $this->reportConnectionError( $this->mErrorConnection
);
452 # Now we have an explicit index into the servers array
453 $conn = $this->openConnection( $i, $wiki );
455 $this->reportConnectionError( $this->mErrorConnection
);
458 wfProfileOut( __METHOD__
);
463 * Mark a foreign connection as being available for reuse under a different
464 * DB name or prefix. This mechanism is reference-counted, and must be called
465 * the same number of times as getConnection() to work.
467 public function reuseConnection( $conn ) {
468 $serverIndex = $conn->getLBInfo('serverIndex');
469 $refCount = $conn->getLBInfo('foreignPoolRefCount');
470 $dbName = $conn->getDBname();
471 $prefix = $conn->tablePrefix();
472 if ( strval( $prefix ) !== '' ) {
473 $wiki = "$dbName-$prefix";
477 if ( $serverIndex === null ||
$refCount === null ) {
478 wfDebug( __METHOD__
.": this connection was not opened as a foreign connection\n" );
480 * This can happen in code like:
481 * foreach ( $dbs as $db ) {
482 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
484 * $lb->reuseConnection( $conn );
486 * When a connection to the local DB is opened in this way, reuseConnection()
491 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
492 throw new MWException( __METHOD__
.": connection not found, has the connection been freed already?" );
494 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
495 if ( $refCount <= 0 ) {
496 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
497 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
498 wfDebug( __METHOD__
.": freed connection $serverIndex/$wiki\n" );
500 wfDebug( __METHOD__
.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
505 * Open a connection to the server given by the specified index
506 * Index must be an actual index into the array.
507 * If the server is already open, returns it.
509 * On error, returns false, and the connection which caused the
510 * error will be available via $this->mErrorConnection.
512 * @param integer $i Server index
513 * @param string $wiki Wiki ID to open
518 function openConnection( $i, $wiki = false ) {
519 wfProfileIn( __METHOD__
);
520 if ( $wiki !== false ) {
521 $conn = $this->openForeignConnection( $i, $wiki );
522 wfProfileOut( __METHOD__
);
525 if ( isset( $this->mConns
['local'][$i][0] ) ) {
526 $conn = $this->mConns
['local'][$i][0];
528 $server = $this->mServers
[$i];
529 $server['serverIndex'] = $i;
530 $conn = $this->reallyOpenConnection( $server, false );
531 if ( $conn->isOpen() ) {
532 $this->mConns
['local'][$i][0] = $conn;
534 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
535 $this->mErrorConnection
= $conn;
539 wfProfileOut( __METHOD__
);
544 * Open a connection to a foreign DB, or return one if it is already open.
546 * Increments a reference count on the returned connection which locks the
547 * connection to the requested wiki. This reference count can be
548 * decremented by calling reuseConnection().
550 * If a connection is open to the appropriate server already, but with the wrong
551 * database, it will be switched to the right database and returned, as long as
552 * it has been freed first with reuseConnection().
554 * On error, returns false, and the connection which caused the
555 * error will be available via $this->mErrorConnection.
557 * @param integer $i Server index
558 * @param string $wiki Wiki ID to open
561 function openForeignConnection( $i, $wiki ) {
562 wfProfileIn(__METHOD__
);
563 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
564 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
565 // Reuse an already-used connection
566 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
567 wfDebug( __METHOD__
.": reusing connection $i/$wiki\n" );
568 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
569 // Reuse a free connection for the same wiki
570 $conn = $this->mConns
['foreignFree'][$i][$wiki];
571 unset( $this->mConns
['foreignFree'][$i][$wiki] );
572 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
573 wfDebug( __METHOD__
.": reusing free connection $i/$wiki\n" );
574 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
575 // Reuse a connection from another wiki
576 $conn = reset( $this->mConns
['foreignFree'][$i] );
577 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
579 if ( !$conn->selectDB( $dbName ) ) {
581 $this->mLastError
= "Error selecting database $dbName on server " .
582 $conn->getServer() . " from client host {$wguname['nodename']}\n";
583 $this->mErrorConnection
= $conn;
586 $conn->tablePrefix( $prefix );
587 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
588 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
589 wfDebug( __METHOD__
.": reusing free connection from $oldWiki for $wiki\n" );
592 // Open a new connection
593 $server = $this->mServers
[$i];
594 $server['serverIndex'] = $i;
595 $server['foreignPoolRefCount'] = 0;
596 $conn = $this->reallyOpenConnection( $server, $dbName );
597 if ( !$conn->isOpen() ) {
598 wfDebug( __METHOD__
.": error opening connection for $i/$wiki\n" );
599 $this->mErrorConnection
= $conn;
602 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
603 wfDebug( __METHOD__
.": opened new connection for $i/$wiki\n" );
607 // Increment reference count
609 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
610 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
612 wfProfileOut(__METHOD__
);
617 * Test if the specified index represents an open connection
620 function isOpen( $index ) {
621 if( !is_integer( $index ) ) {
624 return (bool)$this->getAnyOpenConnection( $index );
628 * Really opens a connection. Uncached.
629 * Returns a Database object whether or not the connection was successful.
632 function reallyOpenConnection( $server, $dbNameOverride = false ) {
633 if( !is_array( $server ) ) {
634 throw new MWException( 'You must update your load-balancing configuration. See DefaultSettings.php entry for $wgDBservers.' );
638 if ( $dbNameOverride !== false ) {
639 $dbname = $dbNameOverride;
642 if( !isset( $prefix ) ){
644 $prefix = $wgDBprefix;
647 # Get class for this database type
648 $class = 'Database' . ucfirst( $type );
651 wfDebug( "Connecting to $host $dbname...\n" );
652 $db = new $class( $host, $user, $password, $dbname, 1, $flags, $prefix );
653 if ( $db->isOpen() ) {
654 wfDebug( "Connected\n" );
656 wfDebug( "Failed\n" );
658 $db->setLBInfo( $server );
659 if ( isset( $server['fakeSlaveLag'] ) ) {
660 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
662 if ( isset( $server['fakeMaster'] ) ) {
663 $db->setFakeMaster( true );
668 function reportConnectionError( &$conn ) {
669 wfProfileIn( __METHOD__
);
671 if ( !is_object( $conn ) ) {
672 // No last connection, probably due to all servers being too busy
673 wfLogDBError( "LB failure with no last connection\n" );
674 $conn = new Database
;
675 if ( $this->mFailFunction
) {
676 $conn->failFunction( $this->mFailFunction
);
677 $conn->reportConnectionError( $this->mLastError
);
679 // If all servers were busy, mLastError will contain something sensible
680 throw new DBConnectionError( $conn, $this->mLastError
);
683 if ( $this->mFailFunction
) {
684 $conn->failFunction( $this->mFailFunction
);
686 $conn->failFunction( false );
688 $server = $conn->getProperty( 'mServer' );
689 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
690 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
692 wfProfileOut( __METHOD__
);
695 function getWriterIndex() {
700 * Returns true if the specified index is a valid server index
702 function haveIndex( $i ) {
703 return array_key_exists( $i, $this->mServers
);
707 * Returns true if the specified index is valid and has non-zero load
709 function isNonZeroLoad( $i ) {
710 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
714 * Get the number of defined servers (not the number of open connections)
716 function getServerCount() {
717 return count( $this->mServers
);
721 * Get the host name or IP address of the server with the specified index
722 * Prefer a readable name if available.
724 function getServerName( $i ) {
725 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
726 return $this->mServers
[$i]['hostName'];
727 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
728 return $this->mServers
[$i]['host'];
735 * Return the server info structure for a given index, or false if the index is invalid.
737 function getServerInfo( $i ) {
738 if ( isset( $this->mServers
[$i] ) ) {
739 return $this->mServers
[$i];
746 * Get the current master position for chronology control purposes
749 function getMasterPos() {
750 # If this entire request was served from a slave without opening a connection to the
751 # master (however unlikely that may be), then we can fetch the position from the slave.
752 $masterConn = $this->getAnyOpenConnection( 0 );
753 if ( !$masterConn ) {
754 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
755 $conn = $this->getAnyOpenConnection( $i );
757 wfDebug( "Master pos fetched from slave\n" );
758 return $conn->getSlavePos();
762 wfDebug( "Master pos fetched from master\n" );
763 return $masterConn->getMasterPos();
769 * Close all open connections
771 function closeAll() {
772 foreach ( $this->mConns
as $conns2 ) {
773 foreach ( $conns2 as $conns3 ) {
774 foreach ( $conns3 as $conn ) {
779 $this->mConns
= array(
781 'foreignFree' => array(),
782 'foreignUsed' => array(),
788 * Using this function makes sure the LoadBalancer knows the connection is closed.
789 * If you use $conn->close() directly, the load balancer won't update its state.
791 function closeConnecton( $conn ) {
793 foreach ( $this->mConns
as $i1 => $conns2 ) {
794 foreach ( $conns2 as $i2 => $conns3 ) {
795 foreach ( $conns3 as $i3 => $candidateConn ) {
796 if ( $conn === $candidateConn ) {
798 unset( $this->mConns
[$i1][$i2][$i3] );
811 * Commit transactions on all open connections
813 function commitAll() {
814 foreach ( $this->mConns
as $conns2 ) {
815 foreach ( $conns2 as $conns3 ) {
816 foreach ( $conns3 as $conn ) {
817 $conn->immediateCommit();
823 /* Issue COMMIT only on master, only if queries were done on connection */
824 function commitMasterChanges() {
825 // Always 0, but who knows.. :)
826 $masterIndex = $this->getWriterIndex();
827 foreach ( $this->mConns
as $type => $conns2 ) {
828 if ( empty( $conns2[$masterIndex] ) ) {
831 foreach ( $conns2[$masterIndex] as $conn ) {
832 if ( $conn->lastQuery() != '' ) {
839 function waitTimeout( $value = NULL ) {
840 return wfSetVar( $this->mWaitTimeout
, $value );
843 function getLaggedSlaveMode() {
844 return $this->mLaggedSlaveMode
;
847 /* Disables/enables lag checks */
848 function allowLagged($mode=null) {
850 return $this->mAllowLagged
;
851 $this->mAllowLagged
=$mode;
856 foreach ( $this->mConns
as $conns2 ) {
857 foreach ( $conns2 as $conns3 ) {
858 foreach ( $conns3 as $conn ) {
859 if ( !$conn->ping() ) {
869 * Call a function with each open connection object
871 function forEachOpenConnection( $callback, $params = array() ) {
872 foreach ( $this->mConns
as $conns2 ) {
873 foreach ( $conns2 as $conns3 ) {
874 foreach ( $conns3 as $conn ) {
875 $mergedParams = array_merge( array( $conn ), $params );
876 call_user_func_array( $callback, $mergedParams );
883 * Get the hostname and lag time of the most-lagged slave.
884 * This is useful for maintenance scripts that need to throttle their updates.
885 * May attempt to open connections to slaves on the default DB.
887 function getMaxLag() {
890 foreach ( $this->mServers
as $i => $conn ) {
891 $conn = $this->getAnyOpenConnection( $i );
893 $conn = $this->openConnection( $i );
898 $lag = $conn->getLag();
899 if ( $lag > $maxLag ) {
901 $host = $this->mServers
[$i]['host'];
904 return array( $host, $maxLag );
908 * Get lag time for each server
909 * Results are cached for a short time in memcached, and indefinitely in the process cache
911 function getLagTimes( $wiki = false ) {
913 if ( isset( $this->mLagTimes
) ) {
914 return $this->mLagTimes
;
916 # No, send the request to the load monitor
917 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
918 return $this->mLagTimes
;