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 );
220 $laggedSlaveMode = false;
222 # First try quickly looking through the available servers for a server that
225 $totalThreadsConnected = 0;
226 $overloadedServers = 0;
227 $currentLoads = $nonErrorLoads;
228 while ( count( $currentLoads ) ) {
229 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
230 $i = $this->pickRandom( $currentLoads );
232 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
233 if ( $i === false && count( $currentLoads ) != 0 ) {
234 # All slaves lagged. Switch to read-only mode
235 $wgReadOnly = wfMsgNoDBForContent( 'readonly_lag' );
236 $i = $this->pickRandom( $currentLoads );
237 $laggedSlaveMode = true;
241 if ( $i === false ) {
242 # pickRandom() returned false
243 # This is permanent and means the configuration or the load monitor
244 # wants us to return false.
245 wfDebugLog( 'connect', __METHOD__
.": pickRandom() returned false\n" );
246 wfProfileOut( __METHOD__
);
250 wfDebugLog( 'connect', __METHOD__
.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
251 $conn = $this->openConnection( $i, $wiki );
254 wfDebugLog( 'connect', __METHOD__
.": Failed connecting to $i/$wiki\n" );
255 unset( $nonErrorLoads[$i] );
256 unset( $currentLoads[$i] );
260 // Perform post-connection backoff
261 $threshold = isset( $this->mServers
[$i]['max threads'] )
262 ?
$this->mServers
[$i]['max threads'] : false;
263 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
265 // Decrement reference counter, we are finished with this connection.
266 // It will be incremented for the caller later.
267 if ( $wiki !== false ) {
268 $this->reuseConnection( $conn );
272 # Post-connection overload, don't use this server for now
273 $totalThreadsConnected +
= $backoff;
274 $overloadedServers++
;
275 unset( $currentLoads[$i] );
282 # No server found yet
285 # If all servers were down, quit now
286 if ( !count( $nonErrorLoads ) ) {
287 wfDebugLog( 'connect', "All servers down\n" );
291 # Some servers must have been overloaded
292 if ( $overloadedServers == 0 ) {
293 throw new MWException( __METHOD__
.": unexpectedly found no overloaded servers" );
295 # Back off for a while
296 # Scale the sleep time by the number of connected threads, to produce a
297 # roughly constant global poll rate
298 $avgThreads = $totalThreadsConnected / $overloadedServers;
299 $totalElapsed +
= $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
300 } while ( $totalElapsed < $timeout );
302 if ( $totalElapsed >= $timeout ) {
303 wfDebugLog( 'connect', "All servers busy\n" );
304 $this->mErrorConnection
= false;
305 $this->mLastError
= 'All servers busy';
308 if ( $i !== false ) {
309 # Slave connection successful
310 # Wait for the session master pos for a short time
311 if ( $this->mWaitForPos
&& $i > 0 ) {
312 if ( !$this->doWait( $i ) ) {
313 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
316 if ( $this->mReadIndex
<=0 && $this->mLoads
[$i]>0 && $i !== false ) {
317 $this->mReadIndex
= $i;
320 wfProfileOut( __METHOD__
);
325 * Wait for a specified number of microseconds, and return the period waited
327 function sleep( $t ) {
328 wfProfileIn( __METHOD__
);
329 wfDebug( __METHOD__
.": waiting $t us\n" );
331 wfProfileOut( __METHOD__
);
336 * Get a random server to use in a query group
337 * @deprecated use getReaderIndex
339 function getGroupIndex( $group ) {
340 return $this->getReaderIndex( $group );
344 * Set the master wait position
345 * If a DB_SLAVE connection has been opened already, waits
346 * Otherwise sets a variable telling it to wait if such a connection is opened
348 public function waitFor( $pos ) {
349 wfProfileIn( __METHOD__
);
350 $this->mWaitForPos
= $pos;
351 $i = $this->mReadIndex
;
354 if ( !$this->doWait( $i ) ) {
355 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
356 $this->mLaggedSlaveMode
= true;
359 wfProfileOut( __METHOD__
);
363 * Get any open connection to a given server index, local or foreign
364 * Returns false if there is no connection open
366 function getAnyOpenConnection( $i ) {
367 foreach ( $this->mConns
as $type => $conns ) {
368 if ( !empty( $conns[$i] ) ) {
369 return reset( $conns[$i] );
376 * Wait for a given slave to catch up to the master pos stored in $this
378 function doWait( $index ) {
379 # Find a connection to wait on
380 $conn = $this->getAnyOpenConnection( $index );
382 wfDebug( __METHOD__
. ": no connection open\n" );
386 wfDebug( __METHOD__
.": Waiting for slave #$index to catch up...\n" );
387 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
389 if ( $result == -1 ||
is_null( $result ) ) {
390 # Timed out waiting for slave, use master instead
391 wfDebug( __METHOD__
.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
394 wfDebug( __METHOD__
.": Done\n" );
400 * Get a connection by index
401 * This is the main entry point for this class.
403 * @param $i Integer: server index
404 * @param $groups Array: query groups
405 * @param $wiki String: wiki ID
407 * @return DatabaseBase
409 public function &getConnection( $i, $groups = array(), $wiki = false ) {
410 wfProfileIn( __METHOD__
);
412 if ( $i == DB_LAST
) {
413 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with deprecated server index DB_LAST' );
414 } elseif ( $i === null ||
$i === false ) {
415 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with invalid server index' );
418 if ( $wiki === wfWikiID() ) {
423 if ( $i == DB_MASTER
) {
424 $i = $this->getWriterIndex();
425 } elseif ( !is_array( $groups ) ) {
426 $groupIndex = $this->getReaderIndex( $groups, $wiki );
427 if ( $groupIndex !== false ) {
428 $serverName = $this->getServerName( $groupIndex );
429 wfDebug( __METHOD__
.": using server $serverName for group $groups\n" );
433 foreach ( $groups as $group ) {
434 $groupIndex = $this->getReaderIndex( $group, $wiki );
435 if ( $groupIndex !== false ) {
436 $serverName = $this->getServerName( $groupIndex );
437 wfDebug( __METHOD__
.": using server $serverName for group $group\n" );
444 # Operation-based index
445 if ( $i == DB_SLAVE
) {
446 $i = $this->getReaderIndex( false, $wiki );
447 # Couldn't find a working server in getReaderIndex()?
448 if ( $i === false ) {
449 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
450 $this->reportConnectionError( $this->mErrorConnection
);
455 # Now we have an explicit index into the servers array
456 $conn = $this->openConnection( $i, $wiki );
458 $this->reportConnectionError( $this->mErrorConnection
);
461 wfProfileOut( __METHOD__
);
466 * Mark a foreign connection as being available for reuse under a different
467 * DB name or prefix. This mechanism is reference-counted, and must be called
468 * the same number of times as getConnection() to work.
470 public function reuseConnection( $conn ) {
471 $serverIndex = $conn->getLBInfo('serverIndex');
472 $refCount = $conn->getLBInfo('foreignPoolRefCount');
473 $dbName = $conn->getDBname();
474 $prefix = $conn->tablePrefix();
475 if ( strval( $prefix ) !== '' ) {
476 $wiki = "$dbName-$prefix";
480 if ( $serverIndex === null ||
$refCount === null ) {
481 wfDebug( __METHOD__
.": this connection was not opened as a foreign connection\n" );
483 * This can happen in code like:
484 * foreach ( $dbs as $db ) {
485 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
487 * $lb->reuseConnection( $conn );
489 * When a connection to the local DB is opened in this way, reuseConnection()
494 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
495 throw new MWException( __METHOD__
.": connection not found, has the connection been freed already?" );
497 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
498 if ( $refCount <= 0 ) {
499 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
500 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
501 wfDebug( __METHOD__
.": freed connection $serverIndex/$wiki\n" );
503 wfDebug( __METHOD__
.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
508 * Open a connection to the server given by the specified index
509 * Index must be an actual index into the array.
510 * If the server is already open, returns it.
512 * On error, returns false, and the connection which caused the
513 * error will be available via $this->mErrorConnection.
515 * @param $i Integer: server index
516 * @param $wiki String: wiki ID to open
517 * @return DatabaseBase
521 function openConnection( $i, $wiki = false ) {
522 wfProfileIn( __METHOD__
);
523 if ( $wiki !== false ) {
524 $conn = $this->openForeignConnection( $i, $wiki );
525 wfProfileOut( __METHOD__
);
528 if ( isset( $this->mConns
['local'][$i][0] ) ) {
529 $conn = $this->mConns
['local'][$i][0];
531 $server = $this->mServers
[$i];
532 $server['serverIndex'] = $i;
533 $conn = $this->reallyOpenConnection( $server, false );
534 if ( $conn->isOpen() ) {
535 $this->mConns
['local'][$i][0] = $conn;
537 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
538 $this->mErrorConnection
= $conn;
542 wfProfileOut( __METHOD__
);
547 * Open a connection to a foreign DB, or return one if it is already open.
549 * Increments a reference count on the returned connection which locks the
550 * connection to the requested wiki. This reference count can be
551 * decremented by calling reuseConnection().
553 * If a connection is open to the appropriate server already, but with the wrong
554 * database, it will be switched to the right database and returned, as long as
555 * it has been freed first with reuseConnection().
557 * On error, returns false, and the connection which caused the
558 * error will be available via $this->mErrorConnection.
560 * @param $i Integer: server index
561 * @param $wiki String: wiki ID to open
562 * @return DatabaseBase
564 function openForeignConnection( $i, $wiki ) {
565 wfProfileIn(__METHOD__
);
566 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
567 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
568 // Reuse an already-used connection
569 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
570 wfDebug( __METHOD__
.": reusing connection $i/$wiki\n" );
571 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
572 // Reuse a free connection for the same wiki
573 $conn = $this->mConns
['foreignFree'][$i][$wiki];
574 unset( $this->mConns
['foreignFree'][$i][$wiki] );
575 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
576 wfDebug( __METHOD__
.": reusing free connection $i/$wiki\n" );
577 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
578 // Reuse a connection from another wiki
579 $conn = reset( $this->mConns
['foreignFree'][$i] );
580 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
582 if ( !$conn->selectDB( $dbName ) ) {
583 $this->mLastError
= "Error selecting database $dbName on server " .
584 $conn->getServer() . " from client host " . wfHostname() . "\n";
585 $this->mErrorConnection
= $conn;
588 $conn->tablePrefix( $prefix );
589 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
590 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
591 wfDebug( __METHOD__
.": reusing free connection from $oldWiki for $wiki\n" );
594 // Open a new connection
595 $server = $this->mServers
[$i];
596 $server['serverIndex'] = $i;
597 $server['foreignPoolRefCount'] = 0;
598 $conn = $this->reallyOpenConnection( $server, $dbName );
599 if ( !$conn->isOpen() ) {
600 wfDebug( __METHOD__
.": error opening connection for $i/$wiki\n" );
601 $this->mErrorConnection
= $conn;
604 $conn->tablePrefix( $prefix );
605 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
606 wfDebug( __METHOD__
.": opened new connection for $i/$wiki\n" );
610 // Increment reference count
612 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
613 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
615 wfProfileOut(__METHOD__
);
620 * Test if the specified index represents an open connection
622 * @param $index Integer: server index
625 function isOpen( $index ) {
626 if( !is_integer( $index ) ) {
629 return (bool)$this->getAnyOpenConnection( $index );
633 * Really opens a connection. Uncached.
634 * Returns a Database object whether or not the connection was successful.
637 function reallyOpenConnection( $server, $dbNameOverride = false ) {
638 if( !is_array( $server ) ) {
639 throw new MWException( 'You must update your load-balancing configuration. See DefaultSettings.php entry for $wgDBservers.' );
643 if ( $dbNameOverride !== false ) {
644 $dbname = $dbNameOverride;
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 );
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 ) {
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->doneWrites() ) {
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.
886 * @param $wiki string Wiki ID, or false for the default database
888 function getMaxLag( $wiki = false ) {
891 foreach ( $this->mServers
as $i => $conn ) {
893 if ( $wiki === false ) {
894 $conn = $this->getAnyOpenConnection( $i );
897 $conn = $this->openConnection( $i, $wiki );
902 $lag = $conn->getLag();
903 if ( $lag > $maxLag ) {
905 $host = $this->mServers
[$i]['host'];
908 return array( $host, $maxLag );
912 * Get lag time for each server
913 * Results are cached for a short time in memcached, and indefinitely in the process cache
915 function getLagTimes( $wiki = false ) {
917 if ( isset( $this->mLagTimes
) ) {
918 return $this->mLagTimes
;
920 # No, send the request to the load monitor
921 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
922 return $this->mLagTimes
;
926 * Clear the cache for getLagTimes
928 function clearLagTimeCache() {
929 $this->mLagTimes
= null;