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 /** @var array[] Map of (server index => server config array) */
33 /** @var array[] Map of (local/foreignUsed/foreignFree => server index => DatabaseBase array) */
35 /** @var array Map of (server index => weight) */
37 /** @var array[] Map of (group => server index => weight) */
39 /** @var bool Whether to disregard slave lag as a factor in slave selection */
40 private $mAllowLagged;
41 /** @var integer Seconds to spend waiting on slave lag to resolve */
42 private $mWaitTimeout;
44 /** @var array LBFactory information */
46 /** @var string The LoadMonitor subclass name */
47 private $mLoadMonitorClass;
48 /** @var LoadMonitor */
49 private $mLoadMonitor;
51 /** @var bool|DatabaseBase Database connection that caused a problem */
52 private $mErrorConnection;
53 /** @var integer The generic (not query grouped) slave index (of $mServers) */
55 /** @var bool|DBMasterPos False if not set */
57 /** @var bool Whether the generic reader fell back to a lagged slave */
58 private $mLaggedSlaveMode;
59 /** @var string The last DB selection or connection error */
60 private $mLastError = 'Unknown error';
61 /** @var ProcessCacheLRU */
65 * @param array $params Array with keys:
66 * servers Required. Array of server info structures.
67 * loadMonitor Name of a class used to fetch server lag and load.
70 public function __construct( array $params ) {
71 if ( !isset( $params['servers'] ) ) {
72 throw new MWException( __CLASS__
. ': missing servers parameter' );
74 $this->mServers
= $params['servers'];
75 $this->mWaitTimeout
= 10;
77 $this->mReadIndex
= -1;
78 $this->mWriteIndex
= -1;
79 $this->mConns
= array(
81 'foreignUsed' => array(),
82 'foreignFree' => array() );
83 $this->mLoads
= array();
84 $this->mWaitForPos
= false;
85 $this->mLaggedSlaveMode
= false;
86 $this->mErrorConnection
= false;
87 $this->mAllowLagged
= false;
89 if ( isset( $params['loadMonitor'] ) ) {
90 $this->mLoadMonitorClass
= $params['loadMonitor'];
92 $master = reset( $params['servers'] );
93 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
94 $this->mLoadMonitorClass
= 'LoadMonitorMySQL';
96 $this->mLoadMonitorClass
= 'LoadMonitorNull';
100 foreach ( $params['servers'] as $i => $server ) {
101 $this->mLoads
[$i] = $server['load'];
102 if ( isset( $server['groupLoads'] ) ) {
103 foreach ( $server['groupLoads'] as $group => $ratio ) {
104 if ( !isset( $this->mGroupLoads
[$group] ) ) {
105 $this->mGroupLoads
[$group] = array();
107 $this->mGroupLoads
[$group][$i] = $ratio;
112 $this->mProcCache
= new ProcessCacheLRU( 30 );
116 * Get a LoadMonitor instance
118 * @return LoadMonitor
120 private function getLoadMonitor() {
121 if ( !isset( $this->mLoadMonitor
) ) {
122 $class = $this->mLoadMonitorClass
;
123 $this->mLoadMonitor
= new $class( $this );
126 return $this->mLoadMonitor
;
130 * Get or set arbitrary data used by the parent object, usually an LBFactory
134 public function parentInfo( $x = null ) {
135 return wfSetVar( $this->mParentInfo
, $x );
139 * Given an array of non-normalised probabilities, this function will select
140 * an element and return the appropriate key
142 * @deprecated since 1.21, use ArrayUtils::pickRandom()
144 * @param array $weights
145 * @return bool|int|string
147 public function pickRandom( array $weights ) {
148 return ArrayUtils
::pickRandom( $weights );
152 * @param array $loads
153 * @param bool|string $wiki Wiki to get non-lagged for
154 * @param float $maxLag Restrict the maximum allowed lag to this many seconds
155 * @return bool|int|string
157 private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = INF
) {
158 $lags = $this->getLagTimes( $wiki );
160 # Unset excessively lagged servers
161 foreach ( $lags as $i => $lag ) {
163 $maxServerLag = $maxLag;
164 if ( isset( $this->mServers
[$i]['max lag'] ) ) {
165 $maxServerLag = min( $maxServerLag, $this->mServers
[$i]['max lag'] );
167 if ( $lag === false ) {
168 wfDebugLog( 'replication', "Server #$i is not replicating" );
170 } elseif ( $lag > $maxServerLag ) {
171 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)" );
177 # Find out if all the slaves with non-zero load are lagged
179 foreach ( $loads as $load ) {
183 # No appropriate DB servers except maybe the master and some slaves with zero load
184 # Do NOT use the master
185 # Instead, this function will return false, triggering read-only mode,
186 # and a lagged slave will be used instead.
190 if ( count( $loads ) == 0 ) {
194 #wfDebugLog( 'connect', var_export( $loads, true ) );
196 # Return a random representative of the remainder
197 return ArrayUtils
::pickRandom( $loads );
201 * Get the index of the reader connection, which may be a slave
202 * This takes into account load ratios and lag times. It should
203 * always return a consistent index during a given invocation
205 * Side effect: opens connections to databases
206 * @param string|bool $group Query group, or false for the generic reader
207 * @param string|bool $wiki Wiki ID, or false for the current wiki
208 * @throws MWException
209 * @return bool|int|string
211 public function getReaderIndex( $group = false, $wiki = false ) {
212 global $wgReadOnly, $wgDBtype;
214 # @todo FIXME: For now, only go through all this for mysql databases
215 if ( $wgDBtype != 'mysql' ) {
216 return $this->getWriterIndex();
219 if ( count( $this->mServers
) == 1 ) {
220 # Skip the load balancing if there's only one server
222 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
223 # Shortcut if generic reader exists already
224 return $this->mReadIndex
;
227 new ProfileSection( __METHOD__
);
229 # Find the relevant load array
230 if ( $group !== false ) {
231 if ( isset( $this->mGroupLoads
[$group] ) ) {
232 $nonErrorLoads = $this->mGroupLoads
[$group];
234 # No loads for this group, return false and the caller can use some other group
235 wfDebug( __METHOD__
. ": no loads for group $group\n" );
240 $nonErrorLoads = $this->mLoads
;
243 if ( !count( $nonErrorLoads ) ) {
244 throw new MWException( "Empty server array given to LoadBalancer" );
247 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
248 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
250 $laggedSlaveMode = false;
252 # No server found yet
254 # First try quickly looking through the available servers for a server that
256 $currentLoads = $nonErrorLoads;
257 while ( count( $currentLoads ) ) {
258 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
259 $i = ArrayUtils
::pickRandom( $currentLoads );
262 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
263 # ChronologyProtecter causes mWaitForPos to be set via sessions.
264 # This triggers doWait() after connect, so it's especially good to
265 # avoid lagged servers so as to avoid just blocking in that method.
266 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
267 # Aim for <= 1 second of waiting (being too picky can backfire)
268 $i = $this->getRandomNonLagged( $currentLoads, $wiki, $ago +
1 );
270 if ( $i === false ) {
271 # Any server with less lag than it's 'max lag' param is preferable
272 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
274 if ( $i === false && count( $currentLoads ) != 0 ) {
275 # All slaves lagged. Switch to read-only mode
276 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode" );
277 $wgReadOnly = 'The database has been automatically locked ' .
278 'while the slave database servers catch up to the master';
279 $i = ArrayUtils
::pickRandom( $currentLoads );
280 $laggedSlaveMode = true;
284 if ( $i === false ) {
285 # pickRandom() returned false
286 # This is permanent and means the configuration or the load monitor
287 # wants us to return false.
288 wfDebugLog( 'connect', __METHOD__
. ": pickRandom() returned false" );
293 wfDebugLog( 'connect', __METHOD__
.
294 ": Using reader #$i: {$this->mServers[$i]['host']}..." );
296 $conn = $this->openConnection( $i, $wiki );
298 wfDebugLog( 'connect', __METHOD__
. ": Failed connecting to $i/$wiki" );
299 unset( $nonErrorLoads[$i] );
300 unset( $currentLoads[$i] );
305 // Decrement reference counter, we are finished with this connection.
306 // It will be incremented for the caller later.
307 if ( $wiki !== false ) {
308 $this->reuseConnection( $conn );
315 # If all servers were down, quit now
316 if ( !count( $nonErrorLoads ) ) {
317 wfDebugLog( 'connect', "All servers down" );
320 if ( $i !== false ) {
321 # Slave connection successful
322 # Wait for the session master pos for a short time
323 if ( $this->mWaitForPos
&& $i > 0 ) {
324 if ( !$this->doWait( $i ) ) {
325 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
328 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group !== false ) {
329 $this->mReadIndex
= $i;
337 * Set the master wait position
338 * If a DB_SLAVE connection has been opened already, waits
339 * Otherwise sets a variable telling it to wait if such a connection is opened
340 * @param DBMasterPos $pos
342 public function waitFor( $pos ) {
343 wfProfileIn( __METHOD__
);
344 $this->mWaitForPos
= $pos;
345 $i = $this->mReadIndex
;
348 if ( !$this->doWait( $i ) ) {
349 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
350 $this->mLaggedSlaveMode
= true;
353 wfProfileOut( __METHOD__
);
357 * Set the master wait position and wait for ALL slaves to catch up to it
358 * @param DBMasterPos $pos
359 * @param int $timeout Max seconds to wait; default is mWaitTimeout
360 * @return bool Success (able to connect and no timeouts reached)
362 public function waitForAll( $pos, $timeout = null ) {
363 wfProfileIn( __METHOD__
);
364 $this->mWaitForPos
= $pos;
365 $serverCount = count( $this->mServers
);
368 for ( $i = 1; $i < $serverCount; $i++
) {
369 if ( $this->mLoads
[$i] > 0 ) {
370 $ok = $this->doWait( $i, true, $timeout ) && $ok;
373 wfProfileOut( __METHOD__
);
379 * Get any open connection to a given server index, local or foreign
380 * Returns false if there is no connection open
383 * @return DatabaseBase|bool False on failure
385 public function getAnyOpenConnection( $i ) {
386 foreach ( $this->mConns
as $conns ) {
387 if ( !empty( $conns[$i] ) ) {
388 return reset( $conns[$i] );
396 * Wait for a given slave to catch up to the master pos stored in $this
397 * @param int $index Server index
398 * @param bool $open Check the server even if a new connection has to be made
399 * @param int $timeout Max seconds to wait; default is mWaitTimeout
402 protected function doWait( $index, $open = false, $timeout = null ) {
403 $close = false; // close the connection afterwards
405 # Find a connection to wait on, creating one if needed and allowed
406 $conn = $this->getAnyOpenConnection( $index );
409 wfDebug( __METHOD__
. ": no connection open\n" );
413 $conn = $this->openConnection( $index, '' );
415 wfDebug( __METHOD__
. ": failed to open connection\n" );
419 // Avoid connection spam in waitForAll() when connections
420 // are made just for the sake of doing this lag check.
425 wfDebug( __METHOD__
. ": Waiting for slave #$index to catch up...\n" );
426 $timeout = $timeout ?
: $this->mWaitTimeout
;
427 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
429 if ( $result == -1 ||
is_null( $result ) ) {
430 # Timed out waiting for slave, use master instead
431 $server = $this->mServers
[$index]['host'];
432 $msg = __METHOD__
. ": Timed out waiting on $server pos {$this->mWaitForPos}";
434 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
437 wfDebug( __METHOD__
. ": Done\n" );
442 $this->closeConnection( $conn );
449 * Get a connection by index
450 * This is the main entry point for this class.
452 * @param int $i Server index
453 * @param array|string|bool $groups Query group(s), or false for the generic reader
454 * @param string|bool $wiki Wiki ID, or false for the current wiki
456 * @throws MWException
457 * @return DatabaseBase
459 public function getConnection( $i, $groups = array(), $wiki = false ) {
460 wfProfileIn( __METHOD__
);
462 if ( $i === null ||
$i === false ) {
463 wfProfileOut( __METHOD__
);
464 throw new MWException( 'Attempt to call ' . __METHOD__
.
465 ' with invalid server index' );
468 if ( $wiki === wfWikiID() ) {
472 $groups = ( $groups === false ||
$groups === array() )
473 ?
array( false ) // check one "group": the generic pool
476 if ( $i == DB_MASTER
) {
477 $i = $this->getWriterIndex();
479 # Try to find an available server in any the query groups (in order)
480 foreach ( $groups as $group ) {
481 $groupIndex = $this->getReaderIndex( $group, $wiki );
482 if ( $groupIndex !== false ) {
483 $serverName = $this->getServerName( $groupIndex );
484 wfDebug( __METHOD__
. ": using server $serverName for group $group\n" );
491 # Operation-based index
492 if ( $i == DB_SLAVE
) {
493 $this->mLastError
= 'Unknown error'; // reset error string
494 # Try the general server pool if $groups are unavailable.
495 $i = in_array( false, $groups, true )
496 ?
false // don't bother with this if that is what was tried above
497 : $this->getReaderIndex( false, $wiki );
498 # Couldn't find a working server in getReaderIndex()?
499 if ( $i === false ) {
500 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
501 wfProfileOut( __METHOD__
);
503 return $this->reportConnectionError();
507 # Now we have an explicit index into the servers array
508 $conn = $this->openConnection( $i, $wiki );
510 wfProfileOut( __METHOD__
);
512 return $this->reportConnectionError();
515 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 if ( $serverIndex === null ||
$refCount === null ) {
532 wfDebug( __METHOD__
. ": this connection was not opened as a foreign connection\n" );
535 * This can happen in code like:
536 * foreach ( $dbs as $db ) {
537 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
539 * $lb->reuseConnection( $conn );
541 * When a connection to the local DB is opened in this way, reuseConnection()
548 $dbName = $conn->getDBname();
549 $prefix = $conn->tablePrefix();
550 if ( strval( $prefix ) !== '' ) {
551 $wiki = "$dbName-$prefix";
555 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
556 throw new MWException( __METHOD__
. ": connection not found, has " .
557 "the connection been freed already?" );
559 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
560 if ( $refCount <= 0 ) {
561 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
562 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
563 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
565 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
570 * Get a database connection handle reference
572 * The handle's methods wrap simply wrap those of a DatabaseBase handle
574 * @see LoadBalancer::getConnection() for parameter information
577 * @param array|string|bool $groups Query group(s), or false for the generic reader
578 * @param string|bool $wiki Wiki ID, or false for the current wiki
581 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
582 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
586 * Get a database connection handle reference without connecting yet
588 * The handle's methods wrap simply wrap those of a DatabaseBase handle
590 * @see LoadBalancer::getConnection() for parameter information
593 * @param array|string|bool $groups Query group(s), or false for the generic reader
594 * @param string|bool $wiki Wiki ID, or false for the current wiki
597 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
598 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
602 * Open a connection to the server given by the specified index
603 * Index must be an actual index into the array.
604 * If the server is already open, returns it.
606 * On error, returns false, and the connection which caused the
607 * error will be available via $this->mErrorConnection.
609 * @param int $i Server index
610 * @param string|bool $wiki Wiki ID, or false for the current wiki
611 * @return DatabaseBase
615 public function openConnection( $i, $wiki = false ) {
616 wfProfileIn( __METHOD__
);
617 if ( $wiki !== false ) {
618 $conn = $this->openForeignConnection( $i, $wiki );
619 wfProfileOut( __METHOD__
);
623 if ( isset( $this->mConns
['local'][$i][0] ) ) {
624 $conn = $this->mConns
['local'][$i][0];
626 $server = $this->mServers
[$i];
627 $server['serverIndex'] = $i;
628 $conn = $this->reallyOpenConnection( $server, false );
629 if ( $conn->isOpen() ) {
630 wfDebug( "Connected to database $i at {$this->mServers[$i]['host']}\n" );
631 $this->mConns
['local'][$i][0] = $conn;
633 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
634 $this->mErrorConnection
= $conn;
638 wfProfileOut( __METHOD__
);
644 * Open a connection to a foreign DB, or return one if it is already open.
646 * Increments a reference count on the returned connection which locks the
647 * connection to the requested wiki. This reference count can be
648 * decremented by calling reuseConnection().
650 * If a connection is open to the appropriate server already, but with the wrong
651 * database, it will be switched to the right database and returned, as long as
652 * it has been freed first with reuseConnection().
654 * On error, returns false, and the connection which caused the
655 * error will be available via $this->mErrorConnection.
657 * @param int $i Server index
658 * @param string $wiki Wiki ID to open
659 * @return DatabaseBase
661 private function openForeignConnection( $i, $wiki ) {
662 wfProfileIn( __METHOD__
);
663 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
664 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
665 // Reuse an already-used connection
666 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
667 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
668 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
669 // Reuse a free connection for the same wiki
670 $conn = $this->mConns
['foreignFree'][$i][$wiki];
671 unset( $this->mConns
['foreignFree'][$i][$wiki] );
672 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
673 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
674 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
675 // Reuse a connection from another wiki
676 $conn = reset( $this->mConns
['foreignFree'][$i] );
677 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
679 // The empty string as a DB name means "don't care".
680 // DatabaseMysqlBase::open() already handle this on connection.
681 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
682 $this->mLastError
= "Error selecting database $dbName on server " .
683 $conn->getServer() . " from client host " . wfHostname() . "\n";
684 $this->mErrorConnection
= $conn;
687 $conn->tablePrefix( $prefix );
688 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
689 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
690 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
693 // Open a new connection
694 $server = $this->mServers
[$i];
695 $server['serverIndex'] = $i;
696 $server['foreignPoolRefCount'] = 0;
697 $server['foreign'] = true;
698 $conn = $this->reallyOpenConnection( $server, $dbName );
699 if ( !$conn->isOpen() ) {
700 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
701 $this->mErrorConnection
= $conn;
704 $conn->tablePrefix( $prefix );
705 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
706 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
710 // Increment reference count
712 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
713 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
715 wfProfileOut( __METHOD__
);
721 * Test if the specified index represents an open connection
723 * @param int $index Server index
727 private function isOpen( $index ) {
728 if ( !is_integer( $index ) ) {
732 return (bool)$this->getAnyOpenConnection( $index );
736 * Really opens a connection. Uncached.
737 * Returns a Database object whether or not the connection was successful.
740 * @param array $server
741 * @param bool $dbNameOverride
742 * @throws MWException
743 * @return DatabaseBase
745 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
746 if ( !is_array( $server ) ) {
747 throw new MWException( 'You must update your load-balancing configuration. ' .
748 'See DefaultSettings.php entry for $wgDBservers.' );
751 if ( $dbNameOverride !== false ) {
752 $server['dbname'] = $dbNameOverride;
757 $db = DatabaseBase
::factory( $server['type'], $server );
758 } catch ( DBConnectionError
$e ) {
759 // FIXME: This is probably the ugliest thing I have ever done to
760 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
764 $db->setLBInfo( $server );
765 if ( isset( $server['fakeSlaveLag'] ) ) {
766 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
768 if ( isset( $server['fakeMaster'] ) ) {
769 $db->setFakeMaster( true );
776 * @throws DBConnectionError
779 private function reportConnectionError() {
780 $conn = $this->mErrorConnection
; // The connection which caused the error
782 'method' => __METHOD__
,
783 'last_error' => $this->mLastError
,
786 if ( !is_object( $conn ) ) {
787 // No last connection, probably due to all servers being too busy
789 "LB failure with no last connection. Connection error: {last_error}",
793 // If all servers were busy, mLastError will contain something sensible
794 throw new DBConnectionError( null, $this->mLastError
);
796 $context['db_server'] = $conn->getProperty( 'mServer' );
798 "Connection error: {last_error} ({db_server})",
801 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" ); // throws DBConnectionError
804 return false; /* not reached */
810 private function getWriterIndex() {
815 * Returns true if the specified index is a valid server index
820 public function haveIndex( $i ) {
821 return array_key_exists( $i, $this->mServers
);
825 * Returns true if the specified index is valid and has non-zero load
830 public function isNonZeroLoad( $i ) {
831 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
835 * Get the number of defined servers (not the number of open connections)
839 public function getServerCount() {
840 return count( $this->mServers
);
844 * Get the host name or IP address of the server with the specified index
845 * Prefer a readable name if available.
849 public function getServerName( $i ) {
850 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
851 return $this->mServers
[$i]['hostName'];
852 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
853 return $this->mServers
[$i]['host'];
860 * Return the server info structure for a given index, or false if the index is invalid.
864 public function getServerInfo( $i ) {
865 if ( isset( $this->mServers
[$i] ) ) {
866 return $this->mServers
[$i];
873 * Sets the server info structure for the given index. Entry at index $i
874 * is created if it doesn't exist
876 * @param array $serverInfo
878 public function setServerInfo( $i, array $serverInfo ) {
879 $this->mServers
[$i] = $serverInfo;
883 * Get the current master position for chronology control purposes
886 public function getMasterPos() {
887 # If this entire request was served from a slave without opening a connection to the
888 # master (however unlikely that may be), then we can fetch the position from the slave.
889 $masterConn = $this->getAnyOpenConnection( 0 );
890 if ( !$masterConn ) {
891 $serverCount = count( $this->mServers
);
892 for ( $i = 1; $i < $serverCount; $i++
) {
893 $conn = $this->getAnyOpenConnection( $i );
895 wfDebug( "Master pos fetched from slave\n" );
897 return $conn->getSlavePos();
901 wfDebug( "Master pos fetched from master\n" );
903 return $masterConn->getMasterPos();
910 * Close all open connections
912 public function closeAll() {
913 foreach ( $this->mConns
as $conns2 ) {
914 foreach ( $conns2 as $conns3 ) {
915 /** @var DatabaseBase $conn */
916 foreach ( $conns3 as $conn ) {
921 $this->mConns
= array(
923 'foreignFree' => array(),
924 'foreignUsed' => array(),
930 * Using this function makes sure the LoadBalancer knows the connection is closed.
931 * If you use $conn->close() directly, the load balancer won't update its state.
932 * @param DatabaseBase $conn
934 public function closeConnection( $conn ) {
936 foreach ( $this->mConns
as $i1 => $conns2 ) {
937 foreach ( $conns2 as $i2 => $conns3 ) {
938 foreach ( $conns3 as $i3 => $candidateConn ) {
939 if ( $conn === $candidateConn ) {
941 unset( $this->mConns
[$i1][$i2][$i3] );
954 * Commit transactions on all open connections
956 public function commitAll() {
957 foreach ( $this->mConns
as $conns2 ) {
958 foreach ( $conns2 as $conns3 ) {
959 /** @var DatabaseBase[] $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 public function commitMasterChanges() {
973 // Always 0, but who knows.. :)
974 $masterIndex = $this->getWriterIndex();
975 foreach ( $this->mConns
as $conns2 ) {
976 if ( empty( $conns2[$masterIndex] ) ) {
979 /** @var DatabaseBase $conn */
980 foreach ( $conns2[$masterIndex] as $conn ) {
981 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
982 $conn->commit( __METHOD__
, 'flush' );
989 * Issue ROLLBACK only on master, only if queries were done on connection
992 public function rollbackMasterChanges() {
993 // Always 0, but who knows.. :)
994 $masterIndex = $this->getWriterIndex();
995 foreach ( $this->mConns
as $conns2 ) {
996 if ( empty( $conns2[$masterIndex] ) ) {
999 /** @var DatabaseBase $conn */
1000 foreach ( $conns2[$masterIndex] as $conn ) {
1001 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1002 $conn->rollback( __METHOD__
, 'flush' );
1009 * @return bool Whether a master connection is already open
1012 public function hasMasterConnection() {
1013 return $this->isOpen( $this->getWriterIndex() );
1017 * Determine if there are any pending changes that need to be rolled back
1022 public function hasMasterChanges() {
1023 // Always 0, but who knows.. :)
1024 $masterIndex = $this->getWriterIndex();
1025 foreach ( $this->mConns
as $conns2 ) {
1026 if ( empty( $conns2[$masterIndex] ) ) {
1029 /** @var DatabaseBase $conn */
1030 foreach ( $conns2[$masterIndex] as $conn ) {
1031 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1040 * @param mixed $value
1043 public function waitTimeout( $value = null ) {
1044 return wfSetVar( $this->mWaitTimeout
, $value );
1050 public function getLaggedSlaveMode() {
1051 return $this->mLaggedSlaveMode
;
1055 * Disables/enables lag checks
1056 * @param null|bool $mode
1059 public function allowLagged( $mode = null ) {
1060 if ( $mode === null ) {
1061 return $this->mAllowLagged
;
1063 $this->mAllowLagged
= $mode;
1065 return $this->mAllowLagged
;
1071 public function pingAll() {
1073 foreach ( $this->mConns
as $conns2 ) {
1074 foreach ( $conns2 as $conns3 ) {
1075 /** @var DatabaseBase[] $conns3 */
1076 foreach ( $conns3 as $conn ) {
1077 if ( !$conn->ping() ) {
1088 * Call a function with each open connection object
1089 * @param callable $callback
1090 * @param array $params
1092 public function forEachOpenConnection( $callback, array $params = array() ) {
1093 foreach ( $this->mConns
as $conns2 ) {
1094 foreach ( $conns2 as $conns3 ) {
1095 foreach ( $conns3 as $conn ) {
1096 $mergedParams = array_merge( array( $conn ), $params );
1097 call_user_func_array( $callback, $mergedParams );
1104 * Get the hostname and lag time of the most-lagged slave
1106 * This is useful for maintenance scripts that need to throttle their updates.
1107 * May attempt to open connections to slaves on the default DB. If there is
1108 * no lag, the maximum lag will be reported as -1.
1110 * @param bool|string $wiki Wiki ID, or false for the default database
1111 * @return array ( host, max lag, index of max lagged host )
1113 public function getMaxLag( $wiki = false ) {
1118 if ( $this->getServerCount() <= 1 ) {
1119 return array( $host, $maxLag, $maxIndex ); // no replication = no lag
1122 $lagTimes = $this->getLagTimes( $wiki );
1123 foreach ( $lagTimes as $i => $lag ) {
1124 if ( $lag > $maxLag ) {
1126 $host = $this->mServers
[$i]['host'];
1131 return array( $host, $maxLag, $maxIndex );
1135 * Get lag time for each server
1137 * Results are cached for a short time in memcached/process cache
1139 * @param string|bool $wiki
1140 * @return int[] Map of (server index => seconds)
1142 public function getLagTimes( $wiki = false ) {
1143 if ( $this->getServerCount() <= 1 ) {
1144 return array( 0 => 0 ); // no replication = no lag
1147 if ( $this->mProcCache
->has( 'slave_lag', 'times', 1 ) ) {
1148 return $this->mProcCache
->get( 'slave_lag', 'times' );
1151 # Send the request to the load monitor
1152 $times = $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
1154 $this->mProcCache
->set( 'slave_lag', 'times', $times );
1160 * Get the lag in seconds for a given connection, or zero if this load
1161 * balancer does not have replication enabled.
1163 * This should be used in preference to Database::getLag() in cases where
1164 * replication may not be in use, since there is no way to determine if
1165 * replication is in use at the connection level without running
1166 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1167 * function instead of Database::getLag() avoids a fatal error in this
1168 * case on many installations.
1170 * @param DatabaseBase $conn
1173 public function safeGetLag( $conn ) {
1174 if ( $this->getServerCount() == 1 ) {
1177 return $conn->getLag();
1182 * Clear the cache for slag lag delay times
1184 public function clearLagTimeCache() {
1185 $this->mProcCache
->clear( 'slave_lag' );
1190 * Helper class to handle automatically marking connections as reusable (via RAII pattern)
1191 * as well handling deferring the actual network connection until the handle is used
1196 class DBConnRef
implements IDatabase
{
1197 /** @var LoadBalancer */
1200 /** @var DatabaseBase|null */
1203 /** @var array|null */
1207 * @param LoadBalancer $lb
1208 * @param DatabaseBase|array $conn Connection or (server index, group, wiki ID) array
1210 public function __construct( LoadBalancer
$lb, $conn ) {
1212 if ( $conn instanceof DatabaseBase
) {
1213 $this->conn
= $conn;
1215 $this->params
= $conn;
1219 public function __call( $name, $arguments ) {
1220 if ( $this->conn
=== null ) {
1221 list( $db, $groups, $wiki ) = $this->params
;
1222 $this->conn
= $this->lb
->getConnection( $db, $groups, $wiki );
1225 return call_user_func_array( array( $this->conn
, $name ), $arguments );
1228 public function __destruct() {
1229 if ( $this->conn
!== null ) {
1230 $this->lb
->reuseConnection( $this->conn
);