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 $this->mWaitForPos
= $pos;
344 $i = $this->mReadIndex
;
347 if ( !$this->doWait( $i ) ) {
348 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
349 $this->mLaggedSlaveMode
= true;
355 * Set the master wait position and wait for ALL slaves to catch up to it
356 * @param DBMasterPos $pos
357 * @param int $timeout Max seconds to wait; default is mWaitTimeout
358 * @return bool Success (able to connect and no timeouts reached)
360 public function waitForAll( $pos, $timeout = null ) {
361 $this->mWaitForPos
= $pos;
362 $serverCount = count( $this->mServers
);
365 for ( $i = 1; $i < $serverCount; $i++
) {
366 if ( $this->mLoads
[$i] > 0 ) {
367 $ok = $this->doWait( $i, true, $timeout ) && $ok;
375 * Get any open connection to a given server index, local or foreign
376 * Returns false if there is no connection open
379 * @return DatabaseBase|bool False on failure
381 public function getAnyOpenConnection( $i ) {
382 foreach ( $this->mConns
as $conns ) {
383 if ( !empty( $conns[$i] ) ) {
384 return reset( $conns[$i] );
392 * Wait for a given slave to catch up to the master pos stored in $this
393 * @param int $index Server index
394 * @param bool $open Check the server even if a new connection has to be made
395 * @param int $timeout Max seconds to wait; default is mWaitTimeout
398 protected function doWait( $index, $open = false, $timeout = null ) {
399 $close = false; // close the connection afterwards
401 # Find a connection to wait on, creating one if needed and allowed
402 $conn = $this->getAnyOpenConnection( $index );
405 wfDebug( __METHOD__
. ": no connection open\n" );
409 $conn = $this->openConnection( $index, '' );
411 wfDebug( __METHOD__
. ": failed to open connection\n" );
415 // Avoid connection spam in waitForAll() when connections
416 // are made just for the sake of doing this lag check.
421 wfDebug( __METHOD__
. ": Waiting for slave #$index to catch up...\n" );
422 $timeout = $timeout ?
: $this->mWaitTimeout
;
423 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
425 if ( $result == -1 ||
is_null( $result ) ) {
426 # Timed out waiting for slave, use master instead
427 $server = $this->mServers
[$index]['host'];
428 $msg = __METHOD__
. ": Timed out waiting on $server pos {$this->mWaitForPos}";
430 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
433 wfDebug( __METHOD__
. ": Done\n" );
438 $this->closeConnection( $conn );
445 * Get a connection by index
446 * This is the main entry point for this class.
448 * @param int $i Server index
449 * @param array|string|bool $groups Query group(s), or false for the generic reader
450 * @param string|bool $wiki Wiki ID, or false for the current wiki
452 * @throws MWException
453 * @return DatabaseBase
455 public function getConnection( $i, $groups = array(), $wiki = false ) {
456 if ( $i === null ||
$i === false ) {
457 throw new MWException( 'Attempt to call ' . __METHOD__
.
458 ' with invalid server index' );
461 if ( $wiki === wfWikiID() ) {
465 $groups = ( $groups === false ||
$groups === array() )
466 ?
array( false ) // check one "group": the generic pool
469 if ( $i == DB_MASTER
) {
470 $i = $this->getWriterIndex();
472 # Try to find an available server in any the query groups (in order)
473 foreach ( $groups as $group ) {
474 $groupIndex = $this->getReaderIndex( $group, $wiki );
475 if ( $groupIndex !== false ) {
476 $serverName = $this->getServerName( $groupIndex );
477 wfDebug( __METHOD__
. ": using server $serverName for group $group\n" );
484 # Operation-based index
485 if ( $i == DB_SLAVE
) {
486 $this->mLastError
= 'Unknown error'; // reset error string
487 # Try the general server pool if $groups are unavailable.
488 $i = in_array( false, $groups, true )
489 ?
false // don't bother with this if that is what was tried above
490 : $this->getReaderIndex( false, $wiki );
491 # Couldn't find a working server in getReaderIndex()?
492 if ( $i === false ) {
493 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
495 return $this->reportConnectionError();
499 # Now we have an explicit index into the servers array
500 $conn = $this->openConnection( $i, $wiki );
503 return $this->reportConnectionError();
511 * Mark a foreign connection as being available for reuse under a different
512 * DB name or prefix. This mechanism is reference-counted, and must be called
513 * the same number of times as getConnection() to work.
515 * @param DatabaseBase $conn
516 * @throws MWException
518 public function reuseConnection( $conn ) {
519 $serverIndex = $conn->getLBInfo( 'serverIndex' );
520 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
521 if ( $serverIndex === null ||
$refCount === null ) {
522 wfDebug( __METHOD__
. ": this connection was not opened as a foreign connection\n" );
525 * This can happen in code like:
526 * foreach ( $dbs as $db ) {
527 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
529 * $lb->reuseConnection( $conn );
531 * When a connection to the local DB is opened in this way, reuseConnection()
538 $dbName = $conn->getDBname();
539 $prefix = $conn->tablePrefix();
540 if ( strval( $prefix ) !== '' ) {
541 $wiki = "$dbName-$prefix";
545 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
546 throw new MWException( __METHOD__
. ": connection not found, has " .
547 "the connection been freed already?" );
549 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
550 if ( $refCount <= 0 ) {
551 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
552 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
553 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
555 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
560 * Get a database connection handle reference
562 * The handle's methods wrap simply wrap those of a DatabaseBase handle
564 * @see LoadBalancer::getConnection() for parameter information
567 * @param array|string|bool $groups Query group(s), or false for the generic reader
568 * @param string|bool $wiki Wiki ID, or false for the current wiki
571 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
572 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
576 * Get a database connection handle reference without connecting yet
578 * The handle's methods wrap simply wrap those of a DatabaseBase handle
580 * @see LoadBalancer::getConnection() for parameter information
583 * @param array|string|bool $groups Query group(s), or false for the generic reader
584 * @param string|bool $wiki Wiki ID, or false for the current wiki
587 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
588 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
592 * Open a connection to the server given by the specified index
593 * Index must be an actual index into the array.
594 * If the server is already open, returns it.
596 * On error, returns false, and the connection which caused the
597 * error will be available via $this->mErrorConnection.
599 * @param int $i Server index
600 * @param string|bool $wiki Wiki ID, or false for the current wiki
601 * @return DatabaseBase
605 public function openConnection( $i, $wiki = false ) {
606 if ( $wiki !== false ) {
607 $conn = $this->openForeignConnection( $i, $wiki );
611 if ( isset( $this->mConns
['local'][$i][0] ) ) {
612 $conn = $this->mConns
['local'][$i][0];
614 $server = $this->mServers
[$i];
615 $server['serverIndex'] = $i;
616 $conn = $this->reallyOpenConnection( $server, false );
617 if ( $conn->isOpen() ) {
618 wfDebug( "Connected to database $i at {$this->mServers[$i]['host']}\n" );
619 $this->mConns
['local'][$i][0] = $conn;
621 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
622 $this->mErrorConnection
= $conn;
631 * Open a connection to a foreign DB, or return one if it is already open.
633 * Increments a reference count on the returned connection which locks the
634 * connection to the requested wiki. This reference count can be
635 * decremented by calling reuseConnection().
637 * If a connection is open to the appropriate server already, but with the wrong
638 * database, it will be switched to the right database and returned, as long as
639 * it has been freed first with reuseConnection().
641 * On error, returns false, and the connection which caused the
642 * error will be available via $this->mErrorConnection.
644 * @param int $i Server index
645 * @param string $wiki Wiki ID to open
646 * @return DatabaseBase
648 private function openForeignConnection( $i, $wiki ) {
649 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
650 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
651 // Reuse an already-used connection
652 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
653 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
654 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
655 // Reuse a free connection for the same wiki
656 $conn = $this->mConns
['foreignFree'][$i][$wiki];
657 unset( $this->mConns
['foreignFree'][$i][$wiki] );
658 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
659 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
660 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
661 // Reuse a connection from another wiki
662 $conn = reset( $this->mConns
['foreignFree'][$i] );
663 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
665 // The empty string as a DB name means "don't care".
666 // DatabaseMysqlBase::open() already handle this on connection.
667 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
668 $this->mLastError
= "Error selecting database $dbName on server " .
669 $conn->getServer() . " from client host " . wfHostname() . "\n";
670 $this->mErrorConnection
= $conn;
673 $conn->tablePrefix( $prefix );
674 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
675 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
676 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
679 // Open a new connection
680 $server = $this->mServers
[$i];
681 $server['serverIndex'] = $i;
682 $server['foreignPoolRefCount'] = 0;
683 $server['foreign'] = true;
684 $conn = $this->reallyOpenConnection( $server, $dbName );
685 if ( !$conn->isOpen() ) {
686 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
687 $this->mErrorConnection
= $conn;
690 $conn->tablePrefix( $prefix );
691 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
692 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
696 // Increment reference count
698 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
699 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
706 * Test if the specified index represents an open connection
708 * @param int $index Server index
712 private function isOpen( $index ) {
713 if ( !is_integer( $index ) ) {
717 return (bool)$this->getAnyOpenConnection( $index );
721 * Really opens a connection. Uncached.
722 * Returns a Database object whether or not the connection was successful.
725 * @param array $server
726 * @param bool $dbNameOverride
727 * @throws MWException
728 * @return DatabaseBase
730 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
731 if ( !is_array( $server ) ) {
732 throw new MWException( 'You must update your load-balancing configuration. ' .
733 'See DefaultSettings.php entry for $wgDBservers.' );
736 if ( $dbNameOverride !== false ) {
737 $server['dbname'] = $dbNameOverride;
742 $db = DatabaseBase
::factory( $server['type'], $server );
743 } catch ( DBConnectionError
$e ) {
744 // FIXME: This is probably the ugliest thing I have ever done to
745 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
749 $db->setLBInfo( $server );
750 if ( isset( $server['fakeSlaveLag'] ) ) {
751 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
753 if ( isset( $server['fakeMaster'] ) ) {
754 $db->setFakeMaster( true );
761 * @throws DBConnectionError
764 private function reportConnectionError() {
765 $conn = $this->mErrorConnection
; // The connection which caused the error
767 'method' => __METHOD__
,
768 'last_error' => $this->mLastError
,
771 if ( !is_object( $conn ) ) {
772 // No last connection, probably due to all servers being too busy
774 "LB failure with no last connection. Connection error: {last_error}",
778 // If all servers were busy, mLastError will contain something sensible
779 throw new DBConnectionError( null, $this->mLastError
);
781 $context['db_server'] = $conn->getProperty( 'mServer' );
783 "Connection error: {last_error} ({db_server})",
786 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" ); // throws DBConnectionError
789 return false; /* not reached */
795 private function getWriterIndex() {
800 * Returns true if the specified index is a valid server index
805 public function haveIndex( $i ) {
806 return array_key_exists( $i, $this->mServers
);
810 * Returns true if the specified index is valid and has non-zero load
815 public function isNonZeroLoad( $i ) {
816 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
820 * Get the number of defined servers (not the number of open connections)
824 public function getServerCount() {
825 return count( $this->mServers
);
829 * Get the host name or IP address of the server with the specified index
830 * Prefer a readable name if available.
834 public function getServerName( $i ) {
835 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
836 return $this->mServers
[$i]['hostName'];
837 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
838 return $this->mServers
[$i]['host'];
845 * Return the server info structure for a given index, or false if the index is invalid.
849 public function getServerInfo( $i ) {
850 if ( isset( $this->mServers
[$i] ) ) {
851 return $this->mServers
[$i];
858 * Sets the server info structure for the given index. Entry at index $i
859 * is created if it doesn't exist
861 * @param array $serverInfo
863 public function setServerInfo( $i, array $serverInfo ) {
864 $this->mServers
[$i] = $serverInfo;
868 * Get the current master position for chronology control purposes
871 public function getMasterPos() {
872 # If this entire request was served from a slave without opening a connection to the
873 # master (however unlikely that may be), then we can fetch the position from the slave.
874 $masterConn = $this->getAnyOpenConnection( 0 );
875 if ( !$masterConn ) {
876 $serverCount = count( $this->mServers
);
877 for ( $i = 1; $i < $serverCount; $i++
) {
878 $conn = $this->getAnyOpenConnection( $i );
880 wfDebug( "Master pos fetched from slave\n" );
882 return $conn->getSlavePos();
886 wfDebug( "Master pos fetched from master\n" );
888 return $masterConn->getMasterPos();
895 * Close all open connections
897 public function closeAll() {
898 foreach ( $this->mConns
as $conns2 ) {
899 foreach ( $conns2 as $conns3 ) {
900 /** @var DatabaseBase $conn */
901 foreach ( $conns3 as $conn ) {
906 $this->mConns
= array(
908 'foreignFree' => array(),
909 'foreignUsed' => array(),
915 * Using this function makes sure the LoadBalancer knows the connection is closed.
916 * If you use $conn->close() directly, the load balancer won't update its state.
917 * @param DatabaseBase $conn
919 public function closeConnection( $conn ) {
921 foreach ( $this->mConns
as $i1 => $conns2 ) {
922 foreach ( $conns2 as $i2 => $conns3 ) {
923 foreach ( $conns3 as $i3 => $candidateConn ) {
924 if ( $conn === $candidateConn ) {
926 unset( $this->mConns
[$i1][$i2][$i3] );
939 * Commit transactions on all open connections
941 public function commitAll() {
942 foreach ( $this->mConns
as $conns2 ) {
943 foreach ( $conns2 as $conns3 ) {
944 /** @var DatabaseBase[] $conns3 */
945 foreach ( $conns3 as $conn ) {
946 if ( $conn->trxLevel() ) {
947 $conn->commit( __METHOD__
, 'flush' );
955 * Issue COMMIT only on master, only if queries were done on connection
957 public function commitMasterChanges() {
958 // Always 0, but who knows.. :)
959 $masterIndex = $this->getWriterIndex();
960 foreach ( $this->mConns
as $conns2 ) {
961 if ( empty( $conns2[$masterIndex] ) ) {
964 /** @var DatabaseBase $conn */
965 foreach ( $conns2[$masterIndex] as $conn ) {
966 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
967 $conn->commit( __METHOD__
, 'flush' );
974 * Issue ROLLBACK only on master, only if queries were done on connection
977 public function rollbackMasterChanges() {
978 // Always 0, but who knows.. :)
979 $masterIndex = $this->getWriterIndex();
980 foreach ( $this->mConns
as $conns2 ) {
981 if ( empty( $conns2[$masterIndex] ) ) {
984 /** @var DatabaseBase $conn */
985 foreach ( $conns2[$masterIndex] as $conn ) {
986 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
987 $conn->rollback( __METHOD__
, 'flush' );
994 * @return bool Whether a master connection is already open
997 public function hasMasterConnection() {
998 return $this->isOpen( $this->getWriterIndex() );
1002 * Determine if there are any pending changes that need to be rolled back
1007 public function hasMasterChanges() {
1008 // Always 0, but who knows.. :)
1009 $masterIndex = $this->getWriterIndex();
1010 foreach ( $this->mConns
as $conns2 ) {
1011 if ( empty( $conns2[$masterIndex] ) ) {
1014 /** @var DatabaseBase $conn */
1015 foreach ( $conns2[$masterIndex] as $conn ) {
1016 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1025 * @param mixed $value
1028 public function waitTimeout( $value = null ) {
1029 return wfSetVar( $this->mWaitTimeout
, $value );
1035 public function getLaggedSlaveMode() {
1036 return $this->mLaggedSlaveMode
;
1040 * Disables/enables lag checks
1041 * @param null|bool $mode
1044 public function allowLagged( $mode = null ) {
1045 if ( $mode === null ) {
1046 return $this->mAllowLagged
;
1048 $this->mAllowLagged
= $mode;
1050 return $this->mAllowLagged
;
1056 public function pingAll() {
1058 foreach ( $this->mConns
as $conns2 ) {
1059 foreach ( $conns2 as $conns3 ) {
1060 /** @var DatabaseBase[] $conns3 */
1061 foreach ( $conns3 as $conn ) {
1062 if ( !$conn->ping() ) {
1073 * Call a function with each open connection object
1074 * @param callable $callback
1075 * @param array $params
1077 public function forEachOpenConnection( $callback, array $params = array() ) {
1078 foreach ( $this->mConns
as $conns2 ) {
1079 foreach ( $conns2 as $conns3 ) {
1080 foreach ( $conns3 as $conn ) {
1081 $mergedParams = array_merge( array( $conn ), $params );
1082 call_user_func_array( $callback, $mergedParams );
1089 * Get the hostname and lag time of the most-lagged slave
1091 * This is useful for maintenance scripts that need to throttle their updates.
1092 * May attempt to open connections to slaves on the default DB. If there is
1093 * no lag, the maximum lag will be reported as -1.
1095 * @param bool|string $wiki Wiki ID, or false for the default database
1096 * @return array ( host, max lag, index of max lagged host )
1098 public function getMaxLag( $wiki = false ) {
1103 if ( $this->getServerCount() <= 1 ) {
1104 return array( $host, $maxLag, $maxIndex ); // no replication = no lag
1107 $lagTimes = $this->getLagTimes( $wiki );
1108 foreach ( $lagTimes as $i => $lag ) {
1109 if ( $lag > $maxLag ) {
1111 $host = $this->mServers
[$i]['host'];
1116 return array( $host, $maxLag, $maxIndex );
1120 * Get lag time for each server
1122 * Results are cached for a short time in memcached/process cache
1124 * @param string|bool $wiki
1125 * @return int[] Map of (server index => seconds)
1127 public function getLagTimes( $wiki = false ) {
1128 if ( $this->getServerCount() <= 1 ) {
1129 return array( 0 => 0 ); // no replication = no lag
1132 if ( $this->mProcCache
->has( 'slave_lag', 'times', 1 ) ) {
1133 return $this->mProcCache
->get( 'slave_lag', 'times' );
1136 # Send the request to the load monitor
1137 $times = $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
1139 $this->mProcCache
->set( 'slave_lag', 'times', $times );
1145 * Get the lag in seconds for a given connection, or zero if this load
1146 * balancer does not have replication enabled.
1148 * This should be used in preference to Database::getLag() in cases where
1149 * replication may not be in use, since there is no way to determine if
1150 * replication is in use at the connection level without running
1151 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1152 * function instead of Database::getLag() avoids a fatal error in this
1153 * case on many installations.
1155 * @param DatabaseBase $conn
1158 public function safeGetLag( $conn ) {
1159 if ( $this->getServerCount() == 1 ) {
1162 return $conn->getLag();
1167 * Clear the cache for slag lag delay times
1169 public function clearLagTimeCache() {
1170 $this->mProcCache
->clear( 'slave_lag' );
1175 * Helper class to handle automatically marking connections as reusable (via RAII pattern)
1176 * as well handling deferring the actual network connection until the handle is used
1181 class DBConnRef
implements IDatabase
{
1182 /** @var LoadBalancer */
1185 /** @var DatabaseBase|null */
1188 /** @var array|null */
1192 * @param LoadBalancer $lb
1193 * @param DatabaseBase|array $conn Connection or (server index, group, wiki ID) array
1195 public function __construct( LoadBalancer
$lb, $conn ) {
1197 if ( $conn instanceof DatabaseBase
) {
1198 $this->conn
= $conn;
1200 $this->params
= $conn;
1204 public function __call( $name, $arguments ) {
1205 if ( $this->conn
=== null ) {
1206 list( $db, $groups, $wiki ) = $this->params
;
1207 $this->conn
= $this->lb
->getConnection( $db, $groups, $wiki );
1210 return call_user_func_array( array( $this->conn
, $name ), $arguments );
1213 public function __destruct() {
1214 if ( $this->conn
!== null ) {
1215 $this->lb
->reuseConnection( $this->conn
);