3 * Database load balancing.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * Database load balancing object
31 private $mServers, $mConns, $mLoads, $mGroupLoads;
32 private $mErrorConnection;
33 private $mReadIndex, $mAllowLagged;
34 private $mWaitForPos, $mWaitTimeout;
35 private $mLaggedSlaveMode, $mLastError = 'Unknown error';
36 private $mParentInfo, $mLagTimes;
37 private $mLoadMonitorClass, $mLoadMonitor;
40 * @param $params Array with keys:
41 * servers Required. Array of server info structures.
42 * masterWaitTimeout Replication lag wait timeout
43 * loadMonitor Name of a class used to fetch server lag and load.
46 function __construct( $params ) {
47 if ( !isset( $params['servers'] ) ) {
48 throw new MWException( __CLASS__
.': missing servers parameter' );
50 $this->mServers
= $params['servers'];
52 if ( isset( $params['waitTimeout'] ) ) {
53 $this->mWaitTimeout
= $params['waitTimeout'];
55 $this->mWaitTimeout
= 10;
58 $this->mReadIndex
= -1;
59 $this->mWriteIndex
= -1;
60 $this->mConns
= array(
62 'foreignUsed' => array(),
63 'foreignFree' => array() );
64 $this->mLoads
= array();
65 $this->mWaitForPos
= false;
66 $this->mLaggedSlaveMode
= false;
67 $this->mErrorConnection
= false;
68 $this->mAllowLagged
= false;
70 if ( isset( $params['loadMonitor'] ) ) {
71 $this->mLoadMonitorClass
= $params['loadMonitor'];
73 $master = reset( $params['servers'] );
74 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
75 $this->mLoadMonitorClass
= 'LoadMonitor_MySQL';
77 $this->mLoadMonitorClass
= 'LoadMonitor_Null';
81 foreach( $params['servers'] as $i => $server ) {
82 $this->mLoads
[$i] = $server['load'];
83 if ( isset( $server['groupLoads'] ) ) {
84 foreach ( $server['groupLoads'] as $group => $ratio ) {
85 if ( !isset( $this->mGroupLoads
[$group] ) ) {
86 $this->mGroupLoads
[$group] = array();
88 $this->mGroupLoads
[$group][$i] = $ratio;
95 * Get a LoadMonitor instance
99 function getLoadMonitor() {
100 if ( !isset( $this->mLoadMonitor
) ) {
101 $class = $this->mLoadMonitorClass
;
102 $this->mLoadMonitor
= new $class( $this );
104 return $this->mLoadMonitor
;
108 * Get or set arbitrary data used by the parent object, usually an LBFactory
112 function parentInfo( $x = null ) {
113 return wfSetVar( $this->mParentInfo
, $x );
117 * Given an array of non-normalised probabilities, this function will select
118 * an element and return the appropriate key
120 * @param $weights array
124 function pickRandom( $weights ) {
125 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
129 $sum = array_sum( $weights );
131 # No loads on any of them
132 # In previous versions, this triggered an unweighted random selection,
133 # but this feature has been removed as of April 2006 to allow for strict
134 # separation of query groups.
137 $max = mt_getrandmax();
138 $rand = mt_rand( 0, $max ) / $max * $sum;
141 foreach ( $weights as $i => $w ) {
143 if ( $sum >= $rand ) {
151 * @param $loads array
153 * @return bool|int|string
155 function getRandomNonLagged( $loads, $wiki = false ) {
156 # Unset excessively lagged servers
157 $lags = $this->getLagTimes( $wiki );
158 foreach ( $lags as $i => $lag ) {
160 if ( $lag === false ) {
161 wfDebugLog( 'replication', "Server #$i is not replicating\n" );
163 } elseif ( isset( $this->mServers
[$i]['max lag'] ) && $lag > $this->mServers
[$i]['max lag'] ) {
164 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)\n" );
170 # Find out if all the slaves with non-zero load are lagged
172 foreach ( $loads as $load ) {
176 # No appropriate DB servers except maybe the master and some slaves with zero load
177 # Do NOT use the master
178 # Instead, this function will return false, triggering read-only mode,
179 # and a lagged slave will be used instead.
183 if ( count( $loads ) == 0 ) {
187 #wfDebugLog( 'connect', var_export( $loads, true ) );
189 # Return a random representative of the remainder
190 return $this->pickRandom( $loads );
194 * Get the index of the reader connection, which may be a slave
195 * This takes into account load ratios and lag times. It should
196 * always return a consistent index during a given invocation
198 * Side effect: opens connections to databases
201 * @throws MWException
202 * @return bool|int|string
204 function getReaderIndex( $group = false, $wiki = false ) {
205 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
207 # @todo FIXME: For now, only go through all this for mysql databases
208 if ($wgDBtype != 'mysql') {
209 return $this->getWriterIndex();
212 if ( count( $this->mServers
) == 1 ) {
213 # Skip the load balancing if there's only one server
215 } elseif ( $group === false and $this->mReadIndex
>= 0 ) {
216 # Shortcut if generic reader exists already
217 return $this->mReadIndex
;
220 wfProfileIn( __METHOD__
);
224 # convert from seconds to microseconds
225 $timeout = $wgDBClusterTimeout * 1e6
;
227 # Find the relevant load array
228 if ( $group !== false ) {
229 if ( isset( $this->mGroupLoads
[$group] ) ) {
230 $nonErrorLoads = $this->mGroupLoads
[$group];
232 # No loads for this group, return false and the caller can use some other group
233 wfDebug( __METHOD__
.": no loads for group $group\n" );
234 wfProfileOut( __METHOD__
);
238 $nonErrorLoads = $this->mLoads
;
241 if ( !$nonErrorLoads ) {
242 throw new MWException( "Empty server array given to LoadBalancer" );
245 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
246 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
248 $laggedSlaveMode = false;
250 # First try quickly looking through the available servers for a server that
253 $totalThreadsConnected = 0;
254 $overloadedServers = 0;
255 $currentLoads = $nonErrorLoads;
256 while ( count( $currentLoads ) ) {
257 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
258 $i = $this->pickRandom( $currentLoads );
260 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
261 if ( $i === false && count( $currentLoads ) != 0 ) {
262 # All slaves lagged. Switch to read-only mode
263 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode\n" );
264 $wgReadOnly = 'The database has been automatically locked ' .
265 'while the slave database servers catch up to the master';
266 $i = $this->pickRandom( $currentLoads );
267 $laggedSlaveMode = true;
271 if ( $i === false ) {
272 # pickRandom() returned false
273 # This is permanent and means the configuration or the load monitor
274 # wants us to return false.
275 wfDebugLog( 'connect', __METHOD__
.": pickRandom() returned false\n" );
276 wfProfileOut( __METHOD__
);
280 wfDebugLog( 'connect', __METHOD__
.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
281 $conn = $this->openConnection( $i, $wiki );
284 wfDebugLog( 'connect', __METHOD__
.": Failed connecting to $i/$wiki\n" );
285 unset( $nonErrorLoads[$i] );
286 unset( $currentLoads[$i] );
290 // Perform post-connection backoff
291 $threshold = isset( $this->mServers
[$i]['max threads'] )
292 ?
$this->mServers
[$i]['max threads'] : false;
293 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
295 // Decrement reference counter, we are finished with this connection.
296 // It will be incremented for the caller later.
297 if ( $wiki !== false ) {
298 $this->reuseConnection( $conn );
302 # Post-connection overload, don't use this server for now
303 $totalThreadsConnected +
= $backoff;
304 $overloadedServers++
;
305 unset( $currentLoads[$i] );
312 # No server found yet
315 # If all servers were down, quit now
316 if ( !count( $nonErrorLoads ) ) {
317 wfDebugLog( 'connect', "All servers down\n" );
321 # Some servers must have been overloaded
322 if ( $overloadedServers == 0 ) {
323 throw new MWException( __METHOD__
.": unexpectedly found no overloaded servers" );
325 # Back off for a while
326 # Scale the sleep time by the number of connected threads, to produce a
327 # roughly constant global poll rate
328 $avgThreads = $totalThreadsConnected / $overloadedServers;
329 $totalElapsed +
= $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
330 } while ( $totalElapsed < $timeout );
332 if ( $totalElapsed >= $timeout ) {
333 wfDebugLog( 'connect', "All servers busy\n" );
334 $this->mErrorConnection
= false;
335 $this->mLastError
= 'All servers busy';
338 if ( $i !== false ) {
339 # Slave connection successful
340 # Wait for the session master pos for a short time
341 if ( $this->mWaitForPos
&& $i > 0 ) {
342 if ( !$this->doWait( $i ) ) {
343 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
346 if ( $this->mReadIndex
<=0 && $this->mLoads
[$i]>0 && $i !== false ) {
347 $this->mReadIndex
= $i;
350 wfProfileOut( __METHOD__
);
355 * Wait for a specified number of microseconds, and return the period waited
359 function sleep( $t ) {
360 wfProfileIn( __METHOD__
);
361 wfDebug( __METHOD__
.": waiting $t us\n" );
363 wfProfileOut( __METHOD__
);
368 * Set the master wait position
369 * If a DB_SLAVE connection has been opened already, waits
370 * Otherwise sets a variable telling it to wait if such a connection is opened
373 public function waitFor( $pos ) {
374 wfProfileIn( __METHOD__
);
375 $this->mWaitForPos
= $pos;
376 $i = $this->mReadIndex
;
379 if ( !$this->doWait( $i ) ) {
380 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
381 $this->mLaggedSlaveMode
= true;
384 wfProfileOut( __METHOD__
);
388 * Set the master wait position and wait for ALL slaves to catch up to it
391 public function waitForAll( $pos ) {
392 wfProfileIn( __METHOD__
);
393 $this->mWaitForPos
= $pos;
394 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
395 $this->doWait( $i , true );
397 wfProfileOut( __METHOD__
);
401 * Get any open connection to a given server index, local or foreign
402 * Returns false if there is no connection open
405 * @return DatabaseBase|bool False on failure
407 function getAnyOpenConnection( $i ) {
408 foreach ( $this->mConns
as $conns ) {
409 if ( !empty( $conns[$i] ) ) {
410 return reset( $conns[$i] );
417 * Wait for a given slave to catch up to the master pos stored in $this
422 function doWait( $index, $open = false ) {
423 # Find a connection to wait on
424 $conn = $this->getAnyOpenConnection( $index );
427 wfDebug( __METHOD__
. ": no connection open\n" );
430 $conn = $this->openConnection( $index );
432 wfDebug( __METHOD__
. ": failed to open connection\n" );
438 wfDebug( __METHOD__
.": Waiting for slave #$index to catch up...\n" );
439 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
441 if ( $result == -1 ||
is_null( $result ) ) {
442 # Timed out waiting for slave, use master instead
443 wfDebug( __METHOD__
.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
446 wfDebug( __METHOD__
.": Done\n" );
452 * Get a connection by index
453 * This is the main entry point for this class.
455 * @param $i Integer: server index
456 * @param $groups Array: query groups
457 * @param bool|string $wiki Wiki ID
459 * @throws MWException
460 * @return DatabaseBase
462 public function &getConnection( $i, $groups = array(), $wiki = false ) {
463 wfProfileIn( __METHOD__
);
465 if ( $i == DB_LAST
) {
466 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with deprecated server index DB_LAST' );
467 } elseif ( $i === null ||
$i === false ) {
468 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with invalid server index' );
471 if ( $wiki === wfWikiID() ) {
476 if ( $i == DB_MASTER
) {
477 $i = $this->getWriterIndex();
478 } elseif ( !is_array( $groups ) ) {
479 $groupIndex = $this->getReaderIndex( $groups, $wiki );
480 if ( $groupIndex !== false ) {
481 $serverName = $this->getServerName( $groupIndex );
482 wfDebug( __METHOD__
.": using server $serverName for group $groups\n" );
486 foreach ( $groups as $group ) {
487 $groupIndex = $this->getReaderIndex( $group, $wiki );
488 if ( $groupIndex !== false ) {
489 $serverName = $this->getServerName( $groupIndex );
490 wfDebug( __METHOD__
.": using server $serverName for group $group\n" );
497 # Operation-based index
498 if ( $i == DB_SLAVE
) {
499 $i = $this->getReaderIndex( false, $wiki );
500 # Couldn't find a working server in getReaderIndex()?
501 if ( $i === false ) {
502 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
503 wfProfileOut( __METHOD__
);
504 $this->reportConnectionError( $this->mErrorConnection
);
509 # Now we have an explicit index into the servers array
510 $conn = $this->openConnection( $i, $wiki );
512 wfProfileOut( __METHOD__
);
513 $this->reportConnectionError( $this->mErrorConnection
);
516 wfProfileOut( __METHOD__
);
521 * Mark a foreign connection as being available for reuse under a different
522 * DB name or prefix. This mechanism is reference-counted, and must be called
523 * the same number of times as getConnection() to work.
525 * @param DatabaseBase $conn
526 * @throws MWException
528 public function reuseConnection( $conn ) {
529 $serverIndex = $conn->getLBInfo('serverIndex');
530 $refCount = $conn->getLBInfo('foreignPoolRefCount');
531 $dbName = $conn->getDBname();
532 $prefix = $conn->tablePrefix();
533 if ( strval( $prefix ) !== '' ) {
534 $wiki = "$dbName-$prefix";
538 if ( $serverIndex === null ||
$refCount === null ) {
539 wfDebug( __METHOD__
.": this connection was not opened as a foreign connection\n" );
541 * This can happen in code like:
542 * foreach ( $dbs as $db ) {
543 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
545 * $lb->reuseConnection( $conn );
547 * When a connection to the local DB is opened in this way, reuseConnection()
552 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
553 throw new MWException( __METHOD__
.": connection not found, has the connection been freed already?" );
555 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
556 if ( $refCount <= 0 ) {
557 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
558 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
559 wfDebug( __METHOD__
.": freed connection $serverIndex/$wiki\n" );
561 wfDebug( __METHOD__
.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
566 * Open a connection to the server given by the specified index
567 * Index must be an actual index into the array.
568 * If the server is already open, returns it.
570 * On error, returns false, and the connection which caused the
571 * error will be available via $this->mErrorConnection.
573 * @param $i Integer server index
574 * @param $wiki String wiki ID to open
575 * @return DatabaseBase
579 function openConnection( $i, $wiki = false ) {
580 wfProfileIn( __METHOD__
);
581 if ( $wiki !== false ) {
582 $conn = $this->openForeignConnection( $i, $wiki );
583 wfProfileOut( __METHOD__
);
586 if ( isset( $this->mConns
['local'][$i][0] ) ) {
587 $conn = $this->mConns
['local'][$i][0];
589 $server = $this->mServers
[$i];
590 $server['serverIndex'] = $i;
591 $conn = $this->reallyOpenConnection( $server, false );
592 if ( $conn->isOpen() ) {
593 wfDebug( "Connected to database $i at {$this->mServers[$i]['host']}\n" );
594 $this->mConns
['local'][$i][0] = $conn;
596 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
597 $this->mErrorConnection
= $conn;
601 wfProfileOut( __METHOD__
);
606 * Open a connection to a foreign DB, or return one if it is already open.
608 * Increments a reference count on the returned connection which locks the
609 * connection to the requested wiki. This reference count can be
610 * decremented by calling reuseConnection().
612 * If a connection is open to the appropriate server already, but with the wrong
613 * database, it will be switched to the right database and returned, as long as
614 * it has been freed first with reuseConnection().
616 * On error, returns false, and the connection which caused the
617 * error will be available via $this->mErrorConnection.
619 * @param $i Integer: server index
620 * @param $wiki String: wiki ID to open
621 * @return DatabaseBase
623 function openForeignConnection( $i, $wiki ) {
624 wfProfileIn(__METHOD__
);
625 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
626 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
627 // Reuse an already-used connection
628 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
629 wfDebug( __METHOD__
.": reusing connection $i/$wiki\n" );
630 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
631 // Reuse a free connection for the same wiki
632 $conn = $this->mConns
['foreignFree'][$i][$wiki];
633 unset( $this->mConns
['foreignFree'][$i][$wiki] );
634 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
635 wfDebug( __METHOD__
.": reusing free connection $i/$wiki\n" );
636 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
637 // Reuse a connection from another wiki
638 $conn = reset( $this->mConns
['foreignFree'][$i] );
639 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
641 if ( !$conn->selectDB( $dbName ) ) {
642 $this->mLastError
= "Error selecting database $dbName on server " .
643 $conn->getServer() . " from client host " . wfHostname() . "\n";
644 $this->mErrorConnection
= $conn;
647 $conn->tablePrefix( $prefix );
648 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
649 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
650 wfDebug( __METHOD__
.": reusing free connection from $oldWiki for $wiki\n" );
653 // Open a new connection
654 $server = $this->mServers
[$i];
655 $server['serverIndex'] = $i;
656 $server['foreignPoolRefCount'] = 0;
657 $conn = $this->reallyOpenConnection( $server, $dbName );
658 if ( !$conn->isOpen() ) {
659 wfDebug( __METHOD__
.": error opening connection for $i/$wiki\n" );
660 $this->mErrorConnection
= $conn;
663 $conn->tablePrefix( $prefix );
664 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
665 wfDebug( __METHOD__
.": opened new connection for $i/$wiki\n" );
669 // Increment reference count
671 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
672 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
674 wfProfileOut(__METHOD__
);
679 * Test if the specified index represents an open connection
681 * @param $index Integer: server index
685 function isOpen( $index ) {
686 if( !is_integer( $index ) ) {
689 return (bool)$this->getAnyOpenConnection( $index );
693 * Really opens a connection. Uncached.
694 * Returns a Database object whether or not the connection was successful.
698 * @param $dbNameOverride bool
699 * @throws MWException
700 * @return DatabaseBase
702 function reallyOpenConnection( $server, $dbNameOverride = false ) {
703 if( !is_array( $server ) ) {
704 throw new MWException( 'You must update your load-balancing configuration. ' .
705 'See DefaultSettings.php entry for $wgDBservers.' );
708 $host = $server['host'];
709 $dbname = $server['dbname'];
711 if ( $dbNameOverride !== false ) {
712 $server['dbname'] = $dbname = $dbNameOverride;
717 $db = DatabaseBase
::factory( $server['type'], $server );
718 } catch ( DBConnectionError
$e ) {
719 // FIXME: This is probably the ugliest thing I have ever done to
720 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
724 $db->setLBInfo( $server );
725 if ( isset( $server['fakeSlaveLag'] ) ) {
726 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
728 if ( isset( $server['fakeMaster'] ) ) {
729 $db->setFakeMaster( true );
736 * @throws DBConnectionError
738 function reportConnectionError( &$conn ) {
739 if ( !is_object( $conn ) ) {
740 // No last connection, probably due to all servers being too busy
741 wfLogDBError( "LB failure with no last connection. Connection error: {$this->mLastError}\n" );
742 $conn = new Database
;
743 // If all servers were busy, mLastError will contain something sensible
744 throw new DBConnectionError( $conn, $this->mLastError
);
746 $server = $conn->getProperty( 'mServer' );
747 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
748 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
755 function getWriterIndex() {
760 * Returns true if the specified index is a valid server index
765 function haveIndex( $i ) {
766 return array_key_exists( $i, $this->mServers
);
770 * Returns true if the specified index is valid and has non-zero load
775 function isNonZeroLoad( $i ) {
776 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
780 * Get the number of defined servers (not the number of open connections)
784 function getServerCount() {
785 return count( $this->mServers
);
789 * Get the host name or IP address of the server with the specified index
790 * Prefer a readable name if available.
794 function getServerName( $i ) {
795 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
796 return $this->mServers
[$i]['hostName'];
797 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
798 return $this->mServers
[$i]['host'];
805 * Return the server info structure for a given index, or false if the index is invalid.
809 function getServerInfo( $i ) {
810 if ( isset( $this->mServers
[$i] ) ) {
811 return $this->mServers
[$i];
818 * Sets the server info structure for the given index. Entry at index $i is created if it doesn't exist
822 function setServerInfo( $i, $serverInfo ) {
823 $this->mServers
[$i] = $serverInfo;
827 * Get the current master position for chronology control purposes
830 function getMasterPos() {
831 # If this entire request was served from a slave without opening a connection to the
832 # master (however unlikely that may be), then we can fetch the position from the slave.
833 $masterConn = $this->getAnyOpenConnection( 0 );
834 if ( !$masterConn ) {
835 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
836 $conn = $this->getAnyOpenConnection( $i );
838 wfDebug( "Master pos fetched from slave\n" );
839 return $conn->getSlavePos();
843 wfDebug( "Master pos fetched from master\n" );
844 return $masterConn->getMasterPos();
850 * Close all open connections
852 function closeAll() {
853 foreach ( $this->mConns
as $conns2 ) {
854 foreach ( $conns2 as $conns3 ) {
855 foreach ( $conns3 as $conn ) {
860 $this->mConns
= array(
862 'foreignFree' => array(),
863 'foreignUsed' => array(),
868 * Deprecated function, typo in function name
870 * @deprecated in 1.18
873 function closeConnecton( $conn ) {
874 wfDeprecated( __METHOD__
, '1.18' );
875 $this->closeConnection( $conn );
880 * Using this function makes sure the LoadBalancer knows the connection is closed.
881 * If you use $conn->close() directly, the load balancer won't update its state.
882 * @param $conn DatabaseBase
884 function closeConnection( $conn ) {
886 foreach ( $this->mConns
as $i1 => $conns2 ) {
887 foreach ( $conns2 as $i2 => $conns3 ) {
888 foreach ( $conns3 as $i3 => $candidateConn ) {
889 if ( $conn === $candidateConn ) {
891 unset( $this->mConns
[$i1][$i2][$i3] );
904 * Commit transactions on all open connections
906 function commitAll() {
907 foreach ( $this->mConns
as $conns2 ) {
908 foreach ( $conns2 as $conns3 ) {
909 foreach ( $conns3 as $conn ) {
910 $conn->commit( __METHOD__
);
917 * Issue COMMIT only on master, only if queries were done on connection
919 function commitMasterChanges() {
920 // Always 0, but who knows.. :)
921 $masterIndex = $this->getWriterIndex();
922 foreach ( $this->mConns
as $conns2 ) {
923 if ( empty( $conns2[$masterIndex] ) ) {
926 foreach ( $conns2[$masterIndex] as $conn ) {
927 if ( $conn->trxLevel() && $conn->doneWrites() ) {
928 $conn->commit( __METHOD__
);
938 function waitTimeout( $value = null ) {
939 return wfSetVar( $this->mWaitTimeout
, $value );
945 function getLaggedSlaveMode() {
946 return $this->mLaggedSlaveMode
;
950 * Disables/enables lag checks
954 function allowLagged( $mode = null ) {
955 if ( $mode === null) {
956 return $this->mAllowLagged
;
958 $this->mAllowLagged
= $mode;
966 foreach ( $this->mConns
as $conns2 ) {
967 foreach ( $conns2 as $conns3 ) {
968 foreach ( $conns3 as $conn ) {
969 if ( !$conn->ping() ) {
979 * Call a function with each open connection object
981 * @param array $params
983 function forEachOpenConnection( $callback, $params = array() ) {
984 foreach ( $this->mConns
as $conns2 ) {
985 foreach ( $conns2 as $conns3 ) {
986 foreach ( $conns3 as $conn ) {
987 $mergedParams = array_merge( array( $conn ), $params );
988 call_user_func_array( $callback, $mergedParams );
995 * Get the hostname and lag time of the most-lagged slave.
996 * This is useful for maintenance scripts that need to throttle their updates.
997 * May attempt to open connections to slaves on the default DB. If there is
998 * no lag, the maximum lag will be reported as -1.
1000 * @param $wiki string Wiki ID, or false for the default database
1002 * @return array ( host, max lag, index of max lagged host )
1004 function getMaxLag( $wiki = false ) {
1008 if ( $this->getServerCount() > 1 ) { // no replication = no lag
1009 foreach ( $this->mServers
as $i => $conn ) {
1011 if ( $wiki === false ) {
1012 $conn = $this->getAnyOpenConnection( $i );
1015 $conn = $this->openConnection( $i, $wiki );
1020 $lag = $conn->getLag();
1021 if ( $lag > $maxLag ) {
1023 $host = $this->mServers
[$i]['host'];
1028 return array( $host, $maxLag, $maxIndex );
1032 * Get lag time for each server
1033 * Results are cached for a short time in memcached, and indefinitely in the process cache
1039 function getLagTimes( $wiki = false ) {
1041 if ( isset( $this->mLagTimes
) ) {
1042 return $this->mLagTimes
;
1044 if ( $this->getServerCount() == 1 ) {
1046 $this->mLagTimes
= array( 0 => 0 );
1048 # Send the request to the load monitor
1049 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes(
1050 array_keys( $this->mServers
), $wiki );
1052 return $this->mLagTimes
;
1056 * Get the lag in seconds for a given connection, or zero if this load
1057 * balancer does not have replication enabled.
1059 * This should be used in preference to Database::getLag() in cases where
1060 * replication may not be in use, since there is no way to determine if
1061 * replication is in use at the connection level without running
1062 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1063 * function instead of Database::getLag() avoids a fatal error in this
1064 * case on many installations.
1066 * @param $conn DatabaseBase
1070 function safeGetLag( $conn ) {
1071 if ( $this->getServerCount() == 1 ) {
1074 return $conn->getLag();
1079 * Clear the cache for getLagTimes
1081 function clearLagTimeCache() {
1082 $this->mLagTimes
= null;