2283a1e27c6408614762611893590d4638a50781
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 ) {
31 if ( !isset( $params['servers'] ) ) {
32 throw new MWException( __CLASS__
.': missing servers parameter' );
34 $this->mServers
= $params['servers'];
36 if ( isset( $params['waitTimeout'] ) ) {
37 $this->mWaitTimeout
= $params['waitTimeout'];
39 $this->mWaitTimeout
= 10;
42 $this->mReadIndex
= -1;
43 $this->mWriteIndex
= -1;
44 $this->mConns
= array(
46 'foreignUsed' => array(),
47 'foreignFree' => array() );
48 $this->mLoads
= array();
49 $this->mWaitForPos
= false;
50 $this->mLaggedSlaveMode
= false;
51 $this->mErrorConnection
= false;
52 $this->mAllowLagged
= false;
53 $this->mLoadMonitorClass
= isset( $params['loadMonitor'] )
54 ?
$params['loadMonitor'] : 'LoadMonitor_MySQL';
56 foreach( $params['servers'] as $i => $server ) {
57 $this->mLoads
[$i] = $server['load'];
58 if ( isset( $server['groupLoads'] ) ) {
59 foreach ( $server['groupLoads'] as $group => $ratio ) {
60 if ( !isset( $this->mGroupLoads
[$group] ) ) {
61 $this->mGroupLoads
[$group] = array();
63 $this->mGroupLoads
[$group][$i] = $ratio;
70 * Get a LoadMonitor instance
74 function getLoadMonitor() {
75 if ( !isset( $this->mLoadMonitor
) ) {
76 $class = $this->mLoadMonitorClass
;
77 $this->mLoadMonitor
= new $class( $this );
79 return $this->mLoadMonitor
;
83 * Get or set arbitrary data used by the parent object, usually an LBFactory
85 function parentInfo( $x = null ) {
86 return wfSetVar( $this->mParentInfo
, $x );
90 * Given an array of non-normalised probabilities, this function will select
91 * an element and return the appropriate key
97 function pickRandom( $weights ) {
98 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
102 $sum = array_sum( $weights );
104 # No loads on any of them
105 # In previous versions, this triggered an unweighted random selection,
106 # but this feature has been removed as of April 2006 to allow for strict
107 # separation of query groups.
110 $max = mt_getrandmax();
111 $rand = mt_rand(0, $max) / $max * $sum;
114 foreach ( $weights as $i => $w ) {
116 if ( $sum >= $rand ) {
126 * @return bool|int|string
128 function getRandomNonLagged( $loads, $wiki = false ) {
129 # Unset excessively lagged servers
130 $lags = $this->getLagTimes( $wiki );
131 foreach ( $lags as $i => $lag ) {
133 if ( $lag === false ) {
134 wfDebug( "Server #$i is not replicating\n" );
136 } elseif ( isset( $this->mServers
[$i]['max lag'] ) && $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
174 * @return bool|int|string
176 function getReaderIndex( $group = false, $wiki = false ) {
177 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
179 # @todo FIXME: For now, only go through all this for mysql databases
180 if ($wgDBtype != 'mysql') {
181 return $this->getWriterIndex();
184 if ( count( $this->mServers
) == 1 ) {
185 # Skip the load balancing if there's only one server
187 } elseif ( $group === false and $this->mReadIndex
>= 0 ) {
188 # Shortcut if generic reader exists already
189 return $this->mReadIndex
;
192 wfProfileIn( __METHOD__
);
196 # convert from seconds to microseconds
197 $timeout = $wgDBClusterTimeout * 1e6
;
199 # Find the relevant load array
200 if ( $group !== false ) {
201 if ( isset( $this->mGroupLoads
[$group] ) ) {
202 $nonErrorLoads = $this->mGroupLoads
[$group];
204 # No loads for this group, return false and the caller can use some other group
205 wfDebug( __METHOD__
.": no loads for group $group\n" );
206 wfProfileOut( __METHOD__
);
210 $nonErrorLoads = $this->mLoads
;
213 if ( !$nonErrorLoads ) {
214 throw new MWException( "Empty server array given to LoadBalancer" );
217 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
218 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
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 = wfMessage( 'readonly_lag' )->useDatabase( false )->plain();
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 * Set the master wait position
337 * If a DB_SLAVE connection has been opened already, waits
338 * Otherwise sets a variable telling it to wait if such a connection is opened
340 public function waitFor( $pos ) {
341 wfProfileIn( __METHOD__
);
342 $this->mWaitForPos
= $pos;
343 $i = $this->mReadIndex
;
346 if ( !$this->doWait( $i ) ) {
347 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
348 $this->mLaggedSlaveMode
= true;
351 wfProfileOut( __METHOD__
);
355 * Set the master wait position and wait for ALL slaves to catch up to it
357 public function waitForAll( $pos ) {
358 wfProfileIn( __METHOD__
);
359 $this->mWaitForPos
= $pos;
360 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
361 $this->doWait( $i , true );
363 wfProfileOut( __METHOD__
);
367 * Get any open connection to a given server index, local or foreign
368 * Returns false if there is no connection open
370 * @return DatabaseBase
372 function getAnyOpenConnection( $i ) {
373 foreach ( $this->mConns
as $conns ) {
374 if ( !empty( $conns[$i] ) ) {
375 return reset( $conns[$i] );
382 * Wait for a given slave to catch up to the master pos stored in $this
384 function doWait( $index, $open = false ) {
385 # Find a connection to wait on
386 $conn = $this->getAnyOpenConnection( $index );
389 wfDebug( __METHOD__
. ": no connection open\n" );
392 $conn = $this->openConnection( $index );
394 wfDebug( __METHOD__
. ": failed to open connection\n" );
400 wfDebug( __METHOD__
.": Waiting for slave #$index to catch up...\n" );
401 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
403 if ( $result == -1 ||
is_null( $result ) ) {
404 # Timed out waiting for slave, use master instead
405 wfDebug( __METHOD__
.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
408 wfDebug( __METHOD__
.": Done\n" );
414 * Get a connection by index
415 * This is the main entry point for this class.
417 * @param $i Integer: server index
418 * @param $groups Array: query groups
419 * @param $wiki String: wiki ID
421 * @return DatabaseBase
423 public function &getConnection( $i, $groups = array(), $wiki = false ) {
424 wfProfileIn( __METHOD__
);
426 if ( $i == DB_LAST
) {
427 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with deprecated server index DB_LAST' );
428 } elseif ( $i === null ||
$i === false ) {
429 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with invalid server index' );
432 if ( $wiki === wfWikiID() ) {
437 if ( $i == DB_MASTER
) {
438 $i = $this->getWriterIndex();
439 } elseif ( !is_array( $groups ) ) {
440 $groupIndex = $this->getReaderIndex( $groups, $wiki );
441 if ( $groupIndex !== false ) {
442 $serverName = $this->getServerName( $groupIndex );
443 wfDebug( __METHOD__
.": using server $serverName for group $groups\n" );
447 foreach ( $groups as $group ) {
448 $groupIndex = $this->getReaderIndex( $group, $wiki );
449 if ( $groupIndex !== false ) {
450 $serverName = $this->getServerName( $groupIndex );
451 wfDebug( __METHOD__
.": using server $serverName for group $group\n" );
458 # Operation-based index
459 if ( $i == DB_SLAVE
) {
460 $i = $this->getReaderIndex( false, $wiki );
461 # Couldn't find a working server in getReaderIndex()?
462 if ( $i === false ) {
463 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
464 $this->reportConnectionError( $this->mErrorConnection
);
465 wfProfileOut( __METHOD__
);
470 # Now we have an explicit index into the servers array
471 $conn = $this->openConnection( $i, $wiki );
473 $this->reportConnectionError( $this->mErrorConnection
);
476 wfProfileOut( __METHOD__
);
481 * Mark a foreign connection as being available for reuse under a different
482 * DB name or prefix. This mechanism is reference-counted, and must be called
483 * the same number of times as getConnection() to work.
485 * @param DatabaseBase $conn
487 public function reuseConnection( $conn ) {
488 $serverIndex = $conn->getLBInfo('serverIndex');
489 $refCount = $conn->getLBInfo('foreignPoolRefCount');
490 $dbName = $conn->getDBname();
491 $prefix = $conn->tablePrefix();
492 if ( strval( $prefix ) !== '' ) {
493 $wiki = "$dbName-$prefix";
497 if ( $serverIndex === null ||
$refCount === null ) {
498 wfDebug( __METHOD__
.": this connection was not opened as a foreign connection\n" );
500 * This can happen in code like:
501 * foreach ( $dbs as $db ) {
502 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
504 * $lb->reuseConnection( $conn );
506 * When a connection to the local DB is opened in this way, reuseConnection()
511 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
512 throw new MWException( __METHOD__
.": connection not found, has the connection been freed already?" );
514 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
515 if ( $refCount <= 0 ) {
516 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
517 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
518 wfDebug( __METHOD__
.": freed connection $serverIndex/$wiki\n" );
520 wfDebug( __METHOD__
.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
525 * Open a connection to the server given by the specified index
526 * Index must be an actual index into the array.
527 * If the server is already open, returns it.
529 * On error, returns false, and the connection which caused the
530 * error will be available via $this->mErrorConnection.
532 * @param $i Integer server index
533 * @param $wiki String wiki ID to open
534 * @return DatabaseBase
538 function openConnection( $i, $wiki = false ) {
539 wfProfileIn( __METHOD__
);
540 if ( $wiki !== false ) {
541 $conn = $this->openForeignConnection( $i, $wiki );
542 wfProfileOut( __METHOD__
);
545 if ( isset( $this->mConns
['local'][$i][0] ) ) {
546 $conn = $this->mConns
['local'][$i][0];
548 $server = $this->mServers
[$i];
549 $server['serverIndex'] = $i;
550 $conn = $this->reallyOpenConnection( $server, false );
551 if ( $conn->isOpen() ) {
552 $this->mConns
['local'][$i][0] = $conn;
554 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
555 $this->mErrorConnection
= $conn;
559 wfProfileOut( __METHOD__
);
564 * Open a connection to a foreign DB, or return one if it is already open.
566 * Increments a reference count on the returned connection which locks the
567 * connection to the requested wiki. This reference count can be
568 * decremented by calling reuseConnection().
570 * If a connection is open to the appropriate server already, but with the wrong
571 * database, it will be switched to the right database and returned, as long as
572 * it has been freed first with reuseConnection().
574 * On error, returns false, and the connection which caused the
575 * error will be available via $this->mErrorConnection.
577 * @param $i Integer: server index
578 * @param $wiki String: wiki ID to open
579 * @return DatabaseBase
581 function openForeignConnection( $i, $wiki ) {
582 wfProfileIn(__METHOD__
);
583 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
584 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
585 // Reuse an already-used connection
586 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
587 wfDebug( __METHOD__
.": reusing connection $i/$wiki\n" );
588 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
589 // Reuse a free connection for the same wiki
590 $conn = $this->mConns
['foreignFree'][$i][$wiki];
591 unset( $this->mConns
['foreignFree'][$i][$wiki] );
592 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
593 wfDebug( __METHOD__
.": reusing free connection $i/$wiki\n" );
594 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
595 // Reuse a connection from another wiki
596 $conn = reset( $this->mConns
['foreignFree'][$i] );
597 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
599 if ( !$conn->selectDB( $dbName ) ) {
600 $this->mLastError
= "Error selecting database $dbName on server " .
601 $conn->getServer() . " from client host " . wfHostname() . "\n";
602 $this->mErrorConnection
= $conn;
605 $conn->tablePrefix( $prefix );
606 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
607 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
608 wfDebug( __METHOD__
.": reusing free connection from $oldWiki for $wiki\n" );
611 // Open a new connection
612 $server = $this->mServers
[$i];
613 $server['serverIndex'] = $i;
614 $server['foreignPoolRefCount'] = 0;
615 $conn = $this->reallyOpenConnection( $server, $dbName );
616 if ( !$conn->isOpen() ) {
617 wfDebug( __METHOD__
.": error opening connection for $i/$wiki\n" );
618 $this->mErrorConnection
= $conn;
621 $conn->tablePrefix( $prefix );
622 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
623 wfDebug( __METHOD__
.": opened new connection for $i/$wiki\n" );
627 // Increment reference count
629 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
630 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
632 wfProfileOut(__METHOD__
);
637 * Test if the specified index represents an open connection
639 * @param $index Integer: server index
643 function isOpen( $index ) {
644 if( !is_integer( $index ) ) {
647 return (bool)$this->getAnyOpenConnection( $index );
651 * Really opens a connection. Uncached.
652 * Returns a Database object whether or not the connection was successful.
655 * @return DatabaseBase
657 function reallyOpenConnection( $server, $dbNameOverride = false ) {
658 if( !is_array( $server ) ) {
659 throw new MWException( 'You must update your load-balancing configuration. ' .
660 'See DefaultSettings.php entry for $wgDBservers.' );
663 $host = $server['host'];
664 $dbname = $server['dbname'];
666 if ( $dbNameOverride !== false ) {
667 $server['dbname'] = $dbname = $dbNameOverride;
671 wfDebug( "Connecting to $host $dbname...\n" );
672 $db = DatabaseBase
::newFromType( $server['type'], $server );
673 if ( $db->isOpen() ) {
674 wfDebug( "Connected to $host $dbname.\n" );
676 wfDebug( "Connection failed to $host $dbname.\n" );
678 $db->setLBInfo( $server );
679 if ( isset( $server['fakeSlaveLag'] ) ) {
680 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
682 if ( isset( $server['fakeMaster'] ) ) {
683 $db->setFakeMaster( true );
688 function reportConnectionError( &$conn ) {
689 wfProfileIn( __METHOD__
);
691 if ( !is_object( $conn ) ) {
692 // No last connection, probably due to all servers being too busy
693 wfLogDBError( "LB failure with no last connection\n" );
694 $conn = new Database
;
695 // If all servers were busy, mLastError will contain something sensible
696 throw new DBConnectionError( $conn, $this->mLastError
);
698 $server = $conn->getProperty( 'mServer' );
699 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
700 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
702 wfProfileOut( __METHOD__
);
705 function getWriterIndex() {
710 * Returns true if the specified index is a valid server index
714 function haveIndex( $i ) {
715 return array_key_exists( $i, $this->mServers
);
719 * Returns true if the specified index is valid and has non-zero load
723 function isNonZeroLoad( $i ) {
724 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
728 * Get the number of defined servers (not the number of open connections)
732 function getServerCount() {
733 return count( $this->mServers
);
737 * Get the host name or IP address of the server with the specified index
738 * Prefer a readable name if available.
740 function getServerName( $i ) {
741 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
742 return $this->mServers
[$i]['hostName'];
743 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
744 return $this->mServers
[$i]['host'];
751 * Return the server info structure for a given index, or false if the index is invalid.
753 function getServerInfo( $i ) {
754 if ( isset( $this->mServers
[$i] ) ) {
755 return $this->mServers
[$i];
762 * Sets the server info structure for the given index. Entry at index $i is created if it doesn't exist
764 function setServerInfo( $i, $serverInfo ) {
765 $this->mServers
[$i] = $serverInfo;
769 * Get the current master position for chronology control purposes
772 function getMasterPos() {
773 # If this entire request was served from a slave without opening a connection to the
774 # master (however unlikely that may be), then we can fetch the position from the slave.
775 $masterConn = $this->getAnyOpenConnection( 0 );
776 if ( !$masterConn ) {
777 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
778 $conn = $this->getAnyOpenConnection( $i );
780 wfDebug( "Master pos fetched from slave\n" );
781 return $conn->getSlavePos();
785 wfDebug( "Master pos fetched from master\n" );
786 return $masterConn->getMasterPos();
792 * Close all open connections
794 function closeAll() {
795 foreach ( $this->mConns
as $conns2 ) {
796 foreach ( $conns2 as $conns3 ) {
797 foreach ( $conns3 as $conn ) {
802 $this->mConns
= array(
804 'foreignFree' => array(),
805 'foreignUsed' => array(),
810 * Deprecated function, typo in function name
812 * @deprecated in 1.18
814 function closeConnecton( $conn ) {
815 $this->closeConnection( $conn );
820 * Using this function makes sure the LoadBalancer knows the connection is closed.
821 * If you use $conn->close() directly, the load balancer won't update its state.
825 function closeConnection( $conn ) {
827 foreach ( $this->mConns
as $i1 => $conns2 ) {
828 foreach ( $conns2 as $i2 => $conns3 ) {
829 foreach ( $conns3 as $i3 => $candidateConn ) {
830 if ( $conn === $candidateConn ) {
832 unset( $this->mConns
[$i1][$i2][$i3] );
845 * Commit transactions on all open connections
847 function commitAll() {
848 foreach ( $this->mConns
as $conns2 ) {
849 foreach ( $conns2 as $conns3 ) {
850 foreach ( $conns3 as $conn ) {
858 * Issue COMMIT only on master, only if queries were done on connection
860 function commitMasterChanges() {
861 // Always 0, but who knows.. :)
862 $masterIndex = $this->getWriterIndex();
863 foreach ( $this->mConns
as $conns2 ) {
864 if ( empty( $conns2[$masterIndex] ) ) {
867 foreach ( $conns2[$masterIndex] as $conn ) {
868 if ( $conn->doneWrites() ) {
875 function waitTimeout( $value = null ) {
876 return wfSetVar( $this->mWaitTimeout
, $value );
879 function getLaggedSlaveMode() {
880 return $this->mLaggedSlaveMode
;
883 /* Disables/enables lag checks */
884 function allowLagged( $mode = null ) {
885 if ( $mode === null) {
886 return $this->mAllowLagged
;
888 $this->mAllowLagged
= $mode;
893 foreach ( $this->mConns
as $conns2 ) {
894 foreach ( $conns2 as $conns3 ) {
895 foreach ( $conns3 as $conn ) {
896 if ( !$conn->ping() ) {
906 * Call a function with each open connection object
908 function forEachOpenConnection( $callback, $params = array() ) {
909 foreach ( $this->mConns
as $conns2 ) {
910 foreach ( $conns2 as $conns3 ) {
911 foreach ( $conns3 as $conn ) {
912 $mergedParams = array_merge( array( $conn ), $params );
913 call_user_func_array( $callback, $mergedParams );
920 * Get the hostname and lag time of the most-lagged slave.
921 * This is useful for maintenance scripts that need to throttle their updates.
922 * May attempt to open connections to slaves on the default DB.
923 * @param $wiki string Wiki ID, or false for the default database
925 * @return array ( host, max lag, index of max lagged host )
927 function getMaxLag( $wiki = false ) {
931 foreach ( $this->mServers
as $i => $conn ) {
933 if ( $wiki === false ) {
934 $conn = $this->getAnyOpenConnection( $i );
937 $conn = $this->openConnection( $i, $wiki );
942 $lag = $conn->getLag();
943 if ( $lag > $maxLag ) {
945 $host = $this->mServers
[$i]['host'];
949 return array( $host, $maxLag, $maxIndex );
953 * Get lag time for each server
954 * Results are cached for a short time in memcached, and indefinitely in the process cache
960 function getLagTimes( $wiki = false ) {
962 if ( isset( $this->mLagTimes
) ) {
963 return $this->mLagTimes
;
965 # No, send the request to the load monitor
966 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
967 return $this->mLagTimes
;
971 * Clear the cache for getLagTimes
973 function clearLagTimeCache() {
974 $this->mLagTimes
= null;