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
96 function parentInfo( $x = null ) {
97 return wfSetVar( $this->mParentInfo
, $x );
101 * Given an array of non-normalised probabilities, this function will select
102 * an element and return the appropriate key
104 * @param $weights array
108 function pickRandom( $weights ) {
109 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
113 $sum = array_sum( $weights );
115 # No loads on any of them
116 # In previous versions, this triggered an unweighted random selection,
117 # but this feature has been removed as of April 2006 to allow for strict
118 # separation of query groups.
121 $max = mt_getrandmax();
122 $rand = mt_rand( 0, $max ) / $max * $sum;
125 foreach ( $weights as $i => $w ) {
127 if ( $sum >= $rand ) {
135 * @param $loads array
137 * @return bool|int|string
139 function getRandomNonLagged( $loads, $wiki = false ) {
140 # Unset excessively lagged servers
141 $lags = $this->getLagTimes( $wiki );
142 foreach ( $lags as $i => $lag ) {
144 if ( $lag === false ) {
145 wfDebugLog( 'replication', "Server #$i is not replicating\n" );
147 } elseif ( isset( $this->mServers
[$i]['max lag'] ) && $lag > $this->mServers
[$i]['max lag'] ) {
148 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)\n" );
154 # Find out if all the slaves with non-zero load are lagged
156 foreach ( $loads as $load ) {
160 # No appropriate DB servers except maybe the master and some slaves with zero load
161 # Do NOT use the master
162 # Instead, this function will return false, triggering read-only mode,
163 # and a lagged slave will be used instead.
167 if ( count( $loads ) == 0 ) {
171 #wfDebugLog( 'connect', var_export( $loads, true ) );
173 # Return a random representative of the remainder
174 return $this->pickRandom( $loads );
178 * Get the index of the reader connection, which may be a slave
179 * This takes into account load ratios and lag times. It should
180 * always return a consistent index during a given invocation
182 * Side effect: opens connections to databases
185 * @return bool|int|string
187 function getReaderIndex( $group = false, $wiki = false ) {
188 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
190 # @todo FIXME: For now, only go through all this for mysql databases
191 if ($wgDBtype != 'mysql') {
192 return $this->getWriterIndex();
195 if ( count( $this->mServers
) == 1 ) {
196 # Skip the load balancing if there's only one server
198 } elseif ( $group === false and $this->mReadIndex
>= 0 ) {
199 # Shortcut if generic reader exists already
200 return $this->mReadIndex
;
203 wfProfileIn( __METHOD__
);
207 # convert from seconds to microseconds
208 $timeout = $wgDBClusterTimeout * 1e6
;
210 # Find the relevant load array
211 if ( $group !== false ) {
212 if ( isset( $this->mGroupLoads
[$group] ) ) {
213 $nonErrorLoads = $this->mGroupLoads
[$group];
215 # No loads for this group, return false and the caller can use some other group
216 wfDebug( __METHOD__
.": no loads for group $group\n" );
217 wfProfileOut( __METHOD__
);
221 $nonErrorLoads = $this->mLoads
;
224 if ( !$nonErrorLoads ) {
225 throw new MWException( "Empty server array given to LoadBalancer" );
228 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
229 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
231 $laggedSlaveMode = false;
233 # First try quickly looking through the available servers for a server that
236 $totalThreadsConnected = 0;
237 $overloadedServers = 0;
238 $currentLoads = $nonErrorLoads;
239 while ( count( $currentLoads ) ) {
240 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
241 $i = $this->pickRandom( $currentLoads );
243 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
244 if ( $i === false && count( $currentLoads ) != 0 ) {
245 # All slaves lagged. Switch to read-only mode
246 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode\n" );
247 $wgReadOnly = 'The database has been automatically locked ' .
248 'while the slave database servers catch up to the master';
249 $i = $this->pickRandom( $currentLoads );
250 $laggedSlaveMode = true;
254 if ( $i === false ) {
255 # pickRandom() returned false
256 # This is permanent and means the configuration or the load monitor
257 # wants us to return false.
258 wfDebugLog( 'connect', __METHOD__
.": pickRandom() returned false\n" );
259 wfProfileOut( __METHOD__
);
263 wfDebugLog( 'connect', __METHOD__
.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
264 $conn = $this->openConnection( $i, $wiki );
267 wfDebugLog( 'connect', __METHOD__
.": Failed connecting to $i/$wiki\n" );
268 unset( $nonErrorLoads[$i] );
269 unset( $currentLoads[$i] );
273 // Perform post-connection backoff
274 $threshold = isset( $this->mServers
[$i]['max threads'] )
275 ?
$this->mServers
[$i]['max threads'] : false;
276 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
278 // Decrement reference counter, we are finished with this connection.
279 // It will be incremented for the caller later.
280 if ( $wiki !== false ) {
281 $this->reuseConnection( $conn );
285 # Post-connection overload, don't use this server for now
286 $totalThreadsConnected +
= $backoff;
287 $overloadedServers++
;
288 unset( $currentLoads[$i] );
295 # No server found yet
298 # If all servers were down, quit now
299 if ( !count( $nonErrorLoads ) ) {
300 wfDebugLog( 'connect', "All servers down\n" );
304 # Some servers must have been overloaded
305 if ( $overloadedServers == 0 ) {
306 throw new MWException( __METHOD__
.": unexpectedly found no overloaded servers" );
308 # Back off for a while
309 # Scale the sleep time by the number of connected threads, to produce a
310 # roughly constant global poll rate
311 $avgThreads = $totalThreadsConnected / $overloadedServers;
312 $totalElapsed +
= $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
313 } while ( $totalElapsed < $timeout );
315 if ( $totalElapsed >= $timeout ) {
316 wfDebugLog( 'connect', "All servers busy\n" );
317 $this->mErrorConnection
= false;
318 $this->mLastError
= 'All servers busy';
321 if ( $i !== false ) {
322 # Slave connection successful
323 # Wait for the session master pos for a short time
324 if ( $this->mWaitForPos
&& $i > 0 ) {
325 if ( !$this->doWait( $i ) ) {
326 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
329 if ( $this->mReadIndex
<=0 && $this->mLoads
[$i]>0 && $i !== false ) {
330 $this->mReadIndex
= $i;
333 wfProfileOut( __METHOD__
);
338 * Wait for a specified number of microseconds, and return the period waited
342 function sleep( $t ) {
343 wfProfileIn( __METHOD__
);
344 wfDebug( __METHOD__
.": waiting $t us\n" );
346 wfProfileOut( __METHOD__
);
351 * Set the master wait position
352 * If a DB_SLAVE connection has been opened already, waits
353 * Otherwise sets a variable telling it to wait if such a connection is opened
356 public function waitFor( $pos ) {
357 wfProfileIn( __METHOD__
);
358 $this->mWaitForPos
= $pos;
359 $i = $this->mReadIndex
;
362 if ( !$this->doWait( $i ) ) {
363 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
364 $this->mLaggedSlaveMode
= true;
367 wfProfileOut( __METHOD__
);
371 * Set the master wait position and wait for ALL slaves to catch up to it
374 public function waitForAll( $pos ) {
375 wfProfileIn( __METHOD__
);
376 $this->mWaitForPos
= $pos;
377 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
378 $this->doWait( $i , true );
380 wfProfileOut( __METHOD__
);
384 * Get any open connection to a given server index, local or foreign
385 * Returns false if there is no connection open
388 * @return DatabaseBase|bool False on failure
390 function getAnyOpenConnection( $i ) {
391 foreach ( $this->mConns
as $conns ) {
392 if ( !empty( $conns[$i] ) ) {
393 return reset( $conns[$i] );
400 * Wait for a given slave to catch up to the master pos stored in $this
405 function doWait( $index, $open = false ) {
406 # Find a connection to wait on
407 $conn = $this->getAnyOpenConnection( $index );
410 wfDebug( __METHOD__
. ": no connection open\n" );
413 $conn = $this->openConnection( $index );
415 wfDebug( __METHOD__
. ": failed to open connection\n" );
421 wfDebug( __METHOD__
.": Waiting for slave #$index to catch up...\n" );
422 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
424 if ( $result == -1 ||
is_null( $result ) ) {
425 # Timed out waiting for slave, use master instead
426 wfDebug( __METHOD__
.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
429 wfDebug( __METHOD__
.": Done\n" );
435 * Get a connection by index
436 * This is the main entry point for this class.
438 * @param $i Integer: server index
439 * @param $groups Array: query groups
440 * @param $wiki String: wiki ID
442 * @return DatabaseBase
444 public function &getConnection( $i, $groups = array(), $wiki = false ) {
445 wfProfileIn( __METHOD__
);
447 if ( $i == DB_LAST
) {
448 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with deprecated server index DB_LAST' );
449 } elseif ( $i === null ||
$i === false ) {
450 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with invalid server index' );
453 if ( $wiki === wfWikiID() ) {
458 if ( $i == DB_MASTER
) {
459 $i = $this->getWriterIndex();
460 } elseif ( !is_array( $groups ) ) {
461 $groupIndex = $this->getReaderIndex( $groups, $wiki );
462 if ( $groupIndex !== false ) {
463 $serverName = $this->getServerName( $groupIndex );
464 wfDebug( __METHOD__
.": using server $serverName for group $groups\n" );
468 foreach ( $groups as $group ) {
469 $groupIndex = $this->getReaderIndex( $group, $wiki );
470 if ( $groupIndex !== false ) {
471 $serverName = $this->getServerName( $groupIndex );
472 wfDebug( __METHOD__
.": using server $serverName for group $group\n" );
479 # Operation-based index
480 if ( $i == DB_SLAVE
) {
481 $i = $this->getReaderIndex( false, $wiki );
482 # Couldn't find a working server in getReaderIndex()?
483 if ( $i === false ) {
484 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
485 $this->reportConnectionError( $this->mErrorConnection
);
486 wfProfileOut( __METHOD__
);
491 # Now we have an explicit index into the servers array
492 $conn = $this->openConnection( $i, $wiki );
494 $this->reportConnectionError( $this->mErrorConnection
);
497 wfProfileOut( __METHOD__
);
502 * Mark a foreign connection as being available for reuse under a different
503 * DB name or prefix. This mechanism is reference-counted, and must be called
504 * the same number of times as getConnection() to work.
506 * @param DatabaseBase $conn
508 public function reuseConnection( $conn ) {
509 $serverIndex = $conn->getLBInfo('serverIndex');
510 $refCount = $conn->getLBInfo('foreignPoolRefCount');
511 $dbName = $conn->getDBname();
512 $prefix = $conn->tablePrefix();
513 if ( strval( $prefix ) !== '' ) {
514 $wiki = "$dbName-$prefix";
518 if ( $serverIndex === null ||
$refCount === null ) {
519 wfDebug( __METHOD__
.": this connection was not opened as a foreign connection\n" );
521 * This can happen in code like:
522 * foreach ( $dbs as $db ) {
523 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
525 * $lb->reuseConnection( $conn );
527 * When a connection to the local DB is opened in this way, reuseConnection()
532 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
533 throw new MWException( __METHOD__
.": connection not found, has the connection been freed already?" );
535 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
536 if ( $refCount <= 0 ) {
537 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
538 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
539 wfDebug( __METHOD__
.": freed connection $serverIndex/$wiki\n" );
541 wfDebug( __METHOD__
.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
546 * Open a connection to the server given by the specified index
547 * Index must be an actual index into the array.
548 * If the server is already open, returns it.
550 * On error, returns false, and the connection which caused the
551 * error will be available via $this->mErrorConnection.
553 * @param $i Integer server index
554 * @param $wiki String wiki ID to open
555 * @return DatabaseBase
559 function openConnection( $i, $wiki = false ) {
560 wfProfileIn( __METHOD__
);
561 if ( $wiki !== false ) {
562 $conn = $this->openForeignConnection( $i, $wiki );
563 wfProfileOut( __METHOD__
);
566 if ( isset( $this->mConns
['local'][$i][0] ) ) {
567 $conn = $this->mConns
['local'][$i][0];
569 $server = $this->mServers
[$i];
570 $server['serverIndex'] = $i;
571 $conn = $this->reallyOpenConnection( $server, false );
572 if ( $conn->isOpen() ) {
573 $this->mConns
['local'][$i][0] = $conn;
575 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
576 $this->mErrorConnection
= $conn;
580 wfProfileOut( __METHOD__
);
585 * Open a connection to a foreign DB, or return one if it is already open.
587 * Increments a reference count on the returned connection which locks the
588 * connection to the requested wiki. This reference count can be
589 * decremented by calling reuseConnection().
591 * If a connection is open to the appropriate server already, but with the wrong
592 * database, it will be switched to the right database and returned, as long as
593 * it has been freed first with reuseConnection().
595 * On error, returns false, and the connection which caused the
596 * error will be available via $this->mErrorConnection.
598 * @param $i Integer: server index
599 * @param $wiki String: wiki ID to open
600 * @return DatabaseBase
602 function openForeignConnection( $i, $wiki ) {
603 wfProfileIn(__METHOD__
);
604 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
605 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
606 // Reuse an already-used connection
607 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
608 wfDebug( __METHOD__
.": reusing connection $i/$wiki\n" );
609 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
610 // Reuse a free connection for the same wiki
611 $conn = $this->mConns
['foreignFree'][$i][$wiki];
612 unset( $this->mConns
['foreignFree'][$i][$wiki] );
613 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
614 wfDebug( __METHOD__
.": reusing free connection $i/$wiki\n" );
615 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
616 // Reuse a connection from another wiki
617 $conn = reset( $this->mConns
['foreignFree'][$i] );
618 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
620 if ( !$conn->selectDB( $dbName ) ) {
621 $this->mLastError
= "Error selecting database $dbName on server " .
622 $conn->getServer() . " from client host " . wfHostname() . "\n";
623 $this->mErrorConnection
= $conn;
626 $conn->tablePrefix( $prefix );
627 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
628 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
629 wfDebug( __METHOD__
.": reusing free connection from $oldWiki for $wiki\n" );
632 // Open a new connection
633 $server = $this->mServers
[$i];
634 $server['serverIndex'] = $i;
635 $server['foreignPoolRefCount'] = 0;
636 $conn = $this->reallyOpenConnection( $server, $dbName );
637 if ( !$conn->isOpen() ) {
638 wfDebug( __METHOD__
.": error opening connection for $i/$wiki\n" );
639 $this->mErrorConnection
= $conn;
642 $conn->tablePrefix( $prefix );
643 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
644 wfDebug( __METHOD__
.": opened new connection for $i/$wiki\n" );
648 // Increment reference count
650 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
651 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
653 wfProfileOut(__METHOD__
);
658 * Test if the specified index represents an open connection
660 * @param $index Integer: server index
664 function isOpen( $index ) {
665 if( !is_integer( $index ) ) {
668 return (bool)$this->getAnyOpenConnection( $index );
672 * Really opens a connection. Uncached.
673 * Returns a Database object whether or not the connection was successful.
677 * @param $dbNameOverride bool
678 * @return DatabaseBase
680 function reallyOpenConnection( $server, $dbNameOverride = false ) {
681 if( !is_array( $server ) ) {
682 throw new MWException( 'You must update your load-balancing configuration. ' .
683 'See DefaultSettings.php entry for $wgDBservers.' );
686 $host = $server['host'];
687 $dbname = $server['dbname'];
689 if ( $dbNameOverride !== false ) {
690 $server['dbname'] = $dbname = $dbNameOverride;
694 wfDebug( "Connecting to $host $dbname...\n" );
696 $db = DatabaseBase
::factory( $server['type'], $server );
697 } catch ( DBConnectionError
$e ) {
698 // FIXME: This is probably the ugliest thing I have ever done to
699 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
703 if ( $db->isOpen() ) {
704 wfDebug( "Connected to $host $dbname.\n" );
706 wfDebug( "Connection failed to $host $dbname.\n" );
708 $db->setLBInfo( $server );
709 if ( isset( $server['fakeSlaveLag'] ) ) {
710 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
712 if ( isset( $server['fakeMaster'] ) ) {
713 $db->setFakeMaster( true );
720 * @throws DBConnectionError
722 function reportConnectionError( &$conn ) {
723 wfProfileIn( __METHOD__
);
725 if ( !is_object( $conn ) ) {
726 // No last connection, probably due to all servers being too busy
727 wfLogDBError( "LB failure with no last connection. Connection error: {$this->mLastError}\n" );
728 $conn = new Database
;
729 // If all servers were busy, mLastError will contain something sensible
730 throw new DBConnectionError( $conn, $this->mLastError
);
732 $server = $conn->getProperty( 'mServer' );
733 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
734 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
736 wfProfileOut( __METHOD__
);
742 function getWriterIndex() {
747 * Returns true if the specified index is a valid server index
752 function haveIndex( $i ) {
753 return array_key_exists( $i, $this->mServers
);
757 * Returns true if the specified index is valid and has non-zero load
762 function isNonZeroLoad( $i ) {
763 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
767 * Get the number of defined servers (not the number of open connections)
771 function getServerCount() {
772 return count( $this->mServers
);
776 * Get the host name or IP address of the server with the specified index
777 * Prefer a readable name if available.
781 function getServerName( $i ) {
782 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
783 return $this->mServers
[$i]['hostName'];
784 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
785 return $this->mServers
[$i]['host'];
792 * Return the server info structure for a given index, or false if the index is invalid.
796 function getServerInfo( $i ) {
797 if ( isset( $this->mServers
[$i] ) ) {
798 return $this->mServers
[$i];
805 * Sets the server info structure for the given index. Entry at index $i is created if it doesn't exist
809 function setServerInfo( $i, $serverInfo ) {
810 $this->mServers
[$i] = $serverInfo;
814 * Get the current master position for chronology control purposes
817 function getMasterPos() {
818 # If this entire request was served from a slave without opening a connection to the
819 # master (however unlikely that may be), then we can fetch the position from the slave.
820 $masterConn = $this->getAnyOpenConnection( 0 );
821 if ( !$masterConn ) {
822 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
823 $conn = $this->getAnyOpenConnection( $i );
825 wfDebug( "Master pos fetched from slave\n" );
826 return $conn->getSlavePos();
830 wfDebug( "Master pos fetched from master\n" );
831 return $masterConn->getMasterPos();
837 * Close all open connections
839 function closeAll() {
840 foreach ( $this->mConns
as $conns2 ) {
841 foreach ( $conns2 as $conns3 ) {
842 foreach ( $conns3 as $conn ) {
847 $this->mConns
= array(
849 'foreignFree' => array(),
850 'foreignUsed' => array(),
855 * Deprecated function, typo in function name
857 * @deprecated in 1.18
860 function closeConnecton( $conn ) {
861 wfDeprecated( __METHOD__
, '1.18' );
862 $this->closeConnection( $conn );
867 * Using this function makes sure the LoadBalancer knows the connection is closed.
868 * If you use $conn->close() directly, the load balancer won't update its state.
869 * @param $conn DatabaseBase
871 function closeConnection( $conn ) {
873 foreach ( $this->mConns
as $i1 => $conns2 ) {
874 foreach ( $conns2 as $i2 => $conns3 ) {
875 foreach ( $conns3 as $i3 => $candidateConn ) {
876 if ( $conn === $candidateConn ) {
878 unset( $this->mConns
[$i1][$i2][$i3] );
891 * Commit transactions on all open connections
893 function commitAll() {
894 foreach ( $this->mConns
as $conns2 ) {
895 foreach ( $conns2 as $conns3 ) {
896 foreach ( $conns3 as $conn ) {
897 $conn->commit( __METHOD__
);
904 * Issue COMMIT only on master, only if queries were done on connection
906 function commitMasterChanges() {
907 // Always 0, but who knows.. :)
908 $masterIndex = $this->getWriterIndex();
909 foreach ( $this->mConns
as $conns2 ) {
910 if ( empty( $conns2[$masterIndex] ) ) {
913 foreach ( $conns2[$masterIndex] as $conn ) {
914 if ( $conn->doneWrites() ) {
915 $conn->commit( __METHOD__
);
925 function waitTimeout( $value = null ) {
926 return wfSetVar( $this->mWaitTimeout
, $value );
932 function getLaggedSlaveMode() {
933 return $this->mLaggedSlaveMode
;
937 * Disables/enables lag checks
941 function allowLagged( $mode = null ) {
942 if ( $mode === null) {
943 return $this->mAllowLagged
;
945 $this->mAllowLagged
= $mode;
953 foreach ( $this->mConns
as $conns2 ) {
954 foreach ( $conns2 as $conns3 ) {
955 foreach ( $conns3 as $conn ) {
956 if ( !$conn->ping() ) {
966 * Call a function with each open connection object
968 * @param array $params
970 function forEachOpenConnection( $callback, $params = array() ) {
971 foreach ( $this->mConns
as $conns2 ) {
972 foreach ( $conns2 as $conns3 ) {
973 foreach ( $conns3 as $conn ) {
974 $mergedParams = array_merge( array( $conn ), $params );
975 call_user_func_array( $callback, $mergedParams );
982 * Get the hostname and lag time of the most-lagged slave.
983 * This is useful for maintenance scripts that need to throttle their updates.
984 * May attempt to open connections to slaves on the default DB. If there is
985 * no lag, the maximum lag will be reported as -1.
987 * @param $wiki string Wiki ID, or false for the default database
989 * @return array ( host, max lag, index of max lagged host )
991 function getMaxLag( $wiki = false ) {
995 if ( $this->getServerCount() > 1 ) { // no replication = no lag
996 foreach ( $this->mServers
as $i => $conn ) {
998 if ( $wiki === false ) {
999 $conn = $this->getAnyOpenConnection( $i );
1002 $conn = $this->openConnection( $i, $wiki );
1007 $lag = $conn->getLag();
1008 if ( $lag > $maxLag ) {
1010 $host = $this->mServers
[$i]['host'];
1015 return array( $host, $maxLag, $maxIndex );
1019 * Get lag time for each server
1020 * Results are cached for a short time in memcached, and indefinitely in the process cache
1026 function getLagTimes( $wiki = false ) {
1028 if ( isset( $this->mLagTimes
) ) {
1029 return $this->mLagTimes
;
1031 if ( $this->getServerCount() == 1 ) {
1033 $this->mLagTimes
= array( 0 => 0 );
1035 # Send the request to the load monitor
1036 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes(
1037 array_keys( $this->mServers
), $wiki );
1039 return $this->mLagTimes
;
1043 * Get the lag in seconds for a given connection, or zero if this load
1044 * balancer does not have replication enabled.
1046 * This should be used in preference to Database::getLag() in cases where
1047 * replication may not be in use, since there is no way to determine if
1048 * replication is in use at the connection level without running
1049 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1050 * function instead of Database::getLag() avoids a fatal error in this
1051 * case on many installations.
1053 * @param $conn DatabaseBase
1057 function safeGetLag( $conn ) {
1058 if ( $this->getServerCount() == 1 ) {
1061 return $conn->getLag();
1066 * Clear the cache for getLagTimes
1068 function clearLagTimeCache() {
1069 $this->mLagTimes
= null;