3 * Database load balancing
10 * Database load balancing object
16 /* private */ var $mServers, $mConns, $mLoads, $mGroupLoads;
17 /* private */ var $mFailFunction, $mErrorConnection;
18 /* private */ var $mReadIndex, $mAllowLagged;
19 /* private */ var $mWaitForPos, $mWaitTimeout;
20 /* private */ var $mLaggedSlaveMode, $mLastError = 'Unknown error';
21 /* private */ var $mParentInfo, $mLagTimes;
22 /* private */ var $mLoadMonitorClass, $mLoadMonitor;
25 * @param $params Array with keys:
26 * servers Required. Array of server info structures.
27 * failFunction Deprecated, use exceptions instead.
28 * masterWaitTimeout Replication lag wait timeout
29 * loadMonitor Name of a class used to fetch server lag and load.
31 function __construct( $params )
33 if ( !isset( $params['servers'] ) ) {
34 throw new MWException( __CLASS__
.': missing servers parameter' );
36 $this->mServers
= $params['servers'];
38 if ( isset( $params['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->mLoads
= array();
56 $this->mWaitForPos
= false;
57 $this->mLaggedSlaveMode
= false;
58 $this->mErrorConnection
= false;
59 $this->mAllowLag
= false;
60 $this->mLoadMonitorClass
= isset( $params['loadMonitor'] )
61 ?
$params['loadMonitor'] : 'LoadMonitor_MySQL';
63 foreach( $params['servers'] as $i => $server ) {
64 $this->mLoads
[$i] = $server['load'];
65 if ( isset( $server['groupLoads'] ) ) {
66 foreach ( $server['groupLoads'] as $group => $ratio ) {
67 if ( !isset( $this->mGroupLoads
[$group] ) ) {
68 $this->mGroupLoads
[$group] = array();
70 $this->mGroupLoads
[$group][$i] = $ratio;
76 static function newFromParams( $servers, $failFunction = false, $waitTimeout = 10 )
78 return new LoadBalancer( $servers, $failFunction, $waitTimeout );
82 * Get a LoadMonitor instance
84 function getLoadMonitor() {
85 if ( !isset( $this->mLoadMonitor
) ) {
86 $class = $this->mLoadMonitorClass
;
87 $this->mLoadMonitor
= new $class( $this );
89 return $this->mLoadMonitor
;
93 * Get or set arbitrary data used by the parent object, usually an LBFactory
95 function parentInfo( $x = null ) {
96 return wfSetVar( $this->mParentInfo
, $x );
100 * Given an array of non-normalised probabilities, this function will select
101 * an element and return the appropriate key
103 function pickRandom( $weights )
105 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
109 $sum = array_sum( $weights );
111 # No loads on any of them
112 # In previous versions, this triggered an unweighted random selection,
113 # but this feature has been removed as of April 2006 to allow for strict
114 # separation of query groups.
117 $max = mt_getrandmax();
118 $rand = mt_rand(0, $max) / $max * $sum;
121 foreach ( $weights as $i => $w ) {
123 if ( $sum >= $rand ) {
130 function getRandomNonLagged( $loads, $wiki = false ) {
131 # Unset excessively lagged servers
132 $lags = $this->getLagTimes( $wiki );
133 foreach ( $lags as $i => $lag ) {
134 if ( $i != 0 && isset( $this->mServers
[$i]['max lag'] ) ) {
135 if ( $lag === false ) {
136 wfDebug( "Server #$i is not replicating\n" );
138 } elseif ( $lag > $this->mServers
[$i]['max lag'] ) {
139 wfDebug( "Server #$i is excessively lagged ($lag seconds)\n" );
145 # Find out if all the slaves with non-zero load are lagged
147 foreach ( $loads as $load ) {
151 # No appropriate DB servers except maybe the master and some slaves with zero load
152 # Do NOT use the master
153 # Instead, this function will return false, triggering read-only mode,
154 # and a lagged slave will be used instead.
158 if ( count( $loads ) == 0 ) {
162 #wfDebugLog( 'connect', var_export( $loads, true ) );
164 # Return a random representative of the remainder
165 return $this->pickRandom( $loads );
169 * Get the index of the reader connection, which may be a slave
170 * This takes into account load ratios and lag times. It should
171 * always return a consistent index during a given invocation
173 * Side effect: opens connections to databases
175 function getReaderIndex( $group = false, $wiki = false ) {
176 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
178 # FIXME: For now, only go through all this for mysql databases
179 if ($wgDBtype != 'mysql') {
180 return $this->getWriterIndex();
183 if ( count( $this->mServers
) == 1 ) {
184 # Skip the load balancing if there's only one server
186 } elseif ( $group === false and $this->mReadIndex
>= 0 ) {
187 # Shortcut if generic reader exists already
188 return $this->mReadIndex
;
191 wfProfileIn( __METHOD__
);
195 # convert from seconds to microseconds
196 $timeout = $wgDBClusterTimeout * 1e6
;
198 # Find the relevant load array
199 if ( $group !== false ) {
200 if ( isset( $this->mGroupLoads
[$group] ) ) {
201 $nonErrorLoads = $this->mGroupLoads
[$group];
203 # No loads for this group, return false and the caller can use some other group
204 wfDebug( __METHOD__
.": no loads for group $group\n" );
205 wfProfileOut( __METHOD__
);
209 $nonErrorLoads = $this->mLoads
;
212 if ( !$nonErrorLoads ) {
213 throw new MWException( "Empty server array given to LoadBalancer" );
216 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
217 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
221 $laggedSlaveMode = false;
223 # First try quickly looking through the available servers for a server that
226 $totalThreadsConnected = 0;
227 $overloadedServers = 0;
228 $currentLoads = $nonErrorLoads;
229 while ( count( $currentLoads ) ) {
230 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
231 $i = $this->pickRandom( $currentLoads );
233 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
234 if ( $i === false && count( $currentLoads ) != 0 ) {
235 # All slaves lagged. Switch to read-only mode
236 $wgReadOnly = wfMsgNoDBForContent( 'readonly_lag' );
237 $i = $this->pickRandom( $currentLoads );
238 $laggedSlaveMode = true;
242 if ( $i === false ) {
243 # pickRandom() returned false
244 # This is permanent and means the configuration or the load monitor
245 # wants us to return false.
246 wfDebugLog( 'connect', __METHOD__
.": pickRandom() returned false\n" );
247 wfProfileOut( __METHOD__
);
251 wfDebugLog( 'connect', __METHOD__
.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
252 $conn = $this->openConnection( $i, $wiki );
255 wfDebugLog( 'connect', __METHOD__
.": Failed connecting to $i/$wiki\n" );
256 unset( $nonErrorLoads[$i] );
257 unset( $currentLoads[$i] );
261 // Perform post-connection backoff
262 $threshold = isset( $this->mServers
[$i]['max threads'] )
263 ?
$this->mServers
[$i]['max threads'] : false;
264 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
266 // Decrement reference counter, we are finished with this connection.
267 // It will be incremented for the caller later.
268 if ( $wiki !== false ) {
269 $this->reuseConnection( $conn );
273 # Post-connection overload, don't use this server for now
274 $totalThreadsConnected +
= $backoff;
275 $overloadedServers++
;
276 unset( $currentLoads[$i] );
283 # No server found yet
286 # If all servers were down, quit now
287 if ( !count( $nonErrorLoads ) ) {
288 wfDebugLog( 'connect', "All servers down\n" );
292 # Some servers must have been overloaded
293 if ( $overloadedServers == 0 ) {
294 throw new MWException( __METHOD__
.": unexpectedly found no overloaded servers" );
296 # Back off for a while
297 # Scale the sleep time by the number of connected threads, to produce a
298 # roughly constant global poll rate
299 $avgThreads = $totalThreadsConnected / $overloadedServers;
300 $totalElapsed +
= $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
301 } while ( $totalElapsed < $timeout );
303 if ( $totalElapsed >= $timeout ) {
304 wfDebugLog( 'connect', "All servers busy\n" );
305 $this->mErrorConnection
= false;
306 $this->mLastError
= 'All servers busy';
309 if ( $i !== false ) {
310 # Slave connection successful
311 # Wait for the session master pos for a short time
312 if ( $this->mWaitForPos
&& $i > 0 ) {
313 if ( !$this->doWait( $i ) ) {
314 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
317 if ( $this->mReadIndex
<=0 && $this->mLoads
[$i]>0 && $i !== false ) {
318 $this->mReadIndex
= $i;
321 wfProfileOut( __METHOD__
);
326 * Wait for a specified number of microseconds, and return the period waited
328 function sleep( $t ) {
329 wfProfileIn( __METHOD__
);
330 wfDebug( __METHOD__
.": waiting $t us\n" );
332 wfProfileOut( __METHOD__
);
337 * Get a random server to use in a query group
338 * @deprecated use getReaderIndex
340 function getGroupIndex( $group ) {
341 return $this->getReaderIndex( $group );
345 * Set the master wait position
346 * If a DB_SLAVE connection has been opened already, waits
347 * Otherwise sets a variable telling it to wait if such a connection is opened
349 public function waitFor( $pos ) {
350 wfProfileIn( __METHOD__
);
351 $this->mWaitForPos
= $pos;
352 $i = $this->mReadIndex
;
355 if ( !$this->doWait( $i ) ) {
356 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
357 $this->mLaggedSlaveMode
= true;
360 wfProfileOut( __METHOD__
);
364 * Get any open connection to a given server index, local or foreign
365 * Returns false if there is no connection open
367 function getAnyOpenConnection( $i ) {
368 foreach ( $this->mConns
as $type => $conns ) {
369 if ( !empty( $conns[$i] ) ) {
370 return reset( $conns[$i] );
377 * Wait for a given slave to catch up to the master pos stored in $this
379 function doWait( $index ) {
380 # Find a connection to wait on
381 $conn = $this->getAnyOpenConnection( $index );
383 wfDebug( __METHOD__
. ": no connection open\n" );
387 wfDebug( __METHOD__
.": Waiting for slave #$index to catch up...\n" );
388 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
390 if ( $result == -1 ||
is_null( $result ) ) {
391 # Timed out waiting for slave, use master instead
392 wfDebug( __METHOD__
.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
395 wfDebug( __METHOD__
.": Done\n" );
401 * Get a connection by index
402 * This is the main entry point for this class.
404 * @param $i Integer: server index
405 * @param $groups Array: query groups
406 * @param $wiki String: wiki ID
408 * @return DatabaseBase
410 public function &getConnection( $i, $groups = array(), $wiki = false ) {
411 wfProfileIn( __METHOD__
);
413 if ( $i == DB_LAST
) {
414 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with deprecated server index DB_LAST' );
415 } elseif ( $i === null ||
$i === false ) {
416 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with invalid server index' );
419 if ( $wiki === wfWikiID() ) {
424 if ( $i == DB_MASTER
) {
425 $i = $this->getWriterIndex();
426 } elseif ( !is_array( $groups ) ) {
427 $groupIndex = $this->getReaderIndex( $groups, $wiki );
428 if ( $groupIndex !== false ) {
429 $serverName = $this->getServerName( $groupIndex );
430 wfDebug( __METHOD__
.": using server $serverName for group $groups\n" );
434 foreach ( $groups as $group ) {
435 $groupIndex = $this->getReaderIndex( $group, $wiki );
436 if ( $groupIndex !== false ) {
437 $serverName = $this->getServerName( $groupIndex );
438 wfDebug( __METHOD__
.": using server $serverName for group $group\n" );
445 # Operation-based index
446 if ( $i == DB_SLAVE
) {
447 $i = $this->getReaderIndex( false, $wiki );
448 # Couldn't find a working server in getReaderIndex()?
449 if ( $i === false ) {
450 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
451 $this->reportConnectionError( $this->mErrorConnection
);
456 # Now we have an explicit index into the servers array
457 $conn = $this->openConnection( $i, $wiki );
459 $this->reportConnectionError( $this->mErrorConnection
);
462 wfProfileOut( __METHOD__
);
467 * Mark a foreign connection as being available for reuse under a different
468 * DB name or prefix. This mechanism is reference-counted, and must be called
469 * the same number of times as getConnection() to work.
471 public function reuseConnection( $conn ) {
472 $serverIndex = $conn->getLBInfo('serverIndex');
473 $refCount = $conn->getLBInfo('foreignPoolRefCount');
474 $dbName = $conn->getDBname();
475 $prefix = $conn->tablePrefix();
476 if ( strval( $prefix ) !== '' ) {
477 $wiki = "$dbName-$prefix";
481 if ( $serverIndex === null ||
$refCount === null ) {
482 wfDebug( __METHOD__
.": this connection was not opened as a foreign connection\n" );
484 * This can happen in code like:
485 * foreach ( $dbs as $db ) {
486 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
488 * $lb->reuseConnection( $conn );
490 * When a connection to the local DB is opened in this way, reuseConnection()
495 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
496 throw new MWException( __METHOD__
.": connection not found, has the connection been freed already?" );
498 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
499 if ( $refCount <= 0 ) {
500 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
501 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
502 wfDebug( __METHOD__
.": freed connection $serverIndex/$wiki\n" );
504 wfDebug( __METHOD__
.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
509 * Open a connection to the server given by the specified index
510 * Index must be an actual index into the array.
511 * If the server is already open, returns it.
513 * On error, returns false, and the connection which caused the
514 * error will be available via $this->mErrorConnection.
516 * @param $i Integer: server index
517 * @param $wiki String: wiki ID to open
518 * @return DatabaseBase
522 function openConnection( $i, $wiki = false ) {
523 wfProfileIn( __METHOD__
);
524 if ( $wiki !== false ) {
525 $conn = $this->openForeignConnection( $i, $wiki );
526 wfProfileOut( __METHOD__
);
529 if ( isset( $this->mConns
['local'][$i][0] ) ) {
530 $conn = $this->mConns
['local'][$i][0];
532 $server = $this->mServers
[$i];
533 $server['serverIndex'] = $i;
534 $conn = $this->reallyOpenConnection( $server, false );
535 if ( $conn->isOpen() ) {
536 $this->mConns
['local'][$i][0] = $conn;
538 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
539 $this->mErrorConnection
= $conn;
543 wfProfileOut( __METHOD__
);
548 * Open a connection to a foreign DB, or return one if it is already open.
550 * Increments a reference count on the returned connection which locks the
551 * connection to the requested wiki. This reference count can be
552 * decremented by calling reuseConnection().
554 * If a connection is open to the appropriate server already, but with the wrong
555 * database, it will be switched to the right database and returned, as long as
556 * it has been freed first with reuseConnection().
558 * On error, returns false, and the connection which caused the
559 * error will be available via $this->mErrorConnection.
561 * @param $i Integer: server index
562 * @param $wiki String: wiki ID to open
563 * @return DatabaseBase
565 function openForeignConnection( $i, $wiki ) {
566 wfProfileIn(__METHOD__
);
567 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
568 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
569 // Reuse an already-used connection
570 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
571 wfDebug( __METHOD__
.": reusing connection $i/$wiki\n" );
572 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
573 // Reuse a free connection for the same wiki
574 $conn = $this->mConns
['foreignFree'][$i][$wiki];
575 unset( $this->mConns
['foreignFree'][$i][$wiki] );
576 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
577 wfDebug( __METHOD__
.": reusing free connection $i/$wiki\n" );
578 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
579 // Reuse a connection from another wiki
580 $conn = reset( $this->mConns
['foreignFree'][$i] );
581 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
583 if ( !$conn->selectDB( $dbName ) ) {
584 $this->mLastError
= "Error selecting database $dbName on server " .
585 $conn->getServer() . " from client host " . wfHostname() . "\n";
586 $this->mErrorConnection
= $conn;
589 $conn->tablePrefix( $prefix );
590 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
591 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
592 wfDebug( __METHOD__
.": reusing free connection from $oldWiki for $wiki\n" );
595 // Open a new connection
596 $server = $this->mServers
[$i];
597 $server['serverIndex'] = $i;
598 $server['foreignPoolRefCount'] = 0;
599 $conn = $this->reallyOpenConnection( $server, $dbName );
600 if ( !$conn->isOpen() ) {
601 wfDebug( __METHOD__
.": error opening connection for $i/$wiki\n" );
602 $this->mErrorConnection
= $conn;
605 $conn->tablePrefix( $prefix );
606 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
607 wfDebug( __METHOD__
.": opened new connection for $i/$wiki\n" );
611 // Increment reference count
613 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
614 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
616 wfProfileOut(__METHOD__
);
621 * Test if the specified index represents an open connection
623 * @param $index Integer: server index
626 function isOpen( $index ) {
627 if( !is_integer( $index ) ) {
630 return (bool)$this->getAnyOpenConnection( $index );
634 * Really opens a connection. Uncached.
635 * Returns a Database object whether or not the connection was successful.
638 function reallyOpenConnection( $server, $dbNameOverride = false ) {
639 if( !is_array( $server ) ) {
640 throw new MWException( 'You must update your load-balancing configuration. See DefaultSettings.php entry for $wgDBservers.' );
644 if ( $dbNameOverride !== false ) {
645 $dbname = $dbNameOverride;
648 # Get class for this database type
649 $class = 'Database' . ucfirst( $type );
652 wfDebug( "Connecting to $host $dbname...\n" );
653 $db = new $class( $host, $user, $password, $dbname, 1, $flags );
654 if ( $db->isOpen() ) {
655 wfDebug( "Connected\n" );
657 wfDebug( "Failed\n" );
659 $db->setLBInfo( $server );
660 if ( isset( $server['fakeSlaveLag'] ) ) {
661 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
663 if ( isset( $server['fakeMaster'] ) ) {
664 $db->setFakeMaster( true );
669 function reportConnectionError( &$conn ) {
670 wfProfileIn( __METHOD__
);
672 if ( !is_object( $conn ) ) {
673 // No last connection, probably due to all servers being too busy
674 wfLogDBError( "LB failure with no last connection\n" );
675 $conn = new Database
;
676 if ( $this->mFailFunction
) {
677 $conn->failFunction( $this->mFailFunction
);
678 $conn->reportConnectionError( $this->mLastError
);
680 // If all servers were busy, mLastError will contain something sensible
681 throw new DBConnectionError( $conn, $this->mLastError
);
684 if ( $this->mFailFunction
) {
685 $conn->failFunction( $this->mFailFunction
);
687 $conn->failFunction( false );
689 $server = $conn->getProperty( 'mServer' );
690 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
691 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
693 wfProfileOut( __METHOD__
);
696 function getWriterIndex() {
701 * Returns true if the specified index is a valid server index
703 function haveIndex( $i ) {
704 return array_key_exists( $i, $this->mServers
);
708 * Returns true if the specified index is valid and has non-zero load
710 function isNonZeroLoad( $i ) {
711 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
715 * Get the number of defined servers (not the number of open connections)
717 function getServerCount() {
718 return count( $this->mServers
);
722 * Get the host name or IP address of the server with the specified index
723 * Prefer a readable name if available.
725 function getServerName( $i ) {
726 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
727 return $this->mServers
[$i]['hostName'];
728 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
729 return $this->mServers
[$i]['host'];
736 * Return the server info structure for a given index, or false if the index is invalid.
738 function getServerInfo( $i ) {
739 if ( isset( $this->mServers
[$i] ) ) {
740 return $this->mServers
[$i];
747 * Get the current master position for chronology control purposes
750 function getMasterPos() {
751 # If this entire request was served from a slave without opening a connection to the
752 # master (however unlikely that may be), then we can fetch the position from the slave.
753 $masterConn = $this->getAnyOpenConnection( 0 );
754 if ( !$masterConn ) {
755 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
756 $conn = $this->getAnyOpenConnection( $i );
758 wfDebug( "Master pos fetched from slave\n" );
759 return $conn->getSlavePos();
763 wfDebug( "Master pos fetched from master\n" );
764 return $masterConn->getMasterPos();
770 * Close all open connections
772 function closeAll() {
773 foreach ( $this->mConns
as $conns2 ) {
774 foreach ( $conns2 as $conns3 ) {
775 foreach ( $conns3 as $conn ) {
780 $this->mConns
= array(
782 'foreignFree' => array(),
783 'foreignUsed' => array(),
789 * Using this function makes sure the LoadBalancer knows the connection is closed.
790 * If you use $conn->close() directly, the load balancer won't update its state.
792 function closeConnecton( $conn ) {
794 foreach ( $this->mConns
as $i1 => $conns2 ) {
795 foreach ( $conns2 as $i2 => $conns3 ) {
796 foreach ( $conns3 as $i3 => $candidateConn ) {
797 if ( $conn === $candidateConn ) {
799 unset( $this->mConns
[$i1][$i2][$i3] );
812 * Commit transactions on all open connections
814 function commitAll() {
815 foreach ( $this->mConns
as $conns2 ) {
816 foreach ( $conns2 as $conns3 ) {
817 foreach ( $conns3 as $conn ) {
824 /* Issue COMMIT only on master, only if queries were done on connection */
825 function commitMasterChanges() {
826 // Always 0, but who knows.. :)
827 $masterIndex = $this->getWriterIndex();
828 foreach ( $this->mConns
as $type => $conns2 ) {
829 if ( empty( $conns2[$masterIndex] ) ) {
832 foreach ( $conns2[$masterIndex] as $conn ) {
833 if ( $conn->doneWrites() ) {
840 function waitTimeout( $value = null ) {
841 return wfSetVar( $this->mWaitTimeout
, $value );
844 function getLaggedSlaveMode() {
845 return $this->mLaggedSlaveMode
;
848 /* Disables/enables lag checks */
849 function allowLagged($mode=null) {
851 return $this->mAllowLagged
;
852 $this->mAllowLagged
=$mode;
857 foreach ( $this->mConns
as $conns2 ) {
858 foreach ( $conns2 as $conns3 ) {
859 foreach ( $conns3 as $conn ) {
860 if ( !$conn->ping() ) {
870 * Call a function with each open connection object
872 function forEachOpenConnection( $callback, $params = array() ) {
873 foreach ( $this->mConns
as $conns2 ) {
874 foreach ( $conns2 as $conns3 ) {
875 foreach ( $conns3 as $conn ) {
876 $mergedParams = array_merge( array( $conn ), $params );
877 call_user_func_array( $callback, $mergedParams );
884 * Get the hostname and lag time of the most-lagged slave.
885 * This is useful for maintenance scripts that need to throttle their updates.
886 * May attempt to open connections to slaves on the default DB.
887 * @param $wiki string Wiki ID, or false for the default database
889 function getMaxLag( $wiki = false ) {
892 foreach ( $this->mServers
as $i => $conn ) {
894 if ( $wiki === false ) {
895 $conn = $this->getAnyOpenConnection( $i );
898 $conn = $this->openConnection( $i, $wiki );
903 $lag = $conn->getLag();
904 if ( $lag > $maxLag ) {
906 $host = $this->mServers
[$i]['host'];
909 return array( $host, $maxLag );
913 * Get lag time for each server
914 * Results are cached for a short time in memcached, and indefinitely in the process cache
916 function getLagTimes( $wiki = false ) {
918 if ( isset( $this->mLagTimes
) ) {
919 return $this->mLagTimes
;
921 # No, send the request to the load monitor
922 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
923 return $this->mLagTimes
;
927 * Clear the cache for getLagTimes
929 function clearLagTimeCache() {
930 $this->mLagTimes
= null;