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 $laggedSlaveMode = false;
59 /** @var bool Whether the generic reader fell back to a lagged slave */
60 private $slavesDownMode = false;
61 /** @var string The last DB selection or connection error */
62 private $mLastError = 'Unknown error';
63 /** @var string|bool Reason the LB is read-only or false if not */
64 private $readOnlyReason = false;
65 /** @var integer Total connections opened */
66 private $connsOpened = 0;
68 /** @var integer Warn when this many connection are held */
69 const CONN_HELD_WARN_THRESHOLD
= 10;
70 /** @var integer Default 'max lag' when unspecified */
74 * @param array $params Array with keys:
75 * - servers : Required. Array of server info structures.
76 * - loadMonitor : Name of a class used to fetch server lag and load.
77 * - readOnlyReason : Reason the master DB is read-only if so [optional]
80 public function __construct( array $params ) {
81 if ( !isset( $params['servers'] ) ) {
82 throw new MWException( __CLASS__
. ': missing servers parameter' );
84 $this->mServers
= $params['servers'];
85 $this->mWaitTimeout
= 10;
87 $this->mReadIndex
= -1;
88 $this->mWriteIndex
= -1;
89 $this->mConns
= array(
91 'foreignUsed' => array(),
92 'foreignFree' => array() );
93 $this->mLoads
= array();
94 $this->mWaitForPos
= false;
95 $this->mErrorConnection
= false;
96 $this->mAllowLagged
= false;
98 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
99 $this->readOnlyReason
= $params['readOnlyReason'];
102 if ( isset( $params['loadMonitor'] ) ) {
103 $this->mLoadMonitorClass
= $params['loadMonitor'];
105 $master = reset( $params['servers'] );
106 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
107 $this->mLoadMonitorClass
= 'LoadMonitorMySQL';
109 $this->mLoadMonitorClass
= 'LoadMonitorNull';
113 foreach ( $params['servers'] as $i => $server ) {
114 $this->mLoads
[$i] = $server['load'];
115 if ( isset( $server['groupLoads'] ) ) {
116 foreach ( $server['groupLoads'] as $group => $ratio ) {
117 if ( !isset( $this->mGroupLoads
[$group] ) ) {
118 $this->mGroupLoads
[$group] = array();
120 $this->mGroupLoads
[$group][$i] = $ratio;
127 * Get a LoadMonitor instance
129 * @return LoadMonitor
131 private function getLoadMonitor() {
132 if ( !isset( $this->mLoadMonitor
) ) {
133 $class = $this->mLoadMonitorClass
;
134 $this->mLoadMonitor
= new $class( $this );
137 return $this->mLoadMonitor
;
141 * Get or set arbitrary data used by the parent object, usually an LBFactory
145 public function parentInfo( $x = null ) {
146 return wfSetVar( $this->mParentInfo
, $x );
150 * Given an array of non-normalised probabilities, this function will select
151 * an element and return the appropriate key
153 * @deprecated since 1.21, use ArrayUtils::pickRandom()
155 * @param array $weights
156 * @return bool|int|string
158 public function pickRandom( array $weights ) {
159 return ArrayUtils
::pickRandom( $weights );
163 * @param array $loads
164 * @param bool|string $wiki Wiki to get non-lagged for
165 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
166 * @return bool|int|string
168 private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = self
::MAX_LAG
) {
169 $lags = $this->getLagTimes( $wiki );
171 # Unset excessively lagged servers
172 foreach ( $lags as $i => $lag ) {
174 $maxServerLag = $maxLag;
175 if ( isset( $this->mServers
[$i]['max lag'] ) ) {
176 $maxServerLag = min( $maxServerLag, $this->mServers
[$i]['max lag'] );
178 if ( $lag === false ) {
179 wfDebugLog( 'replication', "Server #$i is not replicating" );
181 } elseif ( $lag > $maxServerLag ) {
182 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)" );
188 # Find out if all the slaves with non-zero load are lagged
190 foreach ( $loads as $load ) {
194 # No appropriate DB servers except maybe the master and some slaves with zero load
195 # Do NOT use the master
196 # Instead, this function will return false, triggering read-only mode,
197 # and a lagged slave will be used instead.
201 if ( count( $loads ) == 0 ) {
205 # wfDebugLog( 'connect', var_export( $loads, true ) );
207 # Return a random representative of the remainder
208 return ArrayUtils
::pickRandom( $loads );
212 * Get the index of the reader connection, which may be a slave
213 * This takes into account load ratios and lag times. It should
214 * always return a consistent index during a given invocation
216 * Side effect: opens connections to databases
217 * @param string|bool $group Query group, or false for the generic reader
218 * @param string|bool $wiki Wiki ID, or false for the current wiki
219 * @throws MWException
220 * @return bool|int|string
222 public function getReaderIndex( $group = false, $wiki = false ) {
225 # @todo FIXME: For now, only go through all this for mysql databases
226 if ( $wgDBtype != 'mysql' ) {
227 return $this->getWriterIndex();
230 if ( count( $this->mServers
) == 1 ) {
231 # Skip the load balancing if there's only one server
233 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
234 # Shortcut if generic reader exists already
235 return $this->mReadIndex
;
238 # Find the relevant load array
239 if ( $group !== false ) {
240 if ( isset( $this->mGroupLoads
[$group] ) ) {
241 $nonErrorLoads = $this->mGroupLoads
[$group];
243 # No loads for this group, return false and the caller can use some other group
244 wfDebug( __METHOD__
. ": no loads for group $group\n" );
249 $nonErrorLoads = $this->mLoads
;
252 if ( !count( $nonErrorLoads ) ) {
253 throw new MWException( "Empty server array given to LoadBalancer" );
256 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
257 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
259 $laggedSlaveMode = false;
261 # No server found yet
264 # First try quickly looking through the available servers for a server that
266 $currentLoads = $nonErrorLoads;
267 while ( count( $currentLoads ) ) {
268 if ( $this->mAllowLagged ||
$laggedSlaveMode ) {
269 $i = ArrayUtils
::pickRandom( $currentLoads );
272 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
273 # ChronologyProtecter causes mWaitForPos to be set via sessions.
274 # This triggers doWait() after connect, so it's especially good to
275 # avoid lagged servers so as to avoid just blocking in that method.
276 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
277 # Aim for <= 1 second of waiting (being too picky can backfire)
278 $i = $this->getRandomNonLagged( $currentLoads, $wiki, $ago +
1 );
280 if ( $i === false ) {
281 # Any server with less lag than it's 'max lag' param is preferable
282 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
284 if ( $i === false && count( $currentLoads ) != 0 ) {
285 # All slaves lagged. Switch to read-only mode
286 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode" );
287 $i = ArrayUtils
::pickRandom( $currentLoads );
288 $laggedSlaveMode = true;
292 if ( $i === false ) {
293 # pickRandom() returned false
294 # This is permanent and means the configuration or the load monitor
295 # wants us to return false.
296 wfDebugLog( 'connect', __METHOD__
. ": pickRandom() returned false" );
301 $serverName = $this->getServerName( $i );
302 wfDebugLog( 'connect', __METHOD__
. ": Using reader #$i: $serverName..." );
304 $conn = $this->openConnection( $i, $wiki );
306 wfDebugLog( 'connect', __METHOD__
. ": Failed connecting to $i/$wiki" );
307 unset( $nonErrorLoads[$i] );
308 unset( $currentLoads[$i] );
313 // Decrement reference counter, we are finished with this connection.
314 // It will be incremented for the caller later.
315 if ( $wiki !== false ) {
316 $this->reuseConnection( $conn );
323 # If all servers were down, quit now
324 if ( !count( $nonErrorLoads ) ) {
325 wfDebugLog( 'connect', "All servers down" );
328 if ( $i !== false ) {
329 # Slave connection successful
330 # Wait for the session master pos for a short time
331 if ( $this->mWaitForPos
&& $i > 0 ) {
332 if ( !$this->doWait( $i ) ) {
333 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
336 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
337 $this->mReadIndex
= $i;
338 # Record if the generic reader index is in "lagged slave" mode
339 if ( $laggedSlaveMode ) {
340 $this->laggedSlaveMode
= true;
343 $serverName = $this->getServerName( $i );
344 wfDebug( __METHOD__
. ": using server $serverName for group '$group'\n" );
351 * Set the master wait position
352 * If a DB_SLAVE connection has been opened already, waits
353 * Otherwise sets a variable telling it to wait if such a connection is opened
354 * @param DBMasterPos $pos
356 public function waitFor( $pos ) {
357 $this->mWaitForPos
= $pos;
358 $i = $this->mReadIndex
;
361 if ( !$this->doWait( $i ) ) {
362 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
363 $this->laggedSlaveMode
= true;
369 * Set the master wait position and wait for a "generic" slave to catch up to it
371 * This can be used a faster proxy for waitForAll()
373 * @param DBMasterPos $pos
374 * @param int $timeout Max seconds to wait; default is mWaitTimeout
375 * @return bool Success (able to connect and no timeouts reached)
378 public function waitForOne( $pos, $timeout = null ) {
379 $this->mWaitForPos
= $pos;
381 $i = $this->mReadIndex
;
383 // Pick a generic slave if there isn't one yet
384 $readLoads = $this->mLoads
;
385 unset( $readLoads[$this->getWriterIndex()] ); // slaves only
386 $readLoads = array_filter( $readLoads ); // with non-zero load
387 $i = ArrayUtils
::pickRandom( $readLoads );
391 $ok = $this->doWait( $i, true, $timeout );
393 $ok = true; // no applicable loads
400 * Set the master wait position and wait for ALL slaves to catch up to it
401 * @param DBMasterPos $pos
402 * @param int $timeout Max seconds to wait; default is mWaitTimeout
403 * @return bool Success (able to connect and no timeouts reached)
405 public function waitForAll( $pos, $timeout = null ) {
406 $this->mWaitForPos
= $pos;
407 $serverCount = count( $this->mServers
);
410 for ( $i = 1; $i < $serverCount; $i++
) {
411 if ( $this->mLoads
[$i] > 0 ) {
412 $ok = $this->doWait( $i, true, $timeout ) && $ok;
420 * Get any open connection to a given server index, local or foreign
421 * Returns false if there is no connection open
424 * @return DatabaseBase|bool False on failure
426 public function getAnyOpenConnection( $i ) {
427 foreach ( $this->mConns
as $conns ) {
428 if ( !empty( $conns[$i] ) ) {
429 return reset( $conns[$i] );
437 * Wait for a given slave to catch up to the master pos stored in $this
438 * @param int $index Server index
439 * @param bool $open Check the server even if a new connection has to be made
440 * @param int $timeout Max seconds to wait; default is mWaitTimeout
443 protected function doWait( $index, $open = false, $timeout = null ) {
444 $close = false; // close the connection afterwards
446 # Find a connection to wait on, creating one if needed and allowed
447 $conn = $this->getAnyOpenConnection( $index );
450 wfDebug( __METHOD__
. ": no connection open\n" );
454 $conn = $this->openConnection( $index, '' );
456 wfDebug( __METHOD__
. ": failed to open connection\n" );
460 // Avoid connection spam in waitForAll() when connections
461 // are made just for the sake of doing this lag check.
466 wfDebug( __METHOD__
. ": Waiting for slave #$index to catch up...\n" );
467 $timeout = $timeout ?
: $this->mWaitTimeout
;
468 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
470 if ( $result == -1 ||
is_null( $result ) ) {
471 # Timed out waiting for slave, use master instead
472 $server = $server = $this->getServerName( $index );
473 $msg = __METHOD__
. ": Timed out waiting on $server pos {$this->mWaitForPos}";
475 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
478 wfDebug( __METHOD__
. ": Done\n" );
483 $this->closeConnection( $conn );
490 * Get a connection by index
491 * This is the main entry point for this class.
493 * @param int $i Server index
494 * @param array|string|bool $groups Query group(s), or false for the generic reader
495 * @param string|bool $wiki Wiki ID, or false for the current wiki
497 * @throws MWException
498 * @return DatabaseBase
500 public function getConnection( $i, $groups = array(), $wiki = false ) {
501 if ( $i === null ||
$i === false ) {
502 throw new MWException( 'Attempt to call ' . __METHOD__
.
503 ' with invalid server index' );
506 if ( $wiki === wfWikiID() ) {
510 $groups = ( $groups === false ||
$groups === array() )
511 ?
array( false ) // check one "group": the generic pool
514 $masterOnly = ( $i == DB_MASTER ||
$i == $this->getWriterIndex() );
515 $oldConnsOpened = $this->connsOpened
; // connections open now
517 if ( $i == DB_MASTER
) {
518 $i = $this->getWriterIndex();
520 # Try to find an available server in any the query groups (in order)
521 foreach ( $groups as $group ) {
522 $groupIndex = $this->getReaderIndex( $group, $wiki );
523 if ( $groupIndex !== false ) {
530 # Operation-based index
531 if ( $i == DB_SLAVE
) {
532 $this->mLastError
= 'Unknown error'; // reset error string
533 # Try the general server pool if $groups are unavailable.
534 $i = in_array( false, $groups, true )
535 ?
false // don't bother with this if that is what was tried above
536 : $this->getReaderIndex( false, $wiki );
537 # Couldn't find a working server in getReaderIndex()?
538 if ( $i === false ) {
539 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
541 return $this->reportConnectionError();
545 # Now we have an explicit index into the servers array
546 $conn = $this->openConnection( $i, $wiki );
548 return $this->reportConnectionError();
551 # Profile any new connections that happen
552 if ( $this->connsOpened
> $oldConnsOpened ) {
553 $host = $conn->getServer();
554 $dbname = $conn->getDBname();
555 $trxProf = Profiler
::instance()->getTransactionProfiler();
556 $trxProf->recordConnection( $host, $dbname, $masterOnly );
560 # Make master-requested DB handles inherit any read-only mode setting
561 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $wiki ) );
568 * Mark a foreign connection as being available for reuse under a different
569 * DB name or prefix. This mechanism is reference-counted, and must be called
570 * the same number of times as getConnection() to work.
572 * @param DatabaseBase $conn
573 * @throws MWException
575 public function reuseConnection( $conn ) {
576 $serverIndex = $conn->getLBInfo( 'serverIndex' );
577 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
578 if ( $serverIndex === null ||
$refCount === null ) {
579 wfDebug( __METHOD__
. ": this connection was not opened as a foreign connection\n" );
582 * This can happen in code like:
583 * foreach ( $dbs as $db ) {
584 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
586 * $lb->reuseConnection( $conn );
588 * When a connection to the local DB is opened in this way, reuseConnection()
595 $dbName = $conn->getDBname();
596 $prefix = $conn->tablePrefix();
597 if ( strval( $prefix ) !== '' ) {
598 $wiki = "$dbName-$prefix";
602 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
603 throw new MWException( __METHOD__
. ": connection not found, has " .
604 "the connection been freed already?" );
606 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
607 if ( $refCount <= 0 ) {
608 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
609 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
610 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
612 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
617 * Get a database connection handle reference
619 * The handle's methods wrap simply wrap those of a DatabaseBase handle
621 * @see LoadBalancer::getConnection() for parameter information
624 * @param array|string|bool $groups Query group(s), or false for the generic reader
625 * @param string|bool $wiki Wiki ID, or false for the current wiki
628 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
629 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
633 * Get a database connection handle reference without connecting yet
635 * The handle's methods wrap simply wrap those of a DatabaseBase handle
637 * @see LoadBalancer::getConnection() for parameter information
640 * @param array|string|bool $groups Query group(s), or false for the generic reader
641 * @param string|bool $wiki Wiki ID, or false for the current wiki
644 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
645 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
649 * Open a connection to the server given by the specified index
650 * Index must be an actual index into the array.
651 * If the server is already open, returns it.
653 * On error, returns false, and the connection which caused the
654 * error will be available via $this->mErrorConnection.
656 * @param int $i Server index
657 * @param string|bool $wiki Wiki ID, or false for the current wiki
658 * @return DatabaseBase
662 public function openConnection( $i, $wiki = false ) {
663 if ( $wiki !== false ) {
664 $conn = $this->openForeignConnection( $i, $wiki );
665 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
666 $conn = $this->mConns
['local'][$i][0];
668 $server = $this->mServers
[$i];
669 $server['serverIndex'] = $i;
670 $conn = $this->reallyOpenConnection( $server, false );
671 $serverName = $this->getServerName( $i );
672 if ( $conn->isOpen() ) {
673 wfDebug( "Connected to database $i at $serverName\n" );
674 $this->mConns
['local'][$i][0] = $conn;
676 wfDebug( "Failed to connect to database $i at $serverName\n" );
677 $this->mErrorConnection
= $conn;
682 if ( $conn && !$conn->isOpen() ) {
683 // Connection was made but later unrecoverably lost for some reason.
684 // Do not return a handle that will just throw exceptions on use,
685 // but let the calling code (e.g. getReaderIndex) try another server.
686 // See DatabaseMyslBase::ping() for how this can happen.
687 $this->mErrorConnection
= $conn;
695 * Open a connection to a foreign DB, or return one if it is already open.
697 * Increments a reference count on the returned connection which locks the
698 * connection to the requested wiki. This reference count can be
699 * decremented by calling reuseConnection().
701 * If a connection is open to the appropriate server already, but with the wrong
702 * database, it will be switched to the right database and returned, as long as
703 * it has been freed first with reuseConnection().
705 * On error, returns false, and the connection which caused the
706 * error will be available via $this->mErrorConnection.
708 * @param int $i Server index
709 * @param string $wiki Wiki ID to open
710 * @return DatabaseBase
712 private function openForeignConnection( $i, $wiki ) {
713 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
714 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
715 // Reuse an already-used connection
716 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
717 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
718 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
719 // Reuse a free connection for the same wiki
720 $conn = $this->mConns
['foreignFree'][$i][$wiki];
721 unset( $this->mConns
['foreignFree'][$i][$wiki] );
722 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
723 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
724 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
725 // Reuse a connection from another wiki
726 $conn = reset( $this->mConns
['foreignFree'][$i] );
727 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
729 // The empty string as a DB name means "don't care".
730 // DatabaseMysqlBase::open() already handle this on connection.
731 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
732 $this->mLastError
= "Error selecting database $dbName on server " .
733 $conn->getServer() . " from client host " . wfHostname() . "\n";
734 $this->mErrorConnection
= $conn;
737 $conn->tablePrefix( $prefix );
738 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
739 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
740 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
743 // Open a new connection
744 $server = $this->mServers
[$i];
745 $server['serverIndex'] = $i;
746 $server['foreignPoolRefCount'] = 0;
747 $server['foreign'] = true;
748 $conn = $this->reallyOpenConnection( $server, $dbName );
749 if ( !$conn->isOpen() ) {
750 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
751 $this->mErrorConnection
= $conn;
754 $conn->tablePrefix( $prefix );
755 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
756 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
760 // Increment reference count
762 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
763 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
770 * Test if the specified index represents an open connection
772 * @param int $index Server index
776 private function isOpen( $index ) {
777 if ( !is_integer( $index ) ) {
781 return (bool)$this->getAnyOpenConnection( $index );
785 * Really opens a connection. Uncached.
786 * Returns a Database object whether or not the connection was successful.
789 * @param array $server
790 * @param bool $dbNameOverride
791 * @throws MWException
792 * @return DatabaseBase
794 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
795 if ( !is_array( $server ) ) {
796 throw new MWException( 'You must update your load-balancing configuration. ' .
797 'See DefaultSettings.php entry for $wgDBservers.' );
800 if ( $dbNameOverride !== false ) {
801 $server['dbname'] = $dbNameOverride;
804 // Log when many connection are made on requests
805 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
806 $masterAddr = $this->getServerName( 0 );
807 wfDebugLog( 'DBPerformance', __METHOD__
. ": " .
808 "{$this->connsOpened}+ connections made (master=$masterAddr)\n" .
809 wfBacktrace( true ) );
814 $db = DatabaseBase
::factory( $server['type'], $server );
815 } catch ( DBConnectionError
$e ) {
816 // FIXME: This is probably the ugliest thing I have ever done to
817 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
821 $db->setLBInfo( $server );
827 * @throws DBConnectionError
830 private function reportConnectionError() {
831 $conn = $this->mErrorConnection
; // The connection which caused the error
833 'method' => __METHOD__
,
834 'last_error' => $this->mLastError
,
837 if ( !is_object( $conn ) ) {
838 // No last connection, probably due to all servers being too busy
840 "LB failure with no last connection. Connection error: {last_error}",
844 // If all servers were busy, mLastError will contain something sensible
845 throw new DBConnectionError( null, $this->mLastError
);
847 $context['db_server'] = $conn->getProperty( 'mServer' );
849 "Connection error: {last_error} ({db_server})",
853 // throws DBConnectionError
854 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
857 return false; /* not reached */
864 public function getWriterIndex() {
869 * Returns true if the specified index is a valid server index
874 public function haveIndex( $i ) {
875 return array_key_exists( $i, $this->mServers
);
879 * Returns true if the specified index is valid and has non-zero load
884 public function isNonZeroLoad( $i ) {
885 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
889 * Get the number of defined servers (not the number of open connections)
893 public function getServerCount() {
894 return count( $this->mServers
);
898 * Get the host name or IP address of the server with the specified index
899 * Prefer a readable name if available.
903 public function getServerName( $i ) {
904 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
905 $name = $this->mServers
[$i]['hostName'];
906 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
907 $name = $this->mServers
[$i]['host'];
912 return ( $name != '' ) ?
$name : 'localhost';
916 * Return the server info structure for a given index, or false if the index is invalid.
920 public function getServerInfo( $i ) {
921 if ( isset( $this->mServers
[$i] ) ) {
922 return $this->mServers
[$i];
929 * Sets the server info structure for the given index. Entry at index $i
930 * is created if it doesn't exist
932 * @param array $serverInfo
934 public function setServerInfo( $i, array $serverInfo ) {
935 $this->mServers
[$i] = $serverInfo;
939 * Get the current master position for chronology control purposes
942 public function getMasterPos() {
943 # If this entire request was served from a slave without opening a connection to the
944 # master (however unlikely that may be), then we can fetch the position from the slave.
945 $masterConn = $this->getAnyOpenConnection( 0 );
946 if ( !$masterConn ) {
947 $serverCount = count( $this->mServers
);
948 for ( $i = 1; $i < $serverCount; $i++
) {
949 $conn = $this->getAnyOpenConnection( $i );
951 wfDebug( "Master pos fetched from slave\n" );
953 return $conn->getSlavePos();
957 wfDebug( "Master pos fetched from master\n" );
959 return $masterConn->getMasterPos();
966 * Close all open connections
968 public function closeAll() {
969 foreach ( $this->mConns
as $conns2 ) {
970 foreach ( $conns2 as $conns3 ) {
971 /** @var DatabaseBase $conn */
972 foreach ( $conns3 as $conn ) {
977 $this->mConns
= array(
979 'foreignFree' => array(),
980 'foreignUsed' => array(),
982 $this->connsOpened
= 0;
987 * Using this function makes sure the LoadBalancer knows the connection is closed.
988 * If you use $conn->close() directly, the load balancer won't update its state.
989 * @param DatabaseBase $conn
991 public function closeConnection( $conn ) {
993 foreach ( $this->mConns
as $i1 => $conns2 ) {
994 foreach ( $conns2 as $i2 => $conns3 ) {
995 foreach ( $conns3 as $i3 => $candidateConn ) {
996 if ( $conn === $candidateConn ) {
998 unset( $this->mConns
[$i1][$i2][$i3] );
999 --$this->connsOpened
;
1012 * Commit transactions on all open connections
1014 public function commitAll() {
1015 foreach ( $this->mConns
as $conns2 ) {
1016 foreach ( $conns2 as $conns3 ) {
1017 /** @var DatabaseBase[] $conns3 */
1018 foreach ( $conns3 as $conn ) {
1019 if ( $conn->trxLevel() ) {
1020 $conn->commit( __METHOD__
, 'flush' );
1028 * Issue COMMIT only on master, only if queries were done on connection
1030 public function commitMasterChanges() {
1031 $masterIndex = $this->getWriterIndex();
1032 foreach ( $this->mConns
as $conns2 ) {
1033 if ( empty( $conns2[$masterIndex] ) ) {
1036 /** @var DatabaseBase $conn */
1037 foreach ( $conns2[$masterIndex] as $conn ) {
1038 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1039 $conn->commit( __METHOD__
, 'flush' );
1046 * Issue ROLLBACK only on master, only if queries were done on connection
1049 public function rollbackMasterChanges() {
1050 $failedServers = array();
1052 $masterIndex = $this->getWriterIndex();
1053 foreach ( $this->mConns
as $conns2 ) {
1054 if ( empty( $conns2[$masterIndex] ) ) {
1057 /** @var DatabaseBase $conn */
1058 foreach ( $conns2[$masterIndex] as $conn ) {
1059 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1061 $conn->rollback( __METHOD__
, 'flush' );
1062 } catch ( DBError
$e ) {
1063 MWExceptionHandler
::logException( $e );
1064 $failedServers[] = $conn->getServer();
1070 if ( $failedServers ) {
1071 throw new DBExpectedError( null, "Rollback failed on server(s) " .
1072 implode( ', ', array_unique( $failedServers ) ) );
1077 * @return bool Whether a master connection is already open
1080 public function hasMasterConnection() {
1081 return $this->isOpen( $this->getWriterIndex() );
1085 * Determine if there are pending changes in a transaction by this thread
1089 public function hasMasterChanges() {
1090 $masterIndex = $this->getWriterIndex();
1091 foreach ( $this->mConns
as $conns2 ) {
1092 if ( empty( $conns2[$masterIndex] ) ) {
1095 /** @var DatabaseBase $conn */
1096 foreach ( $conns2[$masterIndex] as $conn ) {
1097 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1106 * Get the timestamp of the latest write query done by this thread
1108 * @return float|bool UNIX timestamp or false
1110 public function lastMasterChangeTimestamp() {
1112 $masterIndex = $this->getWriterIndex();
1113 foreach ( $this->mConns
as $conns2 ) {
1114 if ( empty( $conns2[$masterIndex] ) ) {
1117 /** @var DatabaseBase $conn */
1118 foreach ( $conns2[$masterIndex] as $conn ) {
1119 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1126 * Check if this load balancer object had any recent or still
1127 * pending writes issued against it by this PHP thread
1129 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
1133 public function hasOrMadeRecentMasterChanges( $age = null ) {
1134 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1136 return ( $this->hasMasterChanges()
1137 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1141 * @param mixed $value
1144 public function waitTimeout( $value = null ) {
1145 return wfSetVar( $this->mWaitTimeout
, $value );
1149 * @note This method will trigger a DB connection if not yet done
1151 * @param string|bool $wiki Wiki ID, or false for the current wiki
1152 * @return bool Whether the generic connection for reads is highly "lagged"
1154 public function getLaggedSlaveMode( $wiki = false ) {
1155 // No-op if there is only one DB (also avoids recursion)
1156 if ( !$this->laggedSlaveMode
&& $this->getServerCount() > 1 ) {
1158 // See if laggedSlaveMode gets set
1159 $this->getConnection( DB_SLAVE
, false, $wiki );
1160 } catch ( DBConnectionError
$e ) {
1161 // Avoid expensive re-connect attempts and failures
1162 $this->slavesDownMode
= true;
1163 $this->laggedSlaveMode
= true;
1167 return $this->laggedSlaveMode
;
1171 * @note This method will never cause a new DB connection
1172 * @return bool Whether any generic connection used for reads was highly "lagged"
1175 public function laggedSlaveUsed() {
1176 return $this->laggedSlaveMode
;
1180 * @note This method may trigger a DB connection if not yet done
1181 * @param string|bool $wiki Wiki ID, or false for the current wiki
1182 * @return string|bool Reason the master is read-only or false if it is not
1185 public function getReadOnlyReason( $wiki = false ) {
1186 if ( $this->readOnlyReason
!== false ) {
1187 return $this->readOnlyReason
;
1188 } elseif ( $this->getLaggedSlaveMode( $wiki ) ) {
1189 if ( $this->slavesDownMode
) {
1190 return 'The database has been automatically locked ' .
1191 'until the slave database servers become available';
1193 return 'The database has been automatically locked ' .
1194 'while the slave database servers catch up to the master.';
1202 * Disables/enables lag checks
1203 * @param null|bool $mode
1206 public function allowLagged( $mode = null ) {
1207 if ( $mode === null ) {
1208 return $this->mAllowLagged
;
1210 $this->mAllowLagged
= $mode;
1212 return $this->mAllowLagged
;
1218 public function pingAll() {
1220 foreach ( $this->mConns
as $conns2 ) {
1221 foreach ( $conns2 as $conns3 ) {
1222 /** @var DatabaseBase[] $conns3 */
1223 foreach ( $conns3 as $conn ) {
1224 if ( !$conn->ping() ) {
1235 * Call a function with each open connection object
1236 * @param callable $callback
1237 * @param array $params
1239 public function forEachOpenConnection( $callback, array $params = array() ) {
1240 foreach ( $this->mConns
as $conns2 ) {
1241 foreach ( $conns2 as $conns3 ) {
1242 foreach ( $conns3 as $conn ) {
1243 $mergedParams = array_merge( array( $conn ), $params );
1244 call_user_func_array( $callback, $mergedParams );
1251 * Get the hostname and lag time of the most-lagged slave
1253 * This is useful for maintenance scripts that need to throttle their updates.
1254 * May attempt to open connections to slaves on the default DB. If there is
1255 * no lag, the maximum lag will be reported as -1.
1257 * @param bool|string $wiki Wiki ID, or false for the default database
1258 * @return array ( host, max lag, index of max lagged host )
1260 public function getMaxLag( $wiki = false ) {
1265 if ( $this->getServerCount() <= 1 ) {
1266 return array( $host, $maxLag, $maxIndex ); // no replication = no lag
1269 $lagTimes = $this->getLagTimes( $wiki );
1270 foreach ( $lagTimes as $i => $lag ) {
1271 if ( $lag > $maxLag ) {
1273 $host = $this->mServers
[$i]['host'];
1278 return array( $host, $maxLag, $maxIndex );
1282 * Get an estimate of replication lag (in seconds) for each server
1284 * Results are cached for a short time in memcached/process cache
1286 * Values may be "false" if replication is too broken to estimate
1288 * @param string|bool $wiki
1289 * @return int[] Map of (server index => float|int|bool)
1291 public function getLagTimes( $wiki = false ) {
1292 if ( $this->getServerCount() <= 1 ) {
1293 return array( 0 => 0 ); // no replication = no lag
1296 # Send the request to the load monitor
1297 return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
1301 * Get the lag in seconds for a given connection, or zero if this load
1302 * balancer does not have replication enabled.
1304 * This should be used in preference to Database::getLag() in cases where
1305 * replication may not be in use, since there is no way to determine if
1306 * replication is in use at the connection level without running
1307 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1308 * function instead of Database::getLag() avoids a fatal error in this
1309 * case on many installations.
1311 * @param DatabaseBase $conn
1314 public function safeGetLag( $conn ) {
1315 if ( $this->getServerCount() == 1 ) {
1318 return $conn->getLag();
1323 * Clear the cache for slag lag delay times
1325 * This is only used for testing
1327 public function clearLagTimeCache() {
1328 $this->getLoadMonitor()->clearCaches();