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;
54 if ( isset( $params['loadMonitor'] ) ) {
55 $this->mLoadMonitorClass
= $params['loadMonitor'];
57 $master = reset( $params['servers'] );
58 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
59 $this->mLoadMonitorClass
= 'LoadMonitor_MySQL';
61 $this->mLoadMonitorClass
= 'LoadMonitor_Null';
65 foreach( $params['servers'] as $i => $server ) {
66 $this->mLoads
[$i] = $server['load'];
67 if ( isset( $server['groupLoads'] ) ) {
68 foreach ( $server['groupLoads'] as $group => $ratio ) {
69 if ( !isset( $this->mGroupLoads
[$group] ) ) {
70 $this->mGroupLoads
[$group] = array();
72 $this->mGroupLoads
[$group][$i] = $ratio;
79 * Get a LoadMonitor instance
83 function getLoadMonitor() {
84 if ( !isset( $this->mLoadMonitor
) ) {
85 $class = $this->mLoadMonitorClass
;
86 $this->mLoadMonitor
= new $class( $this );
88 return $this->mLoadMonitor
;
92 * Get or set arbitrary data used by the parent object, usually an LBFactory
94 function parentInfo( $x = null ) {
95 return wfSetVar( $this->mParentInfo
, $x );
99 * Given an array of non-normalised probabilities, this function will select
100 * an element and return the appropriate key
106 function pickRandom( $weights ) {
107 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
111 $sum = array_sum( $weights );
113 # No loads on any of them
114 # In previous versions, this triggered an unweighted random selection,
115 # but this feature has been removed as of April 2006 to allow for strict
116 # separation of query groups.
119 $max = mt_getrandmax();
120 $rand = mt_rand(0, $max) / $max * $sum;
123 foreach ( $weights as $i => $w ) {
125 if ( $sum >= $rand ) {
135 * @return bool|int|string
137 function getRandomNonLagged( $loads, $wiki = false ) {
138 # Unset excessively lagged servers
139 $lags = $this->getLagTimes( $wiki );
140 foreach ( $lags as $i => $lag ) {
142 if ( $lag === false ) {
143 wfDebug( "Server #$i is not replicating\n" );
145 } elseif ( isset( $this->mServers
[$i]['max lag'] ) && $lag > $this->mServers
[$i]['max lag'] ) {
146 wfDebug( "Server #$i is excessively lagged ($lag seconds)\n" );
152 # Find out if all the slaves with non-zero load are lagged
154 foreach ( $loads as $load ) {
158 # No appropriate DB servers except maybe the master and some slaves with zero load
159 # Do NOT use the master
160 # Instead, this function will return false, triggering read-only mode,
161 # and a lagged slave will be used instead.
165 if ( count( $loads ) == 0 ) {
169 #wfDebugLog( 'connect', var_export( $loads, true ) );
171 # Return a random representative of the remainder
172 return $this->pickRandom( $loads );
176 * Get the index of the reader connection, which may be a slave
177 * This takes into account load ratios and lag times. It should
178 * always return a consistent index during a given invocation
180 * Side effect: opens connections to databases
183 * @return bool|int|string
185 function getReaderIndex( $group = false, $wiki = false ) {
186 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
188 # @todo FIXME: For now, only go through all this for mysql databases
189 if ($wgDBtype != 'mysql') {
190 return $this->getWriterIndex();
193 if ( count( $this->mServers
) == 1 ) {
194 # Skip the load balancing if there's only one server
196 } elseif ( $group === false and $this->mReadIndex
>= 0 ) {
197 # Shortcut if generic reader exists already
198 return $this->mReadIndex
;
201 wfProfileIn( __METHOD__
);
205 # convert from seconds to microseconds
206 $timeout = $wgDBClusterTimeout * 1e6
;
208 # Find the relevant load array
209 if ( $group !== false ) {
210 if ( isset( $this->mGroupLoads
[$group] ) ) {
211 $nonErrorLoads = $this->mGroupLoads
[$group];
213 # No loads for this group, return false and the caller can use some other group
214 wfDebug( __METHOD__
.": no loads for group $group\n" );
215 wfProfileOut( __METHOD__
);
219 $nonErrorLoads = $this->mLoads
;
222 if ( !$nonErrorLoads ) {
223 throw new MWException( "Empty server array given to LoadBalancer" );
226 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
227 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
229 $laggedSlaveMode = false;
231 # First try quickly looking through the available servers for a server that
234 $totalThreadsConnected = 0;
235 $overloadedServers = 0;
236 $currentLoads = $nonErrorLoads;
237 while ( count( $currentLoads ) ) {
238 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
239 $i = $this->pickRandom( $currentLoads );
241 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
242 if ( $i === false && count( $currentLoads ) != 0 ) {
243 # All slaves lagged. Switch to read-only mode
244 $wgReadOnly = wfMessage( 'readonly_lag' )->useDatabase( false )->plain();
245 $i = $this->pickRandom( $currentLoads );
246 $laggedSlaveMode = true;
250 if ( $i === false ) {
251 # pickRandom() returned false
252 # This is permanent and means the configuration or the load monitor
253 # wants us to return false.
254 wfDebugLog( 'connect', __METHOD__
.": pickRandom() returned false\n" );
255 wfProfileOut( __METHOD__
);
259 wfDebugLog( 'connect', __METHOD__
.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
260 $conn = $this->openConnection( $i, $wiki );
263 wfDebugLog( 'connect', __METHOD__
.": Failed connecting to $i/$wiki\n" );
264 unset( $nonErrorLoads[$i] );
265 unset( $currentLoads[$i] );
269 // Perform post-connection backoff
270 $threshold = isset( $this->mServers
[$i]['max threads'] )
271 ?
$this->mServers
[$i]['max threads'] : false;
272 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
274 // Decrement reference counter, we are finished with this connection.
275 // It will be incremented for the caller later.
276 if ( $wiki !== false ) {
277 $this->reuseConnection( $conn );
281 # Post-connection overload, don't use this server for now
282 $totalThreadsConnected +
= $backoff;
283 $overloadedServers++
;
284 unset( $currentLoads[$i] );
291 # No server found yet
294 # If all servers were down, quit now
295 if ( !count( $nonErrorLoads ) ) {
296 wfDebugLog( 'connect', "All servers down\n" );
300 # Some servers must have been overloaded
301 if ( $overloadedServers == 0 ) {
302 throw new MWException( __METHOD__
.": unexpectedly found no overloaded servers" );
304 # Back off for a while
305 # Scale the sleep time by the number of connected threads, to produce a
306 # roughly constant global poll rate
307 $avgThreads = $totalThreadsConnected / $overloadedServers;
308 $totalElapsed +
= $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
309 } while ( $totalElapsed < $timeout );
311 if ( $totalElapsed >= $timeout ) {
312 wfDebugLog( 'connect', "All servers busy\n" );
313 $this->mErrorConnection
= false;
314 $this->mLastError
= 'All servers busy';
317 if ( $i !== false ) {
318 # Slave connection successful
319 # Wait for the session master pos for a short time
320 if ( $this->mWaitForPos
&& $i > 0 ) {
321 if ( !$this->doWait( $i ) ) {
322 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
325 if ( $this->mReadIndex
<=0 && $this->mLoads
[$i]>0 && $i !== false ) {
326 $this->mReadIndex
= $i;
329 wfProfileOut( __METHOD__
);
334 * Wait for a specified number of microseconds, and return the period waited
336 function sleep( $t ) {
337 wfProfileIn( __METHOD__
);
338 wfDebug( __METHOD__
.": waiting $t us\n" );
340 wfProfileOut( __METHOD__
);
345 * Set the master wait position
346 * If a DB_SLAVE connection has been opened already, waits
347 * Otherwise sets a variable telling it to wait if such a connection is opened
349 public function waitFor( $pos ) {
350 wfProfileIn( __METHOD__
);
351 $this->mWaitForPos
= $pos;
352 $i = $this->mReadIndex
;
355 if ( !$this->doWait( $i ) ) {
356 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
357 $this->mLaggedSlaveMode
= true;
360 wfProfileOut( __METHOD__
);
364 * Set the master wait position and wait for ALL slaves to catch up to it
366 public function waitForAll( $pos ) {
367 wfProfileIn( __METHOD__
);
368 $this->mWaitForPos
= $pos;
369 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
370 $this->doWait( $i , true );
372 wfProfileOut( __METHOD__
);
376 * Get any open connection to a given server index, local or foreign
377 * Returns false if there is no connection open
379 * @return DatabaseBase
381 function getAnyOpenConnection( $i ) {
382 foreach ( $this->mConns
as $conns ) {
383 if ( !empty( $conns[$i] ) ) {
384 return reset( $conns[$i] );
391 * Wait for a given slave to catch up to the master pos stored in $this
393 function doWait( $index, $open = false ) {
394 # Find a connection to wait on
395 $conn = $this->getAnyOpenConnection( $index );
398 wfDebug( __METHOD__
. ": no connection open\n" );
401 $conn = $this->openConnection( $index );
403 wfDebug( __METHOD__
. ": failed to open connection\n" );
409 wfDebug( __METHOD__
.": Waiting for slave #$index to catch up...\n" );
410 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
412 if ( $result == -1 ||
is_null( $result ) ) {
413 # Timed out waiting for slave, use master instead
414 wfDebug( __METHOD__
.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
417 wfDebug( __METHOD__
.": Done\n" );
423 * Get a connection by index
424 * This is the main entry point for this class.
426 * @param $i Integer: server index
427 * @param $groups Array: query groups
428 * @param $wiki String: wiki ID
430 * @return DatabaseBase
432 public function &getConnection( $i, $groups = array(), $wiki = false ) {
433 wfProfileIn( __METHOD__
);
435 if ( $i == DB_LAST
) {
436 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with deprecated server index DB_LAST' );
437 } elseif ( $i === null ||
$i === false ) {
438 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with invalid server index' );
441 if ( $wiki === wfWikiID() ) {
446 if ( $i == DB_MASTER
) {
447 $i = $this->getWriterIndex();
448 } elseif ( !is_array( $groups ) ) {
449 $groupIndex = $this->getReaderIndex( $groups, $wiki );
450 if ( $groupIndex !== false ) {
451 $serverName = $this->getServerName( $groupIndex );
452 wfDebug( __METHOD__
.": using server $serverName for group $groups\n" );
456 foreach ( $groups as $group ) {
457 $groupIndex = $this->getReaderIndex( $group, $wiki );
458 if ( $groupIndex !== false ) {
459 $serverName = $this->getServerName( $groupIndex );
460 wfDebug( __METHOD__
.": using server $serverName for group $group\n" );
467 # Operation-based index
468 if ( $i == DB_SLAVE
) {
469 $i = $this->getReaderIndex( false, $wiki );
470 # Couldn't find a working server in getReaderIndex()?
471 if ( $i === false ) {
472 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
473 $this->reportConnectionError( $this->mErrorConnection
);
474 wfProfileOut( __METHOD__
);
479 # Now we have an explicit index into the servers array
480 $conn = $this->openConnection( $i, $wiki );
482 $this->reportConnectionError( $this->mErrorConnection
);
485 wfProfileOut( __METHOD__
);
490 * Mark a foreign connection as being available for reuse under a different
491 * DB name or prefix. This mechanism is reference-counted, and must be called
492 * the same number of times as getConnection() to work.
494 * @param DatabaseBase $conn
496 public function reuseConnection( $conn ) {
497 $serverIndex = $conn->getLBInfo('serverIndex');
498 $refCount = $conn->getLBInfo('foreignPoolRefCount');
499 $dbName = $conn->getDBname();
500 $prefix = $conn->tablePrefix();
501 if ( strval( $prefix ) !== '' ) {
502 $wiki = "$dbName-$prefix";
506 if ( $serverIndex === null ||
$refCount === null ) {
507 wfDebug( __METHOD__
.": this connection was not opened as a foreign connection\n" );
509 * This can happen in code like:
510 * foreach ( $dbs as $db ) {
511 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
513 * $lb->reuseConnection( $conn );
515 * When a connection to the local DB is opened in this way, reuseConnection()
520 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
521 throw new MWException( __METHOD__
.": connection not found, has the connection been freed already?" );
523 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
524 if ( $refCount <= 0 ) {
525 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
526 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
527 wfDebug( __METHOD__
.": freed connection $serverIndex/$wiki\n" );
529 wfDebug( __METHOD__
.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
534 * Open a connection to the server given by the specified index
535 * Index must be an actual index into the array.
536 * If the server is already open, returns it.
538 * On error, returns false, and the connection which caused the
539 * error will be available via $this->mErrorConnection.
541 * @param $i Integer server index
542 * @param $wiki String wiki ID to open
543 * @return DatabaseBase
547 function openConnection( $i, $wiki = false ) {
548 wfProfileIn( __METHOD__
);
549 if ( $wiki !== false ) {
550 $conn = $this->openForeignConnection( $i, $wiki );
551 wfProfileOut( __METHOD__
);
554 if ( isset( $this->mConns
['local'][$i][0] ) ) {
555 $conn = $this->mConns
['local'][$i][0];
557 $server = $this->mServers
[$i];
558 $server['serverIndex'] = $i;
559 $conn = $this->reallyOpenConnection( $server, false );
560 if ( $conn->isOpen() ) {
561 $this->mConns
['local'][$i][0] = $conn;
563 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
564 $this->mErrorConnection
= $conn;
568 wfProfileOut( __METHOD__
);
573 * Open a connection to a foreign DB, or return one if it is already open.
575 * Increments a reference count on the returned connection which locks the
576 * connection to the requested wiki. This reference count can be
577 * decremented by calling reuseConnection().
579 * If a connection is open to the appropriate server already, but with the wrong
580 * database, it will be switched to the right database and returned, as long as
581 * it has been freed first with reuseConnection().
583 * On error, returns false, and the connection which caused the
584 * error will be available via $this->mErrorConnection.
586 * @param $i Integer: server index
587 * @param $wiki String: wiki ID to open
588 * @return DatabaseBase
590 function openForeignConnection( $i, $wiki ) {
591 wfProfileIn(__METHOD__
);
592 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
593 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
594 // Reuse an already-used connection
595 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
596 wfDebug( __METHOD__
.": reusing connection $i/$wiki\n" );
597 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
598 // Reuse a free connection for the same wiki
599 $conn = $this->mConns
['foreignFree'][$i][$wiki];
600 unset( $this->mConns
['foreignFree'][$i][$wiki] );
601 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
602 wfDebug( __METHOD__
.": reusing free connection $i/$wiki\n" );
603 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
604 // Reuse a connection from another wiki
605 $conn = reset( $this->mConns
['foreignFree'][$i] );
606 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
608 if ( !$conn->selectDB( $dbName ) ) {
609 $this->mLastError
= "Error selecting database $dbName on server " .
610 $conn->getServer() . " from client host " . wfHostname() . "\n";
611 $this->mErrorConnection
= $conn;
614 $conn->tablePrefix( $prefix );
615 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
616 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
617 wfDebug( __METHOD__
.": reusing free connection from $oldWiki for $wiki\n" );
620 // Open a new connection
621 $server = $this->mServers
[$i];
622 $server['serverIndex'] = $i;
623 $server['foreignPoolRefCount'] = 0;
624 $conn = $this->reallyOpenConnection( $server, $dbName );
625 if ( !$conn->isOpen() ) {
626 wfDebug( __METHOD__
.": error opening connection for $i/$wiki\n" );
627 $this->mErrorConnection
= $conn;
630 $conn->tablePrefix( $prefix );
631 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
632 wfDebug( __METHOD__
.": opened new connection for $i/$wiki\n" );
636 // Increment reference count
638 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
639 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
641 wfProfileOut(__METHOD__
);
646 * Test if the specified index represents an open connection
648 * @param $index Integer: server index
652 function isOpen( $index ) {
653 if( !is_integer( $index ) ) {
656 return (bool)$this->getAnyOpenConnection( $index );
660 * Really opens a connection. Uncached.
661 * Returns a Database object whether or not the connection was successful.
664 * @return DatabaseBase
666 function reallyOpenConnection( $server, $dbNameOverride = false ) {
667 if( !is_array( $server ) ) {
668 throw new MWException( 'You must update your load-balancing configuration. ' .
669 'See DefaultSettings.php entry for $wgDBservers.' );
672 $host = $server['host'];
673 $dbname = $server['dbname'];
675 if ( $dbNameOverride !== false ) {
676 $server['dbname'] = $dbname = $dbNameOverride;
680 wfDebug( "Connecting to $host $dbname...\n" );
681 $db = DatabaseBase
::factory( $server['type'], $server );
682 if ( $db->isOpen() ) {
683 wfDebug( "Connected to $host $dbname.\n" );
685 wfDebug( "Connection failed to $host $dbname.\n" );
687 $db->setLBInfo( $server );
688 if ( isset( $server['fakeSlaveLag'] ) ) {
689 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
691 if ( isset( $server['fakeMaster'] ) ) {
692 $db->setFakeMaster( true );
697 function reportConnectionError( &$conn ) {
698 wfProfileIn( __METHOD__
);
700 if ( !is_object( $conn ) ) {
701 // No last connection, probably due to all servers being too busy
702 wfLogDBError( "LB failure with no last connection\n" );
703 $conn = new Database
;
704 // If all servers were busy, mLastError will contain something sensible
705 throw new DBConnectionError( $conn, $this->mLastError
);
707 $server = $conn->getProperty( 'mServer' );
708 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
709 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
711 wfProfileOut( __METHOD__
);
714 function getWriterIndex() {
719 * Returns true if the specified index is a valid server index
723 function haveIndex( $i ) {
724 return array_key_exists( $i, $this->mServers
);
728 * Returns true if the specified index is valid and has non-zero load
732 function isNonZeroLoad( $i ) {
733 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
737 * Get the number of defined servers (not the number of open connections)
741 function getServerCount() {
742 return count( $this->mServers
);
746 * Get the host name or IP address of the server with the specified index
747 * Prefer a readable name if available.
749 function getServerName( $i ) {
750 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
751 return $this->mServers
[$i]['hostName'];
752 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
753 return $this->mServers
[$i]['host'];
760 * Return the server info structure for a given index, or false if the index is invalid.
762 function getServerInfo( $i ) {
763 if ( isset( $this->mServers
[$i] ) ) {
764 return $this->mServers
[$i];
771 * Sets the server info structure for the given index. Entry at index $i is created if it doesn't exist
773 function setServerInfo( $i, $serverInfo ) {
774 $this->mServers
[$i] = $serverInfo;
778 * Get the current master position for chronology control purposes
781 function getMasterPos() {
782 # If this entire request was served from a slave without opening a connection to the
783 # master (however unlikely that may be), then we can fetch the position from the slave.
784 $masterConn = $this->getAnyOpenConnection( 0 );
785 if ( !$masterConn ) {
786 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
787 $conn = $this->getAnyOpenConnection( $i );
789 wfDebug( "Master pos fetched from slave\n" );
790 return $conn->getSlavePos();
794 wfDebug( "Master pos fetched from master\n" );
795 return $masterConn->getMasterPos();
801 * Close all open connections
803 function closeAll() {
804 foreach ( $this->mConns
as $conns2 ) {
805 foreach ( $conns2 as $conns3 ) {
806 foreach ( $conns3 as $conn ) {
811 $this->mConns
= array(
813 'foreignFree' => array(),
814 'foreignUsed' => array(),
819 * Deprecated function, typo in function name
821 * @deprecated in 1.18
823 function closeConnecton( $conn ) {
824 $this->closeConnection( $conn );
829 * Using this function makes sure the LoadBalancer knows the connection is closed.
830 * If you use $conn->close() directly, the load balancer won't update its state.
834 function closeConnection( $conn ) {
836 foreach ( $this->mConns
as $i1 => $conns2 ) {
837 foreach ( $conns2 as $i2 => $conns3 ) {
838 foreach ( $conns3 as $i3 => $candidateConn ) {
839 if ( $conn === $candidateConn ) {
841 unset( $this->mConns
[$i1][$i2][$i3] );
854 * Commit transactions on all open connections
856 function commitAll() {
857 foreach ( $this->mConns
as $conns2 ) {
858 foreach ( $conns2 as $conns3 ) {
859 foreach ( $conns3 as $conn ) {
867 * Issue COMMIT only on master, only if queries were done on connection
869 function commitMasterChanges() {
870 // Always 0, but who knows.. :)
871 $masterIndex = $this->getWriterIndex();
872 foreach ( $this->mConns
as $conns2 ) {
873 if ( empty( $conns2[$masterIndex] ) ) {
876 foreach ( $conns2[$masterIndex] as $conn ) {
877 if ( $conn->doneWrites() ) {
884 function waitTimeout( $value = null ) {
885 return wfSetVar( $this->mWaitTimeout
, $value );
888 function getLaggedSlaveMode() {
889 return $this->mLaggedSlaveMode
;
892 /* Disables/enables lag checks */
893 function allowLagged( $mode = null ) {
894 if ( $mode === null) {
895 return $this->mAllowLagged
;
897 $this->mAllowLagged
= $mode;
902 foreach ( $this->mConns
as $conns2 ) {
903 foreach ( $conns2 as $conns3 ) {
904 foreach ( $conns3 as $conn ) {
905 if ( !$conn->ping() ) {
915 * Call a function with each open connection object
917 function forEachOpenConnection( $callback, $params = array() ) {
918 foreach ( $this->mConns
as $conns2 ) {
919 foreach ( $conns2 as $conns3 ) {
920 foreach ( $conns3 as $conn ) {
921 $mergedParams = array_merge( array( $conn ), $params );
922 call_user_func_array( $callback, $mergedParams );
929 * Get the hostname and lag time of the most-lagged slave.
930 * This is useful for maintenance scripts that need to throttle their updates.
931 * May attempt to open connections to slaves on the default DB.
932 * @param $wiki string Wiki ID, or false for the default database
934 * @return array ( host, max lag, index of max lagged host )
936 function getMaxLag( $wiki = false ) {
940 foreach ( $this->mServers
as $i => $conn ) {
942 if ( $wiki === false ) {
943 $conn = $this->getAnyOpenConnection( $i );
946 $conn = $this->openConnection( $i, $wiki );
951 $lag = $conn->getLag();
952 if ( $lag > $maxLag ) {
954 $host = $this->mServers
[$i]['host'];
958 return array( $host, $maxLag, $maxIndex );
962 * Get lag time for each server
963 * Results are cached for a short time in memcached, and indefinitely in the process cache
969 function getLagTimes( $wiki = false ) {
971 if ( isset( $this->mLagTimes
) ) {
972 return $this->mLagTimes
;
974 # No, send the request to the load monitor
975 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
976 return $this->mLagTimes
;
980 * Clear the cache for getLagTimes
982 function clearLagTimeCache() {
983 $this->mLagTimes
= null;