9662b03cd42bfe7772bfc1e68d211e65ecbf3f45
3 * Database load balancing
10 * Database load balancing object
16 private $mServers, $mConns, $mLoads, $mGroupLoads;
17 private $mErrorConnection;
18 private $mReadIndex, $mAllowLagged;
19 private $mWaitForPos, $mWaitTimeout;
20 private $mLaggedSlaveMode, $mLastError = 'Unknown error';
21 private $mParentInfo, $mLagTimes;
22 private $mLoadMonitorClass, $mLoadMonitor;
25 * @param $params Array with keys:
26 * servers Required. Array of server info structures.
27 * masterWaitTimeout Replication lag wait timeout
28 * loadMonitor Name of a class used to fetch server lag and load.
30 function __construct( $params )
32 if ( !isset( $params['servers'] ) ) {
33 throw new MWException( __CLASS__
.': missing servers parameter' );
35 $this->mServers
= $params['servers'];
37 if ( isset( $params['waitTimeout'] ) ) {
38 $this->mWaitTimeout
= $params['waitTimeout'];
40 $this->mWaitTimeout
= 10;
43 $this->mReadIndex
= -1;
44 $this->mWriteIndex
= -1;
45 $this->mConns
= array(
47 'foreignUsed' => array(),
48 'foreignFree' => array() );
49 $this->mLoads
= array();
50 $this->mWaitForPos
= false;
51 $this->mLaggedSlaveMode
= false;
52 $this->mErrorConnection
= false;
53 $this->mAllowLagged
= false;
54 $this->mLoadMonitorClass
= isset( $params['loadMonitor'] )
55 ?
$params['loadMonitor'] : 'LoadMonitor_MySQL';
57 foreach( $params['servers'] as $i => $server ) {
58 $this->mLoads
[$i] = $server['load'];
59 if ( isset( $server['groupLoads'] ) ) {
60 foreach ( $server['groupLoads'] as $group => $ratio ) {
61 if ( !isset( $this->mGroupLoads
[$group] ) ) {
62 $this->mGroupLoads
[$group] = array();
64 $this->mGroupLoads
[$group][$i] = $ratio;
71 * Get a LoadMonitor instance
75 function getLoadMonitor() {
76 if ( !isset( $this->mLoadMonitor
) ) {
77 $class = $this->mLoadMonitorClass
;
78 $this->mLoadMonitor
= new $class( $this );
80 return $this->mLoadMonitor
;
84 * Get or set arbitrary data used by the parent object, usually an LBFactory
86 function parentInfo( $x = null ) {
87 return wfSetVar( $this->mParentInfo
, $x );
91 * Given an array of non-normalised probabilities, this function will select
92 * an element and return the appropriate key
94 function pickRandom( $weights ) {
95 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
99 $sum = array_sum( $weights );
101 # No loads on any of them
102 # In previous versions, this triggered an unweighted random selection,
103 # but this feature has been removed as of April 2006 to allow for strict
104 # separation of query groups.
107 $max = mt_getrandmax();
108 $rand = mt_rand(0, $max) / $max * $sum;
111 foreach ( $weights as $i => $w ) {
113 if ( $sum >= $rand ) {
120 function getRandomNonLagged( $loads, $wiki = false ) {
121 # Unset excessively lagged servers
122 $lags = $this->getLagTimes( $wiki );
123 foreach ( $lags as $i => $lag ) {
125 if ( $lag === false ) {
126 wfDebug( "Server #$i is not replicating\n" );
128 } elseif ( isset( $this->mServers
[$i]['max lag'] ) && $lag > $this->mServers
[$i]['max lag'] ) {
129 wfDebug( "Server #$i is excessively lagged ($lag seconds)\n" );
135 # Find out if all the slaves with non-zero load are lagged
137 foreach ( $loads as $load ) {
141 # No appropriate DB servers except maybe the master and some slaves with zero load
142 # Do NOT use the master
143 # Instead, this function will return false, triggering read-only mode,
144 # and a lagged slave will be used instead.
148 if ( count( $loads ) == 0 ) {
152 #wfDebugLog( 'connect', var_export( $loads, true ) );
154 # Return a random representative of the remainder
155 return $this->pickRandom( $loads );
159 * Get the index of the reader connection, which may be a slave
160 * This takes into account load ratios and lag times. It should
161 * always return a consistent index during a given invocation
163 * Side effect: opens connections to databases
165 function getReaderIndex( $group = false, $wiki = false ) {
166 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
168 # @todo FIXME: For now, only go through all this for mysql databases
169 if ($wgDBtype != 'mysql') {
170 return $this->getWriterIndex();
173 if ( count( $this->mServers
) == 1 ) {
174 # Skip the load balancing if there's only one server
176 } elseif ( $group === false and $this->mReadIndex
>= 0 ) {
177 # Shortcut if generic reader exists already
178 return $this->mReadIndex
;
181 wfProfileIn( __METHOD__
);
185 # convert from seconds to microseconds
186 $timeout = $wgDBClusterTimeout * 1e6
;
188 # Find the relevant load array
189 if ( $group !== false ) {
190 if ( isset( $this->mGroupLoads
[$group] ) ) {
191 $nonErrorLoads = $this->mGroupLoads
[$group];
193 # No loads for this group, return false and the caller can use some other group
194 wfDebug( __METHOD__
.": no loads for group $group\n" );
195 wfProfileOut( __METHOD__
);
199 $nonErrorLoads = $this->mLoads
;
202 if ( !$nonErrorLoads ) {
203 throw new MWException( "Empty server array given to LoadBalancer" );
206 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
207 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
209 $laggedSlaveMode = false;
211 # First try quickly looking through the available servers for a server that
214 $totalThreadsConnected = 0;
215 $overloadedServers = 0;
216 $currentLoads = $nonErrorLoads;
217 while ( count( $currentLoads ) ) {
218 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
219 $i = $this->pickRandom( $currentLoads );
221 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
222 if ( $i === false && count( $currentLoads ) != 0 ) {
223 # All slaves lagged. Switch to read-only mode
224 $wgReadOnly = wfMessage( 'readonly_lag' )->useDatabase( false )->plain();
225 $i = $this->pickRandom( $currentLoads );
226 $laggedSlaveMode = true;
230 if ( $i === false ) {
231 # pickRandom() returned false
232 # This is permanent and means the configuration or the load monitor
233 # wants us to return false.
234 wfDebugLog( 'connect', __METHOD__
.": pickRandom() returned false\n" );
235 wfProfileOut( __METHOD__
);
239 wfDebugLog( 'connect', __METHOD__
.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
240 $conn = $this->openConnection( $i, $wiki );
243 wfDebugLog( 'connect', __METHOD__
.": Failed connecting to $i/$wiki\n" );
244 unset( $nonErrorLoads[$i] );
245 unset( $currentLoads[$i] );
249 // Perform post-connection backoff
250 $threshold = isset( $this->mServers
[$i]['max threads'] )
251 ?
$this->mServers
[$i]['max threads'] : false;
252 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
254 // Decrement reference counter, we are finished with this connection.
255 // It will be incremented for the caller later.
256 if ( $wiki !== false ) {
257 $this->reuseConnection( $conn );
261 # Post-connection overload, don't use this server for now
262 $totalThreadsConnected +
= $backoff;
263 $overloadedServers++
;
264 unset( $currentLoads[$i] );
271 # No server found yet
274 # If all servers were down, quit now
275 if ( !count( $nonErrorLoads ) ) {
276 wfDebugLog( 'connect', "All servers down\n" );
280 # Some servers must have been overloaded
281 if ( $overloadedServers == 0 ) {
282 throw new MWException( __METHOD__
.": unexpectedly found no overloaded servers" );
284 # Back off for a while
285 # Scale the sleep time by the number of connected threads, to produce a
286 # roughly constant global poll rate
287 $avgThreads = $totalThreadsConnected / $overloadedServers;
288 $totalElapsed +
= $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
289 } while ( $totalElapsed < $timeout );
291 if ( $totalElapsed >= $timeout ) {
292 wfDebugLog( 'connect', "All servers busy\n" );
293 $this->mErrorConnection
= false;
294 $this->mLastError
= 'All servers busy';
297 if ( $i !== false ) {
298 # Slave connection successful
299 # Wait for the session master pos for a short time
300 if ( $this->mWaitForPos
&& $i > 0 ) {
301 if ( !$this->doWait( $i ) ) {
302 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
305 if ( $this->mReadIndex
<=0 && $this->mLoads
[$i]>0 && $i !== false ) {
306 $this->mReadIndex
= $i;
309 wfProfileOut( __METHOD__
);
314 * Wait for a specified number of microseconds, and return the period waited
316 function sleep( $t ) {
317 wfProfileIn( __METHOD__
);
318 wfDebug( __METHOD__
.": waiting $t us\n" );
320 wfProfileOut( __METHOD__
);
325 * Set the master wait position
326 * If a DB_SLAVE connection has been opened already, waits
327 * Otherwise sets a variable telling it to wait if such a connection is opened
329 public function waitFor( $pos ) {
330 wfProfileIn( __METHOD__
);
331 $this->mWaitForPos
= $pos;
332 $i = $this->mReadIndex
;
335 if ( !$this->doWait( $i ) ) {
336 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
337 $this->mLaggedSlaveMode
= true;
340 wfProfileOut( __METHOD__
);
344 * Set the master wait position and wait for ALL slaves to catch up to it
346 public function waitForAll( $pos ) {
347 wfProfileIn( __METHOD__
);
348 $this->mWaitForPos
= $pos;
349 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
350 $this->doWait( $i , true );
352 wfProfileOut( __METHOD__
);
356 * Get any open connection to a given server index, local or foreign
357 * Returns false if there is no connection open
359 * @return DatabaseBase
361 function getAnyOpenConnection( $i ) {
362 foreach ( $this->mConns
as $conns ) {
363 if ( !empty( $conns[$i] ) ) {
364 return reset( $conns[$i] );
371 * Wait for a given slave to catch up to the master pos stored in $this
373 function doWait( $index, $open = false ) {
374 # Find a connection to wait on
375 $conn = $this->getAnyOpenConnection( $index );
378 wfDebug( __METHOD__
. ": no connection open\n" );
381 $conn = $this->openConnection( $index );
383 wfDebug( __METHOD__
. ": failed to open connection\n" );
389 wfDebug( __METHOD__
.": Waiting for slave #$index to catch up...\n" );
390 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
392 if ( $result == -1 ||
is_null( $result ) ) {
393 # Timed out waiting for slave, use master instead
394 wfDebug( __METHOD__
.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
397 wfDebug( __METHOD__
.": Done\n" );
403 * Get a connection by index
404 * This is the main entry point for this class.
406 * @param $i Integer: server index
407 * @param $groups Array: query groups
408 * @param $wiki String: wiki ID
410 * @return DatabaseBase
412 public function &getConnection( $i, $groups = array(), $wiki = false ) {
413 wfProfileIn( __METHOD__
);
415 if ( $i == DB_LAST
) {
416 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with deprecated server index DB_LAST' );
417 } elseif ( $i === null ||
$i === false ) {
418 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with invalid server index' );
421 if ( $wiki === wfWikiID() ) {
426 if ( $i == DB_MASTER
) {
427 $i = $this->getWriterIndex();
428 } elseif ( !is_array( $groups ) ) {
429 $groupIndex = $this->getReaderIndex( $groups, $wiki );
430 if ( $groupIndex !== false ) {
431 $serverName = $this->getServerName( $groupIndex );
432 wfDebug( __METHOD__
.": using server $serverName for group $groups\n" );
436 foreach ( $groups as $group ) {
437 $groupIndex = $this->getReaderIndex( $group, $wiki );
438 if ( $groupIndex !== false ) {
439 $serverName = $this->getServerName( $groupIndex );
440 wfDebug( __METHOD__
.": using server $serverName for group $group\n" );
447 # Operation-based index
448 if ( $i == DB_SLAVE
) {
449 $i = $this->getReaderIndex( false, $wiki );
450 # Couldn't find a working server in getReaderIndex()?
451 if ( $i === false ) {
452 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
453 $this->reportConnectionError( $this->mErrorConnection
);
454 wfProfileOut( __METHOD__
);
459 # Now we have an explicit index into the servers array
460 $conn = $this->openConnection( $i, $wiki );
462 $this->reportConnectionError( $this->mErrorConnection
);
465 wfProfileOut( __METHOD__
);
470 * Mark a foreign connection as being available for reuse under a different
471 * DB name or prefix. This mechanism is reference-counted, and must be called
472 * the same number of times as getConnection() to work.
474 * @param DatabaseBase $conn
476 public function reuseConnection( $conn ) {
477 $serverIndex = $conn->getLBInfo('serverIndex');
478 $refCount = $conn->getLBInfo('foreignPoolRefCount');
479 $dbName = $conn->getDBname();
480 $prefix = $conn->tablePrefix();
481 if ( strval( $prefix ) !== '' ) {
482 $wiki = "$dbName-$prefix";
486 if ( $serverIndex === null ||
$refCount === null ) {
487 wfDebug( __METHOD__
.": this connection was not opened as a foreign connection\n" );
489 * This can happen in code like:
490 * foreach ( $dbs as $db ) {
491 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
493 * $lb->reuseConnection( $conn );
495 * When a connection to the local DB is opened in this way, reuseConnection()
500 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
501 throw new MWException( __METHOD__
.": connection not found, has the connection been freed already?" );
503 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
504 if ( $refCount <= 0 ) {
505 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
506 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
507 wfDebug( __METHOD__
.": freed connection $serverIndex/$wiki\n" );
509 wfDebug( __METHOD__
.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
514 * Open a connection to the server given by the specified index
515 * Index must be an actual index into the array.
516 * If the server is already open, returns it.
518 * On error, returns false, and the connection which caused the
519 * error will be available via $this->mErrorConnection.
521 * @param $i Integer: server index
522 * @param $wiki String: wiki ID to open
523 * @return DatabaseBase
527 function openConnection( $i, $wiki = 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 );
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 wfProfileOut( __METHOD__
);
553 * Open a connection to a foreign DB, or return one if it is already open.
555 * Increments a reference count on the returned connection which locks the
556 * connection to the requested wiki. This reference count can be
557 * decremented by calling reuseConnection().
559 * If a connection is open to the appropriate server already, but with the wrong
560 * database, it will be switched to the right database and returned, as long as
561 * it has been freed first with reuseConnection().
563 * On error, returns false, and the connection which caused the
564 * error will be available via $this->mErrorConnection.
566 * @param $i Integer: server index
567 * @param $wiki String: wiki ID to open
568 * @return DatabaseBase
570 function openForeignConnection( $i, $wiki ) {
571 wfProfileIn(__METHOD__
);
572 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
573 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
574 // Reuse an already-used connection
575 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
576 wfDebug( __METHOD__
.": reusing connection $i/$wiki\n" );
577 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
578 // Reuse a free connection for the same wiki
579 $conn = $this->mConns
['foreignFree'][$i][$wiki];
580 unset( $this->mConns
['foreignFree'][$i][$wiki] );
581 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
582 wfDebug( __METHOD__
.": reusing free connection $i/$wiki\n" );
583 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
584 // Reuse a connection from another wiki
585 $conn = reset( $this->mConns
['foreignFree'][$i] );
586 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
588 if ( !$conn->selectDB( $dbName ) ) {
589 $this->mLastError
= "Error selecting database $dbName on server " .
590 $conn->getServer() . " from client host " . wfHostname() . "\n";
591 $this->mErrorConnection
= $conn;
594 $conn->tablePrefix( $prefix );
595 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
596 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
597 wfDebug( __METHOD__
.": reusing free connection from $oldWiki for $wiki\n" );
600 // Open a new connection
601 $server = $this->mServers
[$i];
602 $server['serverIndex'] = $i;
603 $server['foreignPoolRefCount'] = 0;
604 $conn = $this->reallyOpenConnection( $server, $dbName );
605 if ( !$conn->isOpen() ) {
606 wfDebug( __METHOD__
.": error opening connection for $i/$wiki\n" );
607 $this->mErrorConnection
= $conn;
610 $conn->tablePrefix( $prefix );
611 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
612 wfDebug( __METHOD__
.": opened new connection for $i/$wiki\n" );
616 // Increment reference count
618 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
619 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
621 wfProfileOut(__METHOD__
);
626 * Test if the specified index represents an open connection
628 * @param $index Integer: server index
631 function isOpen( $index ) {
632 if( !is_integer( $index ) ) {
635 return (bool)$this->getAnyOpenConnection( $index );
639 * Really opens a connection. Uncached.
640 * Returns a Database object whether or not the connection was successful.
643 function reallyOpenConnection( $server, $dbNameOverride = false ) {
644 if( !is_array( $server ) ) {
645 throw new MWException( 'You must update your load-balancing configuration. ' .
646 'See DefaultSettings.php entry for $wgDBservers.' );
649 $host = $server['host'];
650 $dbname = $server['dbname'];
652 if ( $dbNameOverride !== false ) {
653 $server['dbname'] = $dbname = $dbNameOverride;
657 wfDebug( "Connecting to $host $dbname...\n" );
658 $db = DatabaseBase
::newFromType( $server['type'], $server );
659 if ( $db->isOpen() ) {
660 wfDebug( "Connected to $host $dbname.\n" );
662 wfDebug( "Connection failed to $host $dbname.\n" );
664 $db->setLBInfo( $server );
665 if ( isset( $server['fakeSlaveLag'] ) ) {
666 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
668 if ( isset( $server['fakeMaster'] ) ) {
669 $db->setFakeMaster( true );
674 function reportConnectionError( &$conn ) {
675 wfProfileIn( __METHOD__
);
677 if ( !is_object( $conn ) ) {
678 // No last connection, probably due to all servers being too busy
679 wfLogDBError( "LB failure with no last connection\n" );
680 $conn = new Database
;
681 // If all servers were busy, mLastError will contain something sensible
682 throw new DBConnectionError( $conn, $this->mLastError
);
684 $server = $conn->getProperty( 'mServer' );
685 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
686 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
688 wfProfileOut( __METHOD__
);
691 function getWriterIndex() {
696 * Returns true if the specified index is a valid server index
698 function haveIndex( $i ) {
699 return array_key_exists( $i, $this->mServers
);
703 * Returns true if the specified index is valid and has non-zero load
705 function isNonZeroLoad( $i ) {
706 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
710 * Get the number of defined servers (not the number of open connections)
712 function getServerCount() {
713 return count( $this->mServers
);
717 * Get the host name or IP address of the server with the specified index
718 * Prefer a readable name if available.
720 function getServerName( $i ) {
721 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
722 return $this->mServers
[$i]['hostName'];
723 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
724 return $this->mServers
[$i]['host'];
731 * Return the server info structure for a given index, or false if the index is invalid.
733 function getServerInfo( $i ) {
734 if ( isset( $this->mServers
[$i] ) ) {
735 return $this->mServers
[$i];
742 * Sets the server info structure for the given index. Entry at index $i is created if it doesn't exist
744 function setServerInfo( $i, $serverInfo ) {
745 $this->mServers
[$i] = $serverInfo;
749 * Get the current master position for chronology control purposes
752 function getMasterPos() {
753 # If this entire request was served from a slave without opening a connection to the
754 # master (however unlikely that may be), then we can fetch the position from the slave.
755 $masterConn = $this->getAnyOpenConnection( 0 );
756 if ( !$masterConn ) {
757 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
758 $conn = $this->getAnyOpenConnection( $i );
760 wfDebug( "Master pos fetched from slave\n" );
761 return $conn->getSlavePos();
765 wfDebug( "Master pos fetched from master\n" );
766 return $masterConn->getMasterPos();
772 * Close all open connections
774 function closeAll() {
775 foreach ( $this->mConns
as $conns2 ) {
776 foreach ( $conns2 as $conns3 ) {
777 foreach ( $conns3 as $conn ) {
782 $this->mConns
= array(
784 'foreignFree' => array(),
785 'foreignUsed' => array(),
790 * Deprecated function, typo in function name
792 function closeConnecton( $conn ) {
793 $this->closeConnection( $conn );
798 * Using this function makes sure the LoadBalancer knows the connection is closed.
799 * If you use $conn->close() directly, the load balancer won't update its state.
803 function closeConnection( $conn ) {
805 foreach ( $this->mConns
as $i1 => $conns2 ) {
806 foreach ( $conns2 as $i2 => $conns3 ) {
807 foreach ( $conns3 as $i3 => $candidateConn ) {
808 if ( $conn === $candidateConn ) {
810 unset( $this->mConns
[$i1][$i2][$i3] );
823 * Commit transactions on all open connections
825 function commitAll() {
826 foreach ( $this->mConns
as $conns2 ) {
827 foreach ( $conns2 as $conns3 ) {
828 foreach ( $conns3 as $conn ) {
835 /* Issue COMMIT only on master, only if queries were done on connection */
836 function commitMasterChanges() {
837 // Always 0, but who knows.. :)
838 $masterIndex = $this->getWriterIndex();
839 foreach ( $this->mConns
as $conns2 ) {
840 if ( empty( $conns2[$masterIndex] ) ) {
843 foreach ( $conns2[$masterIndex] as $conn ) {
844 if ( $conn->doneWrites() ) {
851 function waitTimeout( $value = null ) {
852 return wfSetVar( $this->mWaitTimeout
, $value );
855 function getLaggedSlaveMode() {
856 return $this->mLaggedSlaveMode
;
859 /* Disables/enables lag checks */
860 function allowLagged($mode=null) {
862 return $this->mAllowLagged
;
863 $this->mAllowLagged
=$mode;
868 foreach ( $this->mConns
as $conns2 ) {
869 foreach ( $conns2 as $conns3 ) {
870 foreach ( $conns3 as $conn ) {
871 if ( !$conn->ping() ) {
881 * Call a function with each open connection object
883 function forEachOpenConnection( $callback, $params = array() ) {
884 foreach ( $this->mConns
as $conns2 ) {
885 foreach ( $conns2 as $conns3 ) {
886 foreach ( $conns3 as $conn ) {
887 $mergedParams = array_merge( array( $conn ), $params );
888 call_user_func_array( $callback, $mergedParams );
895 * Get the hostname and lag time of the most-lagged slave.
896 * This is useful for maintenance scripts that need to throttle their updates.
897 * May attempt to open connections to slaves on the default DB.
898 * @param $wiki string Wiki ID, or false for the default database
900 function getMaxLag( $wiki = false ) {
903 foreach ( $this->mServers
as $i => $conn ) {
905 if ( $wiki === false ) {
906 $conn = $this->getAnyOpenConnection( $i );
909 $conn = $this->openConnection( $i, $wiki );
914 $lag = $conn->getLag();
915 if ( $lag > $maxLag ) {
917 $host = $this->mServers
[$i]['host'];
920 return array( $host, $maxLag );
924 * Get lag time for each server
925 * Results are cached for a short time in memcached, and indefinitely in the process cache
927 function getLagTimes( $wiki = false ) {
929 if ( isset( $this->mLagTimes
) ) {
930 return $this->mLagTimes
;
932 # No, send the request to the load monitor
933 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
934 return $this->mLagTimes
;
938 * Clear the cache for getLagTimes
940 function clearLagTimeCache() {
941 $this->mLagTimes
= null;