46c6155546a7c88c2fa62065befaa0dc28561587
3 * Database load balancing
10 * Database load balancing object
16 /* private */ var $mServers, $mConns, $mLoads, $mGroupLoads;
17 /* private */ var $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 * 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 )
96 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
100 $sum = array_sum( $weights );
102 # No loads on any of them
103 # In previous versions, this triggered an unweighted random selection,
104 # but this feature has been removed as of April 2006 to allow for strict
105 # separation of query groups.
108 $max = mt_getrandmax();
109 $rand = mt_rand(0, $max) / $max * $sum;
112 foreach ( $weights as $i => $w ) {
114 if ( $sum >= $rand ) {
121 function getRandomNonLagged( $loads, $wiki = false ) {
122 # Unset excessively lagged servers
123 $lags = $this->getLagTimes( $wiki );
124 foreach ( $lags as $i => $lag ) {
126 if ( $lag === false ) {
127 wfDebug( "Server #$i is not replicating\n" );
129 } elseif ( isset( $this->mServers
[$i]['max lag'] ) && $lag > $this->mServers
[$i]['max lag'] ) {
130 wfDebug( "Server #$i is excessively lagged ($lag seconds)\n" );
136 # Find out if all the slaves with non-zero load are lagged
138 foreach ( $loads as $load ) {
142 # No appropriate DB servers except maybe the master and some slaves with zero load
143 # Do NOT use the master
144 # Instead, this function will return false, triggering read-only mode,
145 # and a lagged slave will be used instead.
149 if ( count( $loads ) == 0 ) {
153 #wfDebugLog( 'connect', var_export( $loads, true ) );
155 # Return a random representative of the remainder
156 return $this->pickRandom( $loads );
160 * Get the index of the reader connection, which may be a slave
161 * This takes into account load ratios and lag times. It should
162 * always return a consistent index during a given invocation
164 * Side effect: opens connections to databases
166 function getReaderIndex( $group = false, $wiki = false ) {
167 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
169 # FIXME: For now, only go through all this for mysql databases
170 if ($wgDBtype != 'mysql') {
171 return $this->getWriterIndex();
174 if ( count( $this->mServers
) == 1 ) {
175 # Skip the load balancing if there's only one server
177 } elseif ( $group === false and $this->mReadIndex
>= 0 ) {
178 # Shortcut if generic reader exists already
179 return $this->mReadIndex
;
182 wfProfileIn( __METHOD__
);
186 # convert from seconds to microseconds
187 $timeout = $wgDBClusterTimeout * 1e6
;
189 # Find the relevant load array
190 if ( $group !== false ) {
191 if ( isset( $this->mGroupLoads
[$group] ) ) {
192 $nonErrorLoads = $this->mGroupLoads
[$group];
194 # No loads for this group, return false and the caller can use some other group
195 wfDebug( __METHOD__
.": no loads for group $group\n" );
196 wfProfileOut( __METHOD__
);
200 $nonErrorLoads = $this->mLoads
;
203 if ( !$nonErrorLoads ) {
204 throw new MWException( "Empty server array given to LoadBalancer" );
207 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
208 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
210 $laggedSlaveMode = false;
212 # First try quickly looking through the available servers for a server that
215 $totalThreadsConnected = 0;
216 $overloadedServers = 0;
217 $currentLoads = $nonErrorLoads;
218 while ( count( $currentLoads ) ) {
219 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
220 $i = $this->pickRandom( $currentLoads );
222 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
223 if ( $i === false && count( $currentLoads ) != 0 ) {
224 # All slaves lagged. Switch to read-only mode
225 $wgReadOnly = wfMsgNoDBForContent( 'readonly_lag' );
226 $i = $this->pickRandom( $currentLoads );
227 $laggedSlaveMode = true;
231 if ( $i === false ) {
232 # pickRandom() returned false
233 # This is permanent and means the configuration or the load monitor
234 # wants us to return false.
235 wfDebugLog( 'connect', __METHOD__
.": pickRandom() returned false\n" );
236 wfProfileOut( __METHOD__
);
240 wfDebugLog( 'connect', __METHOD__
.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
241 $conn = $this->openConnection( $i, $wiki );
244 wfDebugLog( 'connect', __METHOD__
.": Failed connecting to $i/$wiki\n" );
245 unset( $nonErrorLoads[$i] );
246 unset( $currentLoads[$i] );
250 // Perform post-connection backoff
251 $threshold = isset( $this->mServers
[$i]['max threads'] )
252 ?
$this->mServers
[$i]['max threads'] : false;
253 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
255 // Decrement reference counter, we are finished with this connection.
256 // It will be incremented for the caller later.
257 if ( $wiki !== false ) {
258 $this->reuseConnection( $conn );
262 # Post-connection overload, don't use this server for now
263 $totalThreadsConnected +
= $backoff;
264 $overloadedServers++
;
265 unset( $currentLoads[$i] );
272 # No server found yet
275 # If all servers were down, quit now
276 if ( !count( $nonErrorLoads ) ) {
277 wfDebugLog( 'connect', "All servers down\n" );
281 # Some servers must have been overloaded
282 if ( $overloadedServers == 0 ) {
283 throw new MWException( __METHOD__
.": unexpectedly found no overloaded servers" );
285 # Back off for a while
286 # Scale the sleep time by the number of connected threads, to produce a
287 # roughly constant global poll rate
288 $avgThreads = $totalThreadsConnected / $overloadedServers;
289 $totalElapsed +
= $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
290 } while ( $totalElapsed < $timeout );
292 if ( $totalElapsed >= $timeout ) {
293 wfDebugLog( 'connect', "All servers busy\n" );
294 $this->mErrorConnection
= false;
295 $this->mLastError
= 'All servers busy';
298 if ( $i !== false ) {
299 # Slave connection successful
300 # Wait for the session master pos for a short time
301 if ( $this->mWaitForPos
&& $i > 0 ) {
302 if ( !$this->doWait( $i ) ) {
303 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
306 if ( $this->mReadIndex
<=0 && $this->mLoads
[$i]>0 && $i !== false ) {
307 $this->mReadIndex
= $i;
310 wfProfileOut( __METHOD__
);
315 * Wait for a specified number of microseconds, and return the period waited
317 function sleep( $t ) {
318 wfProfileIn( __METHOD__
);
319 wfDebug( __METHOD__
.": waiting $t us\n" );
321 wfProfileOut( __METHOD__
);
326 * Set the master wait position
327 * If a DB_SLAVE connection has been opened already, waits
328 * Otherwise sets a variable telling it to wait if such a connection is opened
330 public function waitFor( $pos ) {
331 wfProfileIn( __METHOD__
);
332 $this->mWaitForPos
= $pos;
333 $i = $this->mReadIndex
;
336 if ( !$this->doWait( $i ) ) {
337 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
338 $this->mLaggedSlaveMode
= true;
341 wfProfileOut( __METHOD__
);
345 * Set the master wait position and wait for ALL slaves to catch up to it
347 public function waitForAll( $pos ) {
348 wfProfileIn( __METHOD__
);
349 $this->mWaitForPos
= $pos;
350 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
351 $this->doWait( $i , true );
353 wfProfileOut( __METHOD__
);
357 * Get any open connection to a given server index, local or foreign
358 * Returns false if there is no connection open
360 * @return DatabaseBase
362 function getAnyOpenConnection( $i ) {
363 foreach ( $this->mConns
as $conns ) {
364 if ( !empty( $conns[$i] ) ) {
365 return reset( $conns[$i] );
372 * Wait for a given slave to catch up to the master pos stored in $this
374 function doWait( $index, $open = false ) {
375 # Find a connection to wait on
376 $conn = $this->getAnyOpenConnection( $index );
379 wfDebug( __METHOD__
. ": no connection open\n" );
382 $conn = $this->openConnection( $index );
384 wfDebug( __METHOD__
. ": failed to open connection\n" );
390 wfDebug( __METHOD__
.": Waiting for slave #$index to catch up...\n" );
391 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
393 if ( $result == -1 ||
is_null( $result ) ) {
394 # Timed out waiting for slave, use master instead
395 wfDebug( __METHOD__
.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
398 wfDebug( __METHOD__
.": Done\n" );
404 * Get a connection by index
405 * This is the main entry point for this class.
407 * @param $i Integer: server index
408 * @param $groups Array: query groups
409 * @param $wiki String: wiki ID
411 * @return DatabaseBase
413 public function &getConnection( $i, $groups = array(), $wiki = false ) {
414 wfProfileIn( __METHOD__
);
416 if ( $i == DB_LAST
) {
417 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with deprecated server index DB_LAST' );
418 } elseif ( $i === null ||
$i === false ) {
419 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with invalid server index' );
422 if ( $wiki === wfWikiID() ) {
427 if ( $i == DB_MASTER
) {
428 $i = $this->getWriterIndex();
429 } elseif ( !is_array( $groups ) ) {
430 $groupIndex = $this->getReaderIndex( $groups, $wiki );
431 if ( $groupIndex !== false ) {
432 $serverName = $this->getServerName( $groupIndex );
433 wfDebug( __METHOD__
.": using server $serverName for group $groups\n" );
437 foreach ( $groups as $group ) {
438 $groupIndex = $this->getReaderIndex( $group, $wiki );
439 if ( $groupIndex !== false ) {
440 $serverName = $this->getServerName( $groupIndex );
441 wfDebug( __METHOD__
.": using server $serverName for group $group\n" );
448 # Operation-based index
449 if ( $i == DB_SLAVE
) {
450 $i = $this->getReaderIndex( false, $wiki );
451 # Couldn't find a working server in getReaderIndex()?
452 if ( $i === false ) {
453 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
454 $this->reportConnectionError( $this->mErrorConnection
);
455 wfProfileOut( __METHOD__
);
460 # Now we have an explicit index into the servers array
461 $conn = $this->openConnection( $i, $wiki );
463 $this->reportConnectionError( $this->mErrorConnection
);
466 wfProfileOut( __METHOD__
);
471 * Mark a foreign connection as being available for reuse under a different
472 * DB name or prefix. This mechanism is reference-counted, and must be called
473 * the same number of times as getConnection() to work.
475 * @param DatabaseBase $conn
477 public function reuseConnection( $conn ) {
478 $serverIndex = $conn->getLBInfo('serverIndex');
479 $refCount = $conn->getLBInfo('foreignPoolRefCount');
480 $dbName = $conn->getDBname();
481 $prefix = $conn->tablePrefix();
482 if ( strval( $prefix ) !== '' ) {
483 $wiki = "$dbName-$prefix";
487 if ( $serverIndex === null ||
$refCount === null ) {
488 wfDebug( __METHOD__
.": this connection was not opened as a foreign connection\n" );
490 * This can happen in code like:
491 * foreach ( $dbs as $db ) {
492 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
494 * $lb->reuseConnection( $conn );
496 * When a connection to the local DB is opened in this way, reuseConnection()
501 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
502 throw new MWException( __METHOD__
.": connection not found, has the connection been freed already?" );
504 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
505 if ( $refCount <= 0 ) {
506 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
507 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
508 wfDebug( __METHOD__
.": freed connection $serverIndex/$wiki\n" );
510 wfDebug( __METHOD__
.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
515 * Open a connection to the server given by the specified index
516 * Index must be an actual index into the array.
517 * If the server is already open, returns it.
519 * On error, returns false, and the connection which caused the
520 * error will be available via $this->mErrorConnection.
522 * @param $i Integer: server index
523 * @param $wiki String: wiki ID to open
524 * @return DatabaseBase
528 function openConnection( $i, $wiki = false ) {
529 wfProfileIn( __METHOD__
);
530 if ( $wiki !== false ) {
531 $conn = $this->openForeignConnection( $i, $wiki );
532 wfProfileOut( __METHOD__
);
535 if ( isset( $this->mConns
['local'][$i][0] ) ) {
536 $conn = $this->mConns
['local'][$i][0];
538 $server = $this->mServers
[$i];
539 $server['serverIndex'] = $i;
540 $conn = $this->reallyOpenConnection( $server, false );
541 if ( $conn->isOpen() ) {
542 $this->mConns
['local'][$i][0] = $conn;
544 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
545 $this->mErrorConnection
= $conn;
549 wfProfileOut( __METHOD__
);
554 * Open a connection to a foreign DB, or return one if it is already open.
556 * Increments a reference count on the returned connection which locks the
557 * connection to the requested wiki. This reference count can be
558 * decremented by calling reuseConnection().
560 * If a connection is open to the appropriate server already, but with the wrong
561 * database, it will be switched to the right database and returned, as long as
562 * it has been freed first with reuseConnection().
564 * On error, returns false, and the connection which caused the
565 * error will be available via $this->mErrorConnection.
567 * @param $i Integer: server index
568 * @param $wiki String: wiki ID to open
569 * @return DatabaseBase
571 function openForeignConnection( $i, $wiki ) {
572 wfProfileIn(__METHOD__
);
573 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
574 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
575 // Reuse an already-used connection
576 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
577 wfDebug( __METHOD__
.": reusing connection $i/$wiki\n" );
578 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
579 // Reuse a free connection for the same wiki
580 $conn = $this->mConns
['foreignFree'][$i][$wiki];
581 unset( $this->mConns
['foreignFree'][$i][$wiki] );
582 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
583 wfDebug( __METHOD__
.": reusing free connection $i/$wiki\n" );
584 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
585 // Reuse a connection from another wiki
586 $conn = reset( $this->mConns
['foreignFree'][$i] );
587 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
589 if ( !$conn->selectDB( $dbName ) ) {
590 $this->mLastError
= "Error selecting database $dbName on server " .
591 $conn->getServer() . " from client host " . wfHostname() . "\n";
592 $this->mErrorConnection
= $conn;
595 $conn->tablePrefix( $prefix );
596 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
597 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
598 wfDebug( __METHOD__
.": reusing free connection from $oldWiki for $wiki\n" );
601 // Open a new connection
602 $server = $this->mServers
[$i];
603 $server['serverIndex'] = $i;
604 $server['foreignPoolRefCount'] = 0;
605 $conn = $this->reallyOpenConnection( $server, $dbName );
606 if ( !$conn->isOpen() ) {
607 wfDebug( __METHOD__
.": error opening connection for $i/$wiki\n" );
608 $this->mErrorConnection
= $conn;
611 $conn->tablePrefix( $prefix );
612 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
613 wfDebug( __METHOD__
.": opened new connection for $i/$wiki\n" );
617 // Increment reference count
619 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
620 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
622 wfProfileOut(__METHOD__
);
627 * Test if the specified index represents an open connection
629 * @param $index Integer: server index
632 function isOpen( $index ) {
633 if( !is_integer( $index ) ) {
636 return (bool)$this->getAnyOpenConnection( $index );
640 * Really opens a connection. Uncached.
641 * Returns a Database object whether or not the connection was successful.
644 function reallyOpenConnection( $server, $dbNameOverride = false ) {
645 if( !is_array( $server ) ) {
646 throw new MWException( 'You must update your load-balancing configuration. ' .
647 'See DefaultSettings.php entry for $wgDBservers.' );
650 $host = $server['host'];
651 $dbname = $server['dbname'];
653 if ( $dbNameOverride !== false ) {
654 $server['dbname'] = $dbname = $dbNameOverride;
658 wfDebug( "Connecting to $host $dbname...\n" );
659 $db = DatabaseBase
::newFromType( $server['type'], $server );
660 if ( $db->isOpen() ) {
661 wfDebug( "Connected to $host $dbname.\n" );
663 wfDebug( "Connection failed to $host $dbname.\n" );
665 $db->setLBInfo( $server );
666 if ( isset( $server['fakeSlaveLag'] ) ) {
667 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
669 if ( isset( $server['fakeMaster'] ) ) {
670 $db->setFakeMaster( true );
675 function reportConnectionError( &$conn ) {
676 wfProfileIn( __METHOD__
);
678 if ( !is_object( $conn ) ) {
679 // No last connection, probably due to all servers being too busy
680 wfLogDBError( "LB failure with no last connection\n" );
681 $conn = new Database
;
682 // If all servers were busy, mLastError will contain something sensible
683 throw new DBConnectionError( $conn, $this->mLastError
);
685 $server = $conn->getProperty( 'mServer' );
686 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
687 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
689 wfProfileOut( __METHOD__
);
692 function getWriterIndex() {
697 * Returns true if the specified index is a valid server index
699 function haveIndex( $i ) {
700 return array_key_exists( $i, $this->mServers
);
704 * Returns true if the specified index is valid and has non-zero load
706 function isNonZeroLoad( $i ) {
707 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
711 * Get the number of defined servers (not the number of open connections)
713 function getServerCount() {
714 return count( $this->mServers
);
718 * Get the host name or IP address of the server with the specified index
719 * Prefer a readable name if available.
721 function getServerName( $i ) {
722 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
723 return $this->mServers
[$i]['hostName'];
724 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
725 return $this->mServers
[$i]['host'];
732 * Return the server info structure for a given index, or false if the index is invalid.
734 function getServerInfo( $i ) {
735 if ( isset( $this->mServers
[$i] ) ) {
736 return $this->mServers
[$i];
743 * Get the current master position for chronology control purposes
746 function getMasterPos() {
747 # If this entire request was served from a slave without opening a connection to the
748 # master (however unlikely that may be), then we can fetch the position from the slave.
749 $masterConn = $this->getAnyOpenConnection( 0 );
750 if ( !$masterConn ) {
751 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
752 $conn = $this->getAnyOpenConnection( $i );
754 wfDebug( "Master pos fetched from slave\n" );
755 return $conn->getSlavePos();
759 wfDebug( "Master pos fetched from master\n" );
760 return $masterConn->getMasterPos();
766 * Close all open connections
768 function closeAll() {
769 foreach ( $this->mConns
as $conns2 ) {
770 foreach ( $conns2 as $conns3 ) {
771 foreach ( $conns3 as $conn ) {
776 $this->mConns
= array(
778 'foreignFree' => array(),
779 'foreignUsed' => array(),
784 * Deprecated function, typo in function name
786 function closeConnecton( $conn ) {
787 $this->closeConnection( $conn );
792 * Using this function makes sure the LoadBalancer knows the connection is closed.
793 * If you use $conn->close() directly, the load balancer won't update its state.
797 function closeConnection( $conn ) {
799 foreach ( $this->mConns
as $i1 => $conns2 ) {
800 foreach ( $conns2 as $i2 => $conns3 ) {
801 foreach ( $conns3 as $i3 => $candidateConn ) {
802 if ( $conn === $candidateConn ) {
804 unset( $this->mConns
[$i1][$i2][$i3] );
817 * Commit transactions on all open connections
819 function commitAll() {
820 foreach ( $this->mConns
as $conns2 ) {
821 foreach ( $conns2 as $conns3 ) {
822 foreach ( $conns3 as $conn ) {
829 /* Issue COMMIT only on master, only if queries were done on connection */
830 function commitMasterChanges() {
831 // Always 0, but who knows.. :)
832 $masterIndex = $this->getWriterIndex();
833 foreach ( $this->mConns
as $conns2 ) {
834 if ( empty( $conns2[$masterIndex] ) ) {
837 foreach ( $conns2[$masterIndex] as $conn ) {
838 if ( $conn->doneWrites() ) {
845 function waitTimeout( $value = null ) {
846 return wfSetVar( $this->mWaitTimeout
, $value );
849 function getLaggedSlaveMode() {
850 return $this->mLaggedSlaveMode
;
853 /* Disables/enables lag checks */
854 function allowLagged($mode=null) {
856 return $this->mAllowLagged
;
857 $this->mAllowLagged
=$mode;
862 foreach ( $this->mConns
as $conns2 ) {
863 foreach ( $conns2 as $conns3 ) {
864 foreach ( $conns3 as $conn ) {
865 if ( !$conn->ping() ) {
875 * Call a function with each open connection object
877 function forEachOpenConnection( $callback, $params = array() ) {
878 foreach ( $this->mConns
as $conns2 ) {
879 foreach ( $conns2 as $conns3 ) {
880 foreach ( $conns3 as $conn ) {
881 $mergedParams = array_merge( array( $conn ), $params );
882 call_user_func_array( $callback, $mergedParams );
889 * Get the hostname and lag time of the most-lagged slave.
890 * This is useful for maintenance scripts that need to throttle their updates.
891 * May attempt to open connections to slaves on the default DB.
892 * @param $wiki string Wiki ID, or false for the default database
894 function getMaxLag( $wiki = false ) {
897 foreach ( $this->mServers
as $i => $conn ) {
899 if ( $wiki === false ) {
900 $conn = $this->getAnyOpenConnection( $i );
903 $conn = $this->openConnection( $i, $wiki );
908 $lag = $conn->getLag();
909 if ( $lag > $maxLag ) {
911 $host = $this->mServers
[$i]['host'];
914 return array( $host, $maxLag );
918 * Get lag time for each server
919 * Results are cached for a short time in memcached, and indefinitely in the process cache
921 function getLagTimes( $wiki = false ) {
923 if ( isset( $this->mLagTimes
) ) {
924 return $this->mLagTimes
;
926 # No, send the request to the load monitor
927 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
928 return $this->mLagTimes
;
932 * Clear the cache for getLagTimes
934 function clearLagTimeCache() {
935 $this->mLagTimes
= null;