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;
35 /** @var bool|DBMasterPos False if not set */
38 private $mWaitTimeout;
39 private $mLaggedSlaveMode, $mLastError = 'Unknown error';
40 private $mParentInfo, $mLagTimes;
41 private $mLoadMonitorClass, $mLoadMonitor;
44 * @param array $params with keys:
45 * servers Required. Array of server info structures.
46 * masterWaitTimeout Replication lag wait timeout
47 * loadMonitor Name of a class used to fetch server lag and load.
50 function __construct( $params ) {
51 if ( !isset( $params['servers'] ) ) {
52 throw new MWException( __CLASS__
. ': missing servers parameter' );
54 $this->mServers
= $params['servers'];
56 if ( isset( $params['waitTimeout'] ) ) {
57 $this->mWaitTimeout
= $params['waitTimeout'];
59 $this->mWaitTimeout
= 10;
62 $this->mReadIndex
= -1;
63 $this->mWriteIndex
= -1;
64 $this->mConns
= array(
66 'foreignUsed' => array(),
67 'foreignFree' => array() );
68 $this->mLoads
= array();
69 $this->mWaitForPos
= false;
70 $this->mLaggedSlaveMode
= false;
71 $this->mErrorConnection
= false;
72 $this->mAllowLagged
= false;
74 if ( isset( $params['loadMonitor'] ) ) {
75 $this->mLoadMonitorClass
= $params['loadMonitor'];
77 $master = reset( $params['servers'] );
78 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
79 $this->mLoadMonitorClass
= 'LoadMonitorMySQL';
81 $this->mLoadMonitorClass
= 'LoadMonitorNull';
85 foreach ( $params['servers'] as $i => $server ) {
86 $this->mLoads
[$i] = $server['load'];
87 if ( isset( $server['groupLoads'] ) ) {
88 foreach ( $server['groupLoads'] as $group => $ratio ) {
89 if ( !isset( $this->mGroupLoads
[$group] ) ) {
90 $this->mGroupLoads
[$group] = array();
92 $this->mGroupLoads
[$group][$i] = $ratio;
99 * Get a LoadMonitor instance
101 * @return LoadMonitor
103 function getLoadMonitor() {
104 if ( !isset( $this->mLoadMonitor
) ) {
105 $class = $this->mLoadMonitorClass
;
106 $this->mLoadMonitor
= new $class( $this );
109 return $this->mLoadMonitor
;
113 * Get or set arbitrary data used by the parent object, usually an LBFactory
117 function parentInfo( $x = null ) {
118 return wfSetVar( $this->mParentInfo
, $x );
122 * Given an array of non-normalised probabilities, this function will select
123 * an element and return the appropriate key
125 * @deprecated since 1.21, use ArrayUtils::pickRandom()
127 * @param array $weights
128 * @return bool|int|string
130 function pickRandom( $weights ) {
131 return ArrayUtils
::pickRandom( $weights );
135 * @param array $loads
136 * @param bool|string $wiki Wiki to get non-lagged for
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 ArrayUtils
::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
183 * @param bool|string $group
184 * @param bool|string $wiki
185 * @throws MWException
186 * @return bool|int|string
188 function getReaderIndex( $group = false, $wiki = false ) {
189 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
191 # @todo FIXME: For now, only go through all this for mysql databases
192 if ( $wgDBtype != 'mysql' ) {
193 return $this->getWriterIndex();
196 if ( count( $this->mServers
) == 1 ) {
197 # Skip the load balancing if there's only one server
199 } elseif ( $group === false and $this->mReadIndex
>= 0 ) {
200 # Shortcut if generic reader exists already
201 return $this->mReadIndex
;
204 wfProfileIn( __METHOD__
);
208 # convert from seconds to microseconds
209 $timeout = $wgDBClusterTimeout * 1e6
;
211 # Find the relevant load array
212 if ( $group !== false ) {
213 if ( isset( $this->mGroupLoads
[$group] ) ) {
214 $nonErrorLoads = $this->mGroupLoads
[$group];
216 # No loads for this group, return false and the caller can use some other group
217 wfDebug( __METHOD__
. ": no loads for group $group\n" );
218 wfProfileOut( __METHOD__
);
223 $nonErrorLoads = $this->mLoads
;
226 if ( !$nonErrorLoads ) {
227 wfProfileOut( __METHOD__
);
228 throw new MWException( "Empty server array given to LoadBalancer" );
231 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
232 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
234 $laggedSlaveMode = false;
236 # First try quickly looking through the available servers for a server that
239 $totalThreadsConnected = 0;
240 $overloadedServers = 0;
241 $currentLoads = $nonErrorLoads;
242 while ( count( $currentLoads ) ) {
243 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
244 $i = ArrayUtils
::pickRandom( $currentLoads );
246 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
247 if ( $i === false && count( $currentLoads ) != 0 ) {
248 # All slaves lagged. Switch to read-only mode
249 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode\n" );
250 $wgReadOnly = 'The database has been automatically locked ' .
251 'while the slave database servers catch up to the master';
252 $i = ArrayUtils
::pickRandom( $currentLoads );
253 $laggedSlaveMode = true;
257 if ( $i === false ) {
258 # pickRandom() returned false
259 # This is permanent and means the configuration or the load monitor
260 # wants us to return false.
261 wfDebugLog( 'connect', __METHOD__
. ": pickRandom() returned false\n" );
262 wfProfileOut( __METHOD__
);
267 wfDebugLog( 'connect', __METHOD__
. ": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
268 $conn = $this->openConnection( $i, $wiki );
271 wfDebugLog( 'connect', __METHOD__
. ": Failed connecting to $i/$wiki\n" );
272 unset( $nonErrorLoads[$i] );
273 unset( $currentLoads[$i] );
277 // Perform post-connection backoff
278 $threshold = isset( $this->mServers
[$i]['max threads'] )
279 ?
$this->mServers
[$i]['max threads'] : false;
280 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
282 // Decrement reference counter, we are finished with this connection.
283 // It will be incremented for the caller later.
284 if ( $wiki !== false ) {
285 $this->reuseConnection( $conn );
289 # Post-connection overload, don't use this server for now
290 $totalThreadsConnected +
= $backoff;
291 $overloadedServers++
;
292 unset( $currentLoads[$i] );
299 # No server found yet
302 # If all servers were down, quit now
303 if ( !count( $nonErrorLoads ) ) {
304 wfDebugLog( 'connect', "All servers down\n" );
308 # Some servers must have been overloaded
309 if ( $overloadedServers == 0 ) {
310 throw new MWException( __METHOD__
. ": unexpectedly found no overloaded servers" );
312 # Back off for a while
313 # Scale the sleep time by the number of connected threads, to produce a
314 # roughly constant global poll rate
315 $avgThreads = $totalThreadsConnected / $overloadedServers;
316 $totalElapsed +
= $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
317 } while ( $totalElapsed < $timeout );
319 if ( $totalElapsed >= $timeout ) {
320 wfDebugLog( 'connect', "All servers busy\n" );
321 $this->mErrorConnection
= false;
322 $this->mLastError
= 'All servers busy';
325 if ( $i !== false ) {
326 # Slave connection successful
327 # Wait for the session master pos for a short time
328 if ( $this->mWaitForPos
&& $i > 0 ) {
329 if ( !$this->doWait( $i ) ) {
330 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
333 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $i !== false ) {
334 $this->mReadIndex
= $i;
337 wfProfileOut( __METHOD__
);
343 * Wait for a specified number of microseconds, and return the period waited
347 function sleep( $t ) {
348 wfProfileIn( __METHOD__
);
349 wfDebug( __METHOD__
. ": waiting $t us\n" );
351 wfProfileOut( __METHOD__
);
357 * Set the master wait position
358 * If a DB_SLAVE connection has been opened already, waits
359 * Otherwise sets a variable telling it to wait if such a connection is opened
360 * @param DBMasterPos $pos
362 public function waitFor( $pos ) {
363 wfProfileIn( __METHOD__
);
364 $this->mWaitForPos
= $pos;
365 $i = $this->mReadIndex
;
368 if ( !$this->doWait( $i ) ) {
369 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
370 $this->mLaggedSlaveMode
= true;
373 wfProfileOut( __METHOD__
);
377 * Set the master wait position and wait for ALL slaves to catch up to it
378 * @param DBMasterPos $pos
380 public function waitForAll( $pos ) {
381 wfProfileIn( __METHOD__
);
382 $this->mWaitForPos
= $pos;
383 $serverCount = count( $this->mServers
);
384 for ( $i = 1; $i < $serverCount; $i++
) {
385 if ( $this->mLoads
[$i] > 0 ) {
386 $this->doWait( $i, true );
389 wfProfileOut( __METHOD__
);
393 * Get any open connection to a given server index, local or foreign
394 * Returns false if there is no connection open
397 * @return DatabaseBase|bool False on failure
399 function getAnyOpenConnection( $i ) {
400 foreach ( $this->mConns
as $conns ) {
401 if ( !empty( $conns[$i] ) ) {
402 return reset( $conns[$i] );
410 * Wait for a given slave to catch up to the master pos stored in $this
415 protected function doWait( $index, $open = false ) {
416 # Find a connection to wait on
417 $conn = $this->getAnyOpenConnection( $index );
420 wfDebug( __METHOD__
. ": no connection open\n" );
424 $conn = $this->openConnection( $index, '' );
426 wfDebug( __METHOD__
. ": failed to open connection\n" );
433 wfDebug( __METHOD__
. ": Waiting for slave #$index to catch up...\n" );
434 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
436 if ( $result == -1 ||
is_null( $result ) ) {
437 # Timed out waiting for slave, use master instead
438 wfDebug( __METHOD__
. ": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
442 wfDebug( __METHOD__
. ": Done\n" );
449 * Get a connection by index
450 * This is the main entry point for this class.
452 * @param $i Integer: server index
453 * @param array $groups query groups
454 * @param bool|string $wiki Wiki ID
456 * @throws MWException
457 * @return DatabaseBase
459 public function &getConnection( $i, $groups = array(), $wiki = false ) {
460 wfProfileIn( __METHOD__
);
462 if ( $i == DB_LAST
) {
463 wfProfileOut( __METHOD__
);
464 throw new MWException( 'Attempt to call ' . __METHOD__
.
465 ' with deprecated server index DB_LAST' );
466 } elseif ( $i === null ||
$i === false ) {
467 wfProfileOut( __METHOD__
);
468 throw new MWException( 'Attempt to call ' . __METHOD__
.
469 ' with invalid server index' );
472 if ( $wiki === wfWikiID() ) {
477 if ( $i == DB_MASTER
) {
478 $i = $this->getWriterIndex();
479 } elseif ( !is_array( $groups ) ) {
480 $groupIndex = $this->getReaderIndex( $groups, $wiki );
481 if ( $groupIndex !== false ) {
482 $serverName = $this->getServerName( $groupIndex );
483 wfDebug( __METHOD__
. ": using server $serverName for group $groups\n" );
487 foreach ( $groups as $group ) {
488 $groupIndex = $this->getReaderIndex( $group, $wiki );
489 if ( $groupIndex !== false ) {
490 $serverName = $this->getServerName( $groupIndex );
491 wfDebug( __METHOD__
. ": using server $serverName for group $group\n" );
498 # Operation-based index
499 if ( $i == DB_SLAVE
) {
500 $this->mLastError
= 'Unknown error'; // reset error string
501 $i = $this->getReaderIndex( false, $wiki );
502 # Couldn't find a working server in getReaderIndex()?
503 if ( $i === false ) {
504 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
505 wfProfileOut( __METHOD__
);
507 return $this->reportConnectionError();
511 # Now we have an explicit index into the servers array
512 $conn = $this->openConnection( $i, $wiki );
514 wfProfileOut( __METHOD__
);
516 return $this->reportConnectionError();
519 wfProfileOut( __METHOD__
);
525 * Mark a foreign connection as being available for reuse under a different
526 * DB name or prefix. This mechanism is reference-counted, and must be called
527 * the same number of times as getConnection() to work.
529 * @param DatabaseBase $conn
530 * @throws MWException
532 public function reuseConnection( $conn ) {
533 $serverIndex = $conn->getLBInfo( 'serverIndex' );
534 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
535 $dbName = $conn->getDBname();
536 $prefix = $conn->tablePrefix();
537 if ( strval( $prefix ) !== '' ) {
538 $wiki = "$dbName-$prefix";
542 if ( $serverIndex === null ||
$refCount === null ) {
543 wfDebug( __METHOD__
. ": this connection was not opened as a foreign connection\n" );
546 * This can happen in code like:
547 * foreach ( $dbs as $db ) {
548 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
550 * $lb->reuseConnection( $conn );
552 * When a connection to the local DB is opened in this way, reuseConnection()
558 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
559 throw new MWException( __METHOD__
. ": connection not found, has " .
560 "the connection been freed already?" );
562 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
563 if ( $refCount <= 0 ) {
564 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
565 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
566 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
568 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
573 * Get a database connection handle reference
575 * The handle's methods wrap simply wrap those of a DatabaseBase handle
577 * @see LoadBalancer::getConnection() for parameter information
580 * @param mixed $groups
581 * @param bool|string $wiki
584 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
585 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
589 * Get a database connection handle reference without connecting yet
591 * The handle's methods wrap simply wrap those of a DatabaseBase handle
593 * @see LoadBalancer::getConnection() for parameter information
596 * @param mixed $groups
597 * @param bool|string $wiki
600 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
601 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
605 * Open a connection to the server given by the specified index
606 * Index must be an actual index into the array.
607 * If the server is already open, returns it.
609 * On error, returns false, and the connection which caused the
610 * error will be available via $this->mErrorConnection.
612 * @param $i Integer server index
613 * @param bool|string $wiki wiki ID to open
614 * @return DatabaseBase
618 function openConnection( $i, $wiki = false ) {
619 wfProfileIn( __METHOD__
);
620 if ( $wiki !== false ) {
621 $conn = $this->openForeignConnection( $i, $wiki );
622 wfProfileOut( __METHOD__
);
626 if ( isset( $this->mConns
['local'][$i][0] ) ) {
627 $conn = $this->mConns
['local'][$i][0];
629 $server = $this->mServers
[$i];
630 $server['serverIndex'] = $i;
631 $conn = $this->reallyOpenConnection( $server, false );
632 if ( $conn->isOpen() ) {
633 wfDebug( "Connected to database $i at {$this->mServers[$i]['host']}\n" );
634 $this->mConns
['local'][$i][0] = $conn;
636 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
637 $this->mErrorConnection
= $conn;
641 wfProfileOut( __METHOD__
);
647 * Open a connection to a foreign DB, or return one if it is already open.
649 * Increments a reference count on the returned connection which locks the
650 * connection to the requested wiki. This reference count can be
651 * decremented by calling reuseConnection().
653 * If a connection is open to the appropriate server already, but with the wrong
654 * database, it will be switched to the right database and returned, as long as
655 * it has been freed first with reuseConnection().
657 * On error, returns false, and the connection which caused the
658 * error will be available via $this->mErrorConnection.
660 * @param $i Integer: server index
661 * @param string $wiki wiki ID to open
662 * @return DatabaseBase
664 function openForeignConnection( $i, $wiki ) {
665 wfProfileIn( __METHOD__
);
666 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
667 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
668 // Reuse an already-used connection
669 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
670 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
671 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
672 // Reuse a free connection for the same wiki
673 $conn = $this->mConns
['foreignFree'][$i][$wiki];
674 unset( $this->mConns
['foreignFree'][$i][$wiki] );
675 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
676 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
677 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
678 // Reuse a connection from another wiki
679 $conn = reset( $this->mConns
['foreignFree'][$i] );
680 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
682 if ( !$conn->selectDB( $dbName ) ) {
683 $this->mLastError
= "Error selecting database $dbName on server " .
684 $conn->getServer() . " from client host " . wfHostname() . "\n";
685 $this->mErrorConnection
= $conn;
688 $conn->tablePrefix( $prefix );
689 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
690 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
691 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
694 // Open a new connection
695 $server = $this->mServers
[$i];
696 $server['serverIndex'] = $i;
697 $server['foreignPoolRefCount'] = 0;
698 $server['foreign'] = true;
699 $conn = $this->reallyOpenConnection( $server, $dbName );
700 if ( !$conn->isOpen() ) {
701 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
702 $this->mErrorConnection
= $conn;
705 $conn->tablePrefix( $prefix );
706 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
707 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
711 // Increment reference count
713 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
714 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
716 wfProfileOut( __METHOD__
);
722 * Test if the specified index represents an open connection
724 * @param $index Integer: server index
728 function isOpen( $index ) {
729 if ( !is_integer( $index ) ) {
733 return (bool)$this->getAnyOpenConnection( $index );
737 * Really opens a connection. Uncached.
738 * Returns a Database object whether or not the connection was successful.
742 * @param $dbNameOverride bool
743 * @throws MWException
744 * @return DatabaseBase
746 function reallyOpenConnection( $server, $dbNameOverride = false ) {
747 if ( !is_array( $server ) ) {
748 throw new MWException( 'You must update your load-balancing configuration. ' .
749 'See DefaultSettings.php entry for $wgDBservers.' );
752 if ( $dbNameOverride !== false ) {
753 $server['dbname'] = $dbNameOverride;
758 $db = DatabaseBase
::factory( $server['type'], $server );
759 } catch ( DBConnectionError
$e ) {
760 // FIXME: This is probably the ugliest thing I have ever done to
761 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
765 $db->setLBInfo( $server );
766 if ( isset( $server['fakeSlaveLag'] ) ) {
767 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
769 if ( isset( $server['fakeMaster'] ) ) {
770 $db->setFakeMaster( true );
777 * @throws DBConnectionError
780 private function reportConnectionError() {
781 $conn = $this->mErrorConnection
; // The connection which caused the error
783 if ( !is_object( $conn ) ) {
784 // No last connection, probably due to all servers being too busy
785 wfLogDBError( "LB failure with no last connection. Connection error: {$this->mLastError}\n" );
787 // If all servers were busy, mLastError will contain something sensible
788 throw new DBConnectionError( null, $this->mLastError
);
790 $server = $conn->getProperty( 'mServer' );
791 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
792 $conn->reportConnectionError( "{$this->mLastError} ({$server})" ); // throws DBConnectionError
795 return false; /* not reached */
801 function getWriterIndex() {
806 * Returns true if the specified index is a valid server index
811 function haveIndex( $i ) {
812 return array_key_exists( $i, $this->mServers
);
816 * Returns true if the specified index is valid and has non-zero load
821 function isNonZeroLoad( $i ) {
822 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
826 * Get the number of defined servers (not the number of open connections)
830 function getServerCount() {
831 return count( $this->mServers
);
835 * Get the host name or IP address of the server with the specified index
836 * Prefer a readable name if available.
840 function getServerName( $i ) {
841 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
842 return $this->mServers
[$i]['hostName'];
843 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
844 return $this->mServers
[$i]['host'];
851 * Return the server info structure for a given index, or false if the index is invalid.
855 function getServerInfo( $i ) {
856 if ( isset( $this->mServers
[$i] ) ) {
857 return $this->mServers
[$i];
864 * Sets the server info structure for the given index. Entry at index $i
865 * is created if it doesn't exist
869 function setServerInfo( $i, $serverInfo ) {
870 $this->mServers
[$i] = $serverInfo;
874 * Get the current master position for chronology control purposes
877 function getMasterPos() {
878 # If this entire request was served from a slave without opening a connection to the
879 # master (however unlikely that may be), then we can fetch the position from the slave.
880 $masterConn = $this->getAnyOpenConnection( 0 );
881 if ( !$masterConn ) {
882 $serverCount = count( $this->mServers
);
883 for ( $i = 1; $i < $serverCount; $i++
) {
884 $conn = $this->getAnyOpenConnection( $i );
886 wfDebug( "Master pos fetched from slave\n" );
888 return $conn->getSlavePos();
892 wfDebug( "Master pos fetched from master\n" );
894 return $masterConn->getMasterPos();
901 * Close all open connections
903 function closeAll() {
904 foreach ( $this->mConns
as $conns2 ) {
905 foreach ( $conns2 as $conns3 ) {
906 foreach ( $conns3 as $conn ) {
911 $this->mConns
= array(
913 'foreignFree' => array(),
914 'foreignUsed' => array(),
919 * Deprecated function, typo in function name
921 * @deprecated in 1.18
924 function closeConnecton( $conn ) {
925 wfDeprecated( __METHOD__
, '1.18' );
926 $this->closeConnection( $conn );
931 * Using this function makes sure the LoadBalancer knows the connection is closed.
932 * If you use $conn->close() directly, the load balancer won't update its state.
933 * @param $conn DatabaseBase
935 function closeConnection( $conn ) {
937 foreach ( $this->mConns
as $i1 => $conns2 ) {
938 foreach ( $conns2 as $i2 => $conns3 ) {
939 foreach ( $conns3 as $i3 => $candidateConn ) {
940 if ( $conn === $candidateConn ) {
942 unset( $this->mConns
[$i1][$i2][$i3] );
955 * Commit transactions on all open connections
957 function commitAll() {
958 foreach ( $this->mConns
as $conns2 ) {
959 foreach ( $conns2 as $conns3 ) {
960 foreach ( $conns3 as $conn ) {
961 if ( $conn->trxLevel() ) {
962 $conn->commit( __METHOD__
, 'flush' );
970 * Issue COMMIT only on master, only if queries were done on connection
972 function commitMasterChanges() {
973 // Always 0, but who knows.. :)
974 $masterIndex = $this->getWriterIndex();
975 foreach ( $this->mConns
as $conns2 ) {
976 if ( empty( $conns2[$masterIndex] ) ) {
979 foreach ( $conns2[$masterIndex] as $conn ) {
980 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
981 $conn->commit( __METHOD__
, 'flush' );
991 function waitTimeout( $value = null ) {
992 return wfSetVar( $this->mWaitTimeout
, $value );
998 function getLaggedSlaveMode() {
999 return $this->mLaggedSlaveMode
;
1003 * Disables/enables lag checks
1004 * @param null|bool $mode
1007 function allowLagged( $mode = null ) {
1008 if ( $mode === null ) {
1009 return $this->mAllowLagged
;
1011 $this->mAllowLagged
= $mode;
1013 return $this->mAllowLagged
;
1019 function pingAll() {
1021 foreach ( $this->mConns
as $conns2 ) {
1022 foreach ( $conns2 as $conns3 ) {
1023 foreach ( $conns3 as $conn ) {
1024 if ( !$conn->ping() ) {
1035 * Call a function with each open connection object
1036 * @param callable $callback
1037 * @param array $params
1039 function forEachOpenConnection( $callback, $params = array() ) {
1040 foreach ( $this->mConns
as $conns2 ) {
1041 foreach ( $conns2 as $conns3 ) {
1042 foreach ( $conns3 as $conn ) {
1043 $mergedParams = array_merge( array( $conn ), $params );
1044 call_user_func_array( $callback, $mergedParams );
1051 * Get the hostname and lag time of the most-lagged slave.
1052 * This is useful for maintenance scripts that need to throttle their updates.
1053 * May attempt to open connections to slaves on the default DB. If there is
1054 * no lag, the maximum lag will be reported as -1.
1056 * @param bool|string $wiki Wiki ID, or false for the default database
1057 * @return array ( host, max lag, index of max lagged host )
1059 function getMaxLag( $wiki = false ) {
1063 if ( $this->getServerCount() > 1 ) { // no replication = no lag
1064 foreach ( $this->mServers
as $i => $conn ) {
1066 if ( $wiki === false ) {
1067 $conn = $this->getAnyOpenConnection( $i );
1070 $conn = $this->openConnection( $i, $wiki );
1075 $lag = $conn->getLag();
1076 if ( $lag > $maxLag ) {
1078 $host = $this->mServers
[$i]['host'];
1084 return array( $host, $maxLag, $maxIndex );
1088 * Get lag time for each server
1089 * Results are cached for a short time in memcached, and indefinitely in the process cache
1091 * @param string|bool $wiki
1094 function getLagTimes( $wiki = false ) {
1096 if ( isset( $this->mLagTimes
) ) {
1097 return $this->mLagTimes
;
1099 if ( $this->getServerCount() == 1 ) {
1101 $this->mLagTimes
= array( 0 => 0 );
1103 # Send the request to the load monitor
1104 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes(
1105 array_keys( $this->mServers
), $wiki );
1108 return $this->mLagTimes
;
1112 * Get the lag in seconds for a given connection, or zero if this load
1113 * balancer does not have replication enabled.
1115 * This should be used in preference to Database::getLag() in cases where
1116 * replication may not be in use, since there is no way to determine if
1117 * replication is in use at the connection level without running
1118 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1119 * function instead of Database::getLag() avoids a fatal error in this
1120 * case on many installations.
1122 * @param DatabaseBase $conn
1125 function safeGetLag( $conn ) {
1126 if ( $this->getServerCount() == 1 ) {
1129 return $conn->getLag();
1134 * Clear the cache for getLagTimes
1136 function clearLagTimeCache() {
1137 $this->mLagTimes
= null;
1142 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
1143 * as well handling deferring the actual network connection until the handle is used
1148 class DBConnRef
implements IDatabase
{
1149 /** @var LoadBalancer */
1152 /** @var DatabaseBase|null */
1155 /** @var array|null */
1159 * @param LoadBalancer $lb
1160 * @param DatabaseBase|array $conn Connection or (server index, group, wiki ID) array
1162 public function __construct( LoadBalancer
$lb, $conn ) {
1164 if ( $conn instanceof DatabaseBase
) {
1165 $this->conn
= $conn;
1167 $this->params
= $conn;
1171 public function __call( $name, $arguments ) {
1172 if ( $this->conn
=== null ) {
1173 list( $db, $groups, $wiki ) = $this->params
;
1174 $this->conn
= $this->lb
->getConnection( $db, $groups, $wiki );
1177 return call_user_func_array( array( $this->conn
, $name ), $arguments );
1180 function __destruct() {
1181 if ( $this->conn
!== null ) {
1182 $this->lb
->reuseConnection( $this->conn
);