65ee9c716aefb7ca423de0ac894cc1e2a14c7b8d
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;
53 /** @var bool|DatabaseBase Database connection that caused a problem */
54 private $mErrorConnection;
55 /** @var integer The generic (not query grouped) slave index (of $mServers) */
57 /** @var bool|DBMasterPos False if not set */
59 /** @var bool Whether the generic reader fell back to a lagged slave */
60 private $laggedSlaveMode = false;
61 /** @var bool Whether the generic reader fell back to a lagged slave */
62 private $slavesDownMode = false;
63 /** @var string The last DB selection or connection error */
64 private $mLastError = 'Unknown error';
65 /** @var string|bool Reason the LB is read-only or false if not */
66 private $readOnlyReason = false;
67 /** @var integer Total connections opened */
68 private $connsOpened = 0;
70 /** @var integer Warn when this many connection are held */
71 const CONN_HELD_WARN_THRESHOLD
= 10;
72 /** @var integer Default 'max lag' when unspecified */
74 /** @var integer Max time to wait for a slave to catch up (e.g. ChronologyProtector) */
75 const POS_WAIT_TIMEOUT
= 10;
78 * @param array $params Array with keys:
79 * - servers : Required. Array of server info structures.
80 * - loadMonitor : Name of a class used to fetch server lag and load.
81 * - readOnlyReason : Reason the master DB is read-only if so [optional]
84 public function __construct( array $params ) {
85 if ( !isset( $params['servers'] ) ) {
86 throw new MWException( __CLASS__
. ': missing servers parameter' );
88 $this->mServers
= $params['servers'];
89 $this->mWaitTimeout
= self
::POS_WAIT_TIMEOUT
;
91 $this->mReadIndex
= -1;
92 $this->mWriteIndex
= -1;
93 $this->mConns
= array(
95 'foreignUsed' => array(),
96 'foreignFree' => array() );
97 $this->mLoads
= array();
98 $this->mWaitForPos
= false;
99 $this->mErrorConnection
= false;
100 $this->mAllowLagged
= false;
102 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
103 $this->readOnlyReason
= $params['readOnlyReason'];
106 if ( isset( $params['loadMonitor'] ) ) {
107 $this->mLoadMonitorClass
= $params['loadMonitor'];
109 $master = reset( $params['servers'] );
110 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
111 $this->mLoadMonitorClass
= 'LoadMonitorMySQL';
113 $this->mLoadMonitorClass
= 'LoadMonitorNull';
117 foreach ( $params['servers'] as $i => $server ) {
118 $this->mLoads
[$i] = $server['load'];
119 if ( isset( $server['groupLoads'] ) ) {
120 foreach ( $server['groupLoads'] as $group => $ratio ) {
121 if ( !isset( $this->mGroupLoads
[$group] ) ) {
122 $this->mGroupLoads
[$group] = array();
124 $this->mGroupLoads
[$group][$i] = $ratio;
129 $this->srvCache
= ObjectCache
::getLocalServerInstance();
133 * Get a LoadMonitor instance
135 * @return LoadMonitor
137 private function getLoadMonitor() {
138 if ( !isset( $this->mLoadMonitor
) ) {
139 $class = $this->mLoadMonitorClass
;
140 $this->mLoadMonitor
= new $class( $this );
143 return $this->mLoadMonitor
;
147 * Get or set arbitrary data used by the parent object, usually an LBFactory
151 public function parentInfo( $x = null ) {
152 return wfSetVar( $this->mParentInfo
, $x );
156 * Given an array of non-normalised probabilities, this function will select
157 * an element and return the appropriate key
159 * @deprecated since 1.21, use ArrayUtils::pickRandom()
161 * @param array $weights
162 * @return bool|int|string
164 public function pickRandom( array $weights ) {
165 return ArrayUtils
::pickRandom( $weights );
169 * @param array $loads
170 * @param bool|string $wiki Wiki to get non-lagged for
171 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
172 * @return bool|int|string
174 private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = self
::MAX_LAG
) {
175 $lags = $this->getLagTimes( $wiki );
177 # Unset excessively lagged servers
178 foreach ( $lags as $i => $lag ) {
180 $maxServerLag = $maxLag;
181 if ( isset( $this->mServers
[$i]['max lag'] ) ) {
182 $maxServerLag = min( $maxServerLag, $this->mServers
[$i]['max lag'] );
184 if ( $lag === false ) {
185 wfDebugLog( 'replication', "Server #$i is not replicating" );
187 } elseif ( $lag > $maxServerLag ) {
188 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)" );
194 # Find out if all the slaves with non-zero load are lagged
196 foreach ( $loads as $load ) {
200 # No appropriate DB servers except maybe the master and some slaves with zero load
201 # Do NOT use the master
202 # Instead, this function will return false, triggering read-only mode,
203 # and a lagged slave will be used instead.
207 if ( count( $loads ) == 0 ) {
211 # wfDebugLog( 'connect', var_export( $loads, true ) );
213 # Return a random representative of the remainder
214 return ArrayUtils
::pickRandom( $loads );
218 * Get the index of the reader connection, which may be a slave
219 * This takes into account load ratios and lag times. It should
220 * always return a consistent index during a given invocation
222 * Side effect: opens connections to databases
223 * @param string|bool $group Query group, or false for the generic reader
224 * @param string|bool $wiki Wiki ID, or false for the current wiki
225 * @throws MWException
226 * @return bool|int|string
228 public function getReaderIndex( $group = false, $wiki = false ) {
231 # @todo FIXME: For now, only go through all this for mysql databases
232 if ( $wgDBtype != 'mysql' ) {
233 return $this->getWriterIndex();
236 if ( count( $this->mServers
) == 1 ) {
237 # Skip the load balancing if there's only one server
239 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
240 # Shortcut if generic reader exists already
241 return $this->mReadIndex
;
244 # Find the relevant load array
245 if ( $group !== false ) {
246 if ( isset( $this->mGroupLoads
[$group] ) ) {
247 $nonErrorLoads = $this->mGroupLoads
[$group];
249 # No loads for this group, return false and the caller can use some other group
250 wfDebug( __METHOD__
. ": no loads for group $group\n" );
255 $nonErrorLoads = $this->mLoads
;
258 if ( !count( $nonErrorLoads ) ) {
259 throw new MWException( "Empty server array given to LoadBalancer" );
262 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
263 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
265 $laggedSlaveMode = false;
267 # No server found yet
270 # First try quickly looking through the available servers for a server that
272 $currentLoads = $nonErrorLoads;
273 while ( count( $currentLoads ) ) {
274 if ( $this->mAllowLagged ||
$laggedSlaveMode ) {
275 $i = ArrayUtils
::pickRandom( $currentLoads );
278 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
279 # ChronologyProtecter causes mWaitForPos to be set via sessions.
280 # This triggers doWait() after connect, so it's especially good to
281 # avoid lagged servers so as to avoid just blocking in that method.
282 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
283 # Aim for <= 1 second of waiting (being too picky can backfire)
284 $i = $this->getRandomNonLagged( $currentLoads, $wiki, $ago +
1 );
286 if ( $i === false ) {
287 # Any server with less lag than it's 'max lag' param is preferable
288 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
290 if ( $i === false && count( $currentLoads ) != 0 ) {
291 # All slaves lagged. Switch to read-only mode
292 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode" );
293 $i = ArrayUtils
::pickRandom( $currentLoads );
294 $laggedSlaveMode = true;
298 if ( $i === false ) {
299 # pickRandom() returned false
300 # This is permanent and means the configuration or the load monitor
301 # wants us to return false.
302 wfDebugLog( 'connect', __METHOD__
. ": pickRandom() returned false" );
307 $serverName = $this->getServerName( $i );
308 wfDebugLog( 'connect', __METHOD__
. ": Using reader #$i: $serverName..." );
310 $conn = $this->openConnection( $i, $wiki );
312 wfDebugLog( 'connect', __METHOD__
. ": Failed connecting to $i/$wiki" );
313 unset( $nonErrorLoads[$i] );
314 unset( $currentLoads[$i] );
319 // Decrement reference counter, we are finished with this connection.
320 // It will be incremented for the caller later.
321 if ( $wiki !== false ) {
322 $this->reuseConnection( $conn );
329 # If all servers were down, quit now
330 if ( !count( $nonErrorLoads ) ) {
331 wfDebugLog( 'connect', "All servers down" );
334 if ( $i !== false ) {
335 # Slave connection successful
336 # Wait for the session master pos for a short time
337 if ( $this->mWaitForPos
&& $i > 0 ) {
338 if ( !$this->doWait( $i ) ) {
339 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
342 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
343 $this->mReadIndex
= $i;
344 # Record if the generic reader index is in "lagged slave" mode
345 if ( $laggedSlaveMode ) {
346 $this->laggedSlaveMode
= true;
349 $serverName = $this->getServerName( $i );
350 wfDebug( __METHOD__
. ": using server $serverName for group '$group'\n" );
357 * Set the master wait position
358 * If a DB_SLAVE connection has been opened already, waits
359 * Otherwise sets a variable telling it to wait if such a connection is opened
360 * @param DBMasterPos $pos
362 public function waitFor( $pos ) {
363 $this->mWaitForPos
= $pos;
364 $i = $this->mReadIndex
;
367 if ( !$this->doWait( $i ) ) {
368 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
369 $this->laggedSlaveMode
= true;
375 * Set the master wait position and wait for a "generic" slave to catch up to it
377 * This can be used a faster proxy for waitForAll()
379 * @param DBMasterPos $pos
380 * @param int $timeout Max seconds to wait; default is mWaitTimeout
381 * @return bool Success (able to connect and no timeouts reached)
384 public function waitForOne( $pos, $timeout = null ) {
385 $this->mWaitForPos
= $pos;
387 $i = $this->mReadIndex
;
389 // Pick a generic slave if there isn't one yet
390 $readLoads = $this->mLoads
;
391 unset( $readLoads[$this->getWriterIndex()] ); // slaves only
392 $readLoads = array_filter( $readLoads ); // with non-zero load
393 $i = ArrayUtils
::pickRandom( $readLoads );
397 $ok = $this->doWait( $i, true, $timeout );
399 $ok = true; // no applicable loads
406 * Set the master wait position and wait for ALL slaves to catch up to it
407 * @param DBMasterPos $pos
408 * @param int $timeout Max seconds to wait; default is mWaitTimeout
409 * @return bool Success (able to connect and no timeouts reached)
411 public function waitForAll( $pos, $timeout = null ) {
412 $this->mWaitForPos
= $pos;
413 $serverCount = count( $this->mServers
);
416 for ( $i = 1; $i < $serverCount; $i++
) {
417 if ( $this->mLoads
[$i] > 0 ) {
418 $ok = $this->doWait( $i, true, $timeout ) && $ok;
426 * Get any open connection to a given server index, local or foreign
427 * Returns false if there is no connection open
430 * @return DatabaseBase|bool False on failure
432 public function getAnyOpenConnection( $i ) {
433 foreach ( $this->mConns
as $conns ) {
434 if ( !empty( $conns[$i] ) ) {
435 return reset( $conns[$i] );
443 * Wait for a given slave to catch up to the master pos stored in $this
444 * @param int $index Server index
445 * @param bool $open Check the server even if a new connection has to be made
446 * @param int $timeout Max seconds to wait; default is mWaitTimeout
449 protected function doWait( $index, $open = false, $timeout = null ) {
450 $close = false; // close the connection afterwards
452 // Check if we already know that the DB has reached this point
453 $server = $this->getServerName( $index );
454 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server );
455 /** @var DBMasterPos $knownReachedPos */
456 $knownReachedPos = $this->srvCache
->get( $key );
457 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos
) ) {
458 wfDebugLog( 'replication', __METHOD__
. ": Slave $server known to be caught up.\n" );
462 // Find a connection to wait on, creating one if needed and allowed
463 $conn = $this->getAnyOpenConnection( $index );
466 wfDebugLog( 'replication', __METHOD__
. ": no connection open for $server\n" );
470 $conn = $this->openConnection( $index, '' );
472 wfDebugLog( 'replication', __METHOD__
. ": failed to open connection to $server\n" );
476 // Avoid connection spam in waitForAll() when connections
477 // are made just for the sake of doing this lag check.
482 wfDebugLog( 'replication', __METHOD__
. ": Waiting for slave $server to catch up...\n" );
483 $timeout = $timeout ?
: $this->mWaitTimeout
;
484 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
486 if ( $result == -1 ||
is_null( $result ) ) {
487 // Timed out waiting for slave, use master instead
488 $msg = __METHOD__
. ": Timed out waiting on $server pos {$this->mWaitForPos}";
489 wfDebugLog( 'replication', "$msg\n" );
490 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
493 wfDebugLog( 'replication', __METHOD__
. ": Done\n" );
495 // Remember that the DB reached this point
496 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
500 $this->closeConnection( $conn );
507 * Get a connection by index
508 * This is the main entry point for this class.
510 * @param int $i Server index
511 * @param array|string|bool $groups Query group(s), or false for the generic reader
512 * @param string|bool $wiki Wiki ID, or false for the current wiki
514 * @throws MWException
515 * @return DatabaseBase
517 public function getConnection( $i, $groups = array(), $wiki = false ) {
518 if ( $i === null ||
$i === false ) {
519 throw new MWException( 'Attempt to call ' . __METHOD__
.
520 ' with invalid server index' );
523 if ( $wiki === wfWikiID() ) {
527 $groups = ( $groups === false ||
$groups === array() )
528 ?
array( false ) // check one "group": the generic pool
531 $masterOnly = ( $i == DB_MASTER ||
$i == $this->getWriterIndex() );
532 $oldConnsOpened = $this->connsOpened
; // connections open now
534 if ( $i == DB_MASTER
) {
535 $i = $this->getWriterIndex();
537 # Try to find an available server in any the query groups (in order)
538 foreach ( $groups as $group ) {
539 $groupIndex = $this->getReaderIndex( $group, $wiki );
540 if ( $groupIndex !== false ) {
547 # Operation-based index
548 if ( $i == DB_SLAVE
) {
549 $this->mLastError
= 'Unknown error'; // reset error string
550 # Try the general server pool if $groups are unavailable.
551 $i = in_array( false, $groups, true )
552 ?
false // don't bother with this if that is what was tried above
553 : $this->getReaderIndex( false, $wiki );
554 # Couldn't find a working server in getReaderIndex()?
555 if ( $i === false ) {
556 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
558 return $this->reportConnectionError();
562 # Now we have an explicit index into the servers array
563 $conn = $this->openConnection( $i, $wiki );
565 return $this->reportConnectionError();
568 # Profile any new connections that happen
569 if ( $this->connsOpened
> $oldConnsOpened ) {
570 $host = $conn->getServer();
571 $dbname = $conn->getDBname();
572 $trxProf = Profiler
::instance()->getTransactionProfiler();
573 $trxProf->recordConnection( $host, $dbname, $masterOnly );
577 # Make master-requested DB handles inherit any read-only mode setting
578 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $wiki ) );
585 * Mark a foreign connection as being available for reuse under a different
586 * DB name or prefix. This mechanism is reference-counted, and must be called
587 * the same number of times as getConnection() to work.
589 * @param DatabaseBase $conn
590 * @throws MWException
592 public function reuseConnection( $conn ) {
593 $serverIndex = $conn->getLBInfo( 'serverIndex' );
594 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
595 if ( $serverIndex === null ||
$refCount === null ) {
596 wfDebug( __METHOD__
. ": this connection was not opened as a foreign connection\n" );
599 * This can happen in code like:
600 * foreach ( $dbs as $db ) {
601 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
603 * $lb->reuseConnection( $conn );
605 * When a connection to the local DB is opened in this way, reuseConnection()
612 $dbName = $conn->getDBname();
613 $prefix = $conn->tablePrefix();
614 if ( strval( $prefix ) !== '' ) {
615 $wiki = "$dbName-$prefix";
619 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
620 throw new MWException( __METHOD__
. ": connection not found, has " .
621 "the connection been freed already?" );
623 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
624 if ( $refCount <= 0 ) {
625 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
626 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
627 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
629 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
634 * Get a database connection handle reference
636 * The handle's methods wrap simply wrap those of a DatabaseBase handle
638 * @see LoadBalancer::getConnection() for parameter information
641 * @param array|string|bool $groups Query group(s), or false for the generic reader
642 * @param string|bool $wiki Wiki ID, or false for the current wiki
645 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
646 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
650 * Get a database connection handle reference without connecting yet
652 * The handle's methods wrap simply wrap those of a DatabaseBase handle
654 * @see LoadBalancer::getConnection() for parameter information
657 * @param array|string|bool $groups Query group(s), or false for the generic reader
658 * @param string|bool $wiki Wiki ID, or false for the current wiki
661 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
662 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
666 * Open a connection to the server given by the specified index
667 * Index must be an actual index into the array.
668 * If the server is already open, returns it.
670 * On error, returns false, and the connection which caused the
671 * error will be available via $this->mErrorConnection.
673 * @param int $i Server index
674 * @param string|bool $wiki Wiki ID, or false for the current wiki
675 * @return DatabaseBase
679 public function openConnection( $i, $wiki = false ) {
680 if ( $wiki !== false ) {
681 $conn = $this->openForeignConnection( $i, $wiki );
682 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
683 $conn = $this->mConns
['local'][$i][0];
685 $server = $this->mServers
[$i];
686 $server['serverIndex'] = $i;
687 $conn = $this->reallyOpenConnection( $server, false );
688 $serverName = $this->getServerName( $i );
689 if ( $conn->isOpen() ) {
690 wfDebug( "Connected to database $i at $serverName\n" );
691 $this->mConns
['local'][$i][0] = $conn;
693 wfDebug( "Failed to connect to database $i at $serverName\n" );
694 $this->mErrorConnection
= $conn;
699 if ( $conn && !$conn->isOpen() ) {
700 // Connection was made but later unrecoverably lost for some reason.
701 // Do not return a handle that will just throw exceptions on use,
702 // but let the calling code (e.g. getReaderIndex) try another server.
703 // See DatabaseMyslBase::ping() for how this can happen.
704 $this->mErrorConnection
= $conn;
712 * Open a connection to a foreign DB, or return one if it is already open.
714 * Increments a reference count on the returned connection which locks the
715 * connection to the requested wiki. This reference count can be
716 * decremented by calling reuseConnection().
718 * If a connection is open to the appropriate server already, but with the wrong
719 * database, it will be switched to the right database and returned, as long as
720 * it has been freed first with reuseConnection().
722 * On error, returns false, and the connection which caused the
723 * error will be available via $this->mErrorConnection.
725 * @param int $i Server index
726 * @param string $wiki Wiki ID to open
727 * @return DatabaseBase
729 private function openForeignConnection( $i, $wiki ) {
730 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
731 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
732 // Reuse an already-used connection
733 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
734 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
735 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
736 // Reuse a free connection for the same wiki
737 $conn = $this->mConns
['foreignFree'][$i][$wiki];
738 unset( $this->mConns
['foreignFree'][$i][$wiki] );
739 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
740 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
741 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
742 // Reuse a connection from another wiki
743 $conn = reset( $this->mConns
['foreignFree'][$i] );
744 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
746 // The empty string as a DB name means "don't care".
747 // DatabaseMysqlBase::open() already handle this on connection.
748 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
749 $this->mLastError
= "Error selecting database $dbName on server " .
750 $conn->getServer() . " from client host " . wfHostname() . "\n";
751 $this->mErrorConnection
= $conn;
754 $conn->tablePrefix( $prefix );
755 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
756 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
757 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
760 // Open a new connection
761 $server = $this->mServers
[$i];
762 $server['serverIndex'] = $i;
763 $server['foreignPoolRefCount'] = 0;
764 $server['foreign'] = true;
765 $conn = $this->reallyOpenConnection( $server, $dbName );
766 if ( !$conn->isOpen() ) {
767 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
768 $this->mErrorConnection
= $conn;
771 $conn->tablePrefix( $prefix );
772 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
773 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
777 // Increment reference count
779 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
780 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
787 * Test if the specified index represents an open connection
789 * @param int $index Server index
793 private function isOpen( $index ) {
794 if ( !is_integer( $index ) ) {
798 return (bool)$this->getAnyOpenConnection( $index );
802 * Really opens a connection. Uncached.
803 * Returns a Database object whether or not the connection was successful.
806 * @param array $server
807 * @param bool $dbNameOverride
808 * @throws MWException
809 * @return DatabaseBase
811 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
812 if ( !is_array( $server ) ) {
813 throw new MWException( 'You must update your load-balancing configuration. ' .
814 'See DefaultSettings.php entry for $wgDBservers.' );
817 if ( $dbNameOverride !== false ) {
818 $server['dbname'] = $dbNameOverride;
821 // Log when many connection are made on requests
822 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
823 $masterAddr = $this->getServerName( 0 );
824 wfDebugLog( 'DBPerformance', __METHOD__
. ": " .
825 "{$this->connsOpened}+ connections made (master=$masterAddr)\n" .
826 wfBacktrace( true ) );
831 $db = DatabaseBase
::factory( $server['type'], $server );
832 } catch ( DBConnectionError
$e ) {
833 // FIXME: This is probably the ugliest thing I have ever done to
834 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
838 $db->setLBInfo( $server );
844 * @throws DBConnectionError
847 private function reportConnectionError() {
848 $conn = $this->mErrorConnection
; // The connection which caused the error
850 'method' => __METHOD__
,
851 'last_error' => $this->mLastError
,
854 if ( !is_object( $conn ) ) {
855 // No last connection, probably due to all servers being too busy
857 "LB failure with no last connection. Connection error: {last_error}",
861 // If all servers were busy, mLastError will contain something sensible
862 throw new DBConnectionError( null, $this->mLastError
);
864 $context['db_server'] = $conn->getProperty( 'mServer' );
866 "Connection error: {last_error} ({db_server})",
870 // throws DBConnectionError
871 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
874 return false; /* not reached */
881 public function getWriterIndex() {
886 * Returns true if the specified index is a valid server index
891 public function haveIndex( $i ) {
892 return array_key_exists( $i, $this->mServers
);
896 * Returns true if the specified index is valid and has non-zero load
901 public function isNonZeroLoad( $i ) {
902 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
906 * Get the number of defined servers (not the number of open connections)
910 public function getServerCount() {
911 return count( $this->mServers
);
915 * Get the host name or IP address of the server with the specified index
916 * Prefer a readable name if available.
920 public function getServerName( $i ) {
921 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
922 $name = $this->mServers
[$i]['hostName'];
923 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
924 $name = $this->mServers
[$i]['host'];
929 return ( $name != '' ) ?
$name : 'localhost';
933 * Return the server info structure for a given index, or false if the index is invalid.
937 public function getServerInfo( $i ) {
938 if ( isset( $this->mServers
[$i] ) ) {
939 return $this->mServers
[$i];
946 * Sets the server info structure for the given index. Entry at index $i
947 * is created if it doesn't exist
949 * @param array $serverInfo
951 public function setServerInfo( $i, array $serverInfo ) {
952 $this->mServers
[$i] = $serverInfo;
956 * Get the current master position for chronology control purposes
959 public function getMasterPos() {
960 # If this entire request was served from a slave without opening a connection to the
961 # master (however unlikely that may be), then we can fetch the position from the slave.
962 $masterConn = $this->getAnyOpenConnection( 0 );
963 if ( !$masterConn ) {
964 $serverCount = count( $this->mServers
);
965 for ( $i = 1; $i < $serverCount; $i++
) {
966 $conn = $this->getAnyOpenConnection( $i );
968 wfDebug( "Master pos fetched from slave\n" );
970 return $conn->getSlavePos();
974 wfDebug( "Master pos fetched from master\n" );
976 return $masterConn->getMasterPos();
983 * Close all open connections
985 public function closeAll() {
986 foreach ( $this->mConns
as $conns2 ) {
987 foreach ( $conns2 as $conns3 ) {
988 /** @var DatabaseBase $conn */
989 foreach ( $conns3 as $conn ) {
994 $this->mConns
= array(
996 'foreignFree' => array(),
997 'foreignUsed' => array(),
999 $this->connsOpened
= 0;
1003 * Close a connection
1004 * Using this function makes sure the LoadBalancer knows the connection is closed.
1005 * If you use $conn->close() directly, the load balancer won't update its state.
1006 * @param DatabaseBase $conn
1008 public function closeConnection( $conn ) {
1010 foreach ( $this->mConns
as $i1 => $conns2 ) {
1011 foreach ( $conns2 as $i2 => $conns3 ) {
1012 foreach ( $conns3 as $i3 => $candidateConn ) {
1013 if ( $conn === $candidateConn ) {
1015 unset( $this->mConns
[$i1][$i2][$i3] );
1016 --$this->connsOpened
;
1029 * Commit transactions on all open connections
1031 public function commitAll() {
1032 foreach ( $this->mConns
as $conns2 ) {
1033 foreach ( $conns2 as $conns3 ) {
1034 /** @var DatabaseBase[] $conns3 */
1035 foreach ( $conns3 as $conn ) {
1036 if ( $conn->trxLevel() ) {
1037 $conn->commit( __METHOD__
, 'flush' );
1045 * Issue COMMIT only on master, only if queries were done on connection
1047 public function commitMasterChanges() {
1048 $masterIndex = $this->getWriterIndex();
1049 foreach ( $this->mConns
as $conns2 ) {
1050 if ( empty( $conns2[$masterIndex] ) ) {
1053 /** @var DatabaseBase $conn */
1054 foreach ( $conns2[$masterIndex] as $conn ) {
1055 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1056 $conn->commit( __METHOD__
, 'flush' );
1063 * Issue ROLLBACK only on master, only if queries were done on connection
1066 public function rollbackMasterChanges() {
1067 $failedServers = array();
1069 $masterIndex = $this->getWriterIndex();
1070 foreach ( $this->mConns
as $conns2 ) {
1071 if ( empty( $conns2[$masterIndex] ) ) {
1074 /** @var DatabaseBase $conn */
1075 foreach ( $conns2[$masterIndex] as $conn ) {
1076 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1078 $conn->rollback( __METHOD__
, 'flush' );
1079 } catch ( DBError
$e ) {
1080 MWExceptionHandler
::logException( $e );
1081 $failedServers[] = $conn->getServer();
1087 if ( $failedServers ) {
1088 throw new DBExpectedError( null, "Rollback failed on server(s) " .
1089 implode( ', ', array_unique( $failedServers ) ) );
1094 * @return bool Whether a master connection is already open
1097 public function hasMasterConnection() {
1098 return $this->isOpen( $this->getWriterIndex() );
1102 * Determine if there are pending changes in a transaction by this thread
1106 public function hasMasterChanges() {
1107 $masterIndex = $this->getWriterIndex();
1108 foreach ( $this->mConns
as $conns2 ) {
1109 if ( empty( $conns2[$masterIndex] ) ) {
1112 /** @var DatabaseBase $conn */
1113 foreach ( $conns2[$masterIndex] as $conn ) {
1114 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1123 * Get the timestamp of the latest write query done by this thread
1125 * @return float|bool UNIX timestamp or false
1127 public function lastMasterChangeTimestamp() {
1129 $masterIndex = $this->getWriterIndex();
1130 foreach ( $this->mConns
as $conns2 ) {
1131 if ( empty( $conns2[$masterIndex] ) ) {
1134 /** @var DatabaseBase $conn */
1135 foreach ( $conns2[$masterIndex] as $conn ) {
1136 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1143 * Check if this load balancer object had any recent or still
1144 * pending writes issued against it by this PHP thread
1146 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
1150 public function hasOrMadeRecentMasterChanges( $age = null ) {
1151 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1153 return ( $this->hasMasterChanges()
1154 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1158 * @param mixed $value
1161 public function waitTimeout( $value = null ) {
1162 return wfSetVar( $this->mWaitTimeout
, $value );
1166 * @note This method will trigger a DB connection if not yet done
1168 * @param string|bool $wiki Wiki ID, or false for the current wiki
1169 * @return bool Whether the generic connection for reads is highly "lagged"
1171 public function getLaggedSlaveMode( $wiki = false ) {
1172 // No-op if there is only one DB (also avoids recursion)
1173 if ( !$this->laggedSlaveMode
&& $this->getServerCount() > 1 ) {
1175 // See if laggedSlaveMode gets set
1176 $this->getConnection( DB_SLAVE
, false, $wiki );
1177 } catch ( DBConnectionError
$e ) {
1178 // Avoid expensive re-connect attempts and failures
1179 $this->slavesDownMode
= true;
1180 $this->laggedSlaveMode
= true;
1184 return $this->laggedSlaveMode
;
1188 * @note This method will never cause a new DB connection
1189 * @return bool Whether any generic connection used for reads was highly "lagged"
1192 public function laggedSlaveUsed() {
1193 return $this->laggedSlaveMode
;
1197 * @note This method may trigger a DB connection if not yet done
1198 * @param string|bool $wiki Wiki ID, or false for the current wiki
1199 * @return string|bool Reason the master is read-only or false if it is not
1202 public function getReadOnlyReason( $wiki = false ) {
1203 if ( $this->readOnlyReason
!== false ) {
1204 return $this->readOnlyReason
;
1205 } elseif ( $this->getLaggedSlaveMode( $wiki ) ) {
1206 if ( $this->slavesDownMode
) {
1207 return 'The database has been automatically locked ' .
1208 'until the slave database servers become available';
1210 return 'The database has been automatically locked ' .
1211 'while the slave database servers catch up to the master.';
1219 * Disables/enables lag checks
1220 * @param null|bool $mode
1223 public function allowLagged( $mode = null ) {
1224 if ( $mode === null ) {
1225 return $this->mAllowLagged
;
1227 $this->mAllowLagged
= $mode;
1229 return $this->mAllowLagged
;
1235 public function pingAll() {
1237 foreach ( $this->mConns
as $conns2 ) {
1238 foreach ( $conns2 as $conns3 ) {
1239 /** @var DatabaseBase[] $conns3 */
1240 foreach ( $conns3 as $conn ) {
1241 if ( !$conn->ping() ) {
1252 * Call a function with each open connection object
1253 * @param callable $callback
1254 * @param array $params
1256 public function forEachOpenConnection( $callback, array $params = array() ) {
1257 foreach ( $this->mConns
as $conns2 ) {
1258 foreach ( $conns2 as $conns3 ) {
1259 foreach ( $conns3 as $conn ) {
1260 $mergedParams = array_merge( array( $conn ), $params );
1261 call_user_func_array( $callback, $mergedParams );
1268 * Get the hostname and lag time of the most-lagged slave
1270 * This is useful for maintenance scripts that need to throttle their updates.
1271 * May attempt to open connections to slaves on the default DB. If there is
1272 * no lag, the maximum lag will be reported as -1.
1274 * @param bool|string $wiki Wiki ID, or false for the default database
1275 * @return array ( host, max lag, index of max lagged host )
1277 public function getMaxLag( $wiki = false ) {
1282 if ( $this->getServerCount() <= 1 ) {
1283 return array( $host, $maxLag, $maxIndex ); // no replication = no lag
1286 $lagTimes = $this->getLagTimes( $wiki );
1287 foreach ( $lagTimes as $i => $lag ) {
1288 if ( $lag > $maxLag ) {
1290 $host = $this->mServers
[$i]['host'];
1295 return array( $host, $maxLag, $maxIndex );
1299 * Get an estimate of replication lag (in seconds) for each server
1301 * Results are cached for a short time in memcached/process cache
1303 * Values may be "false" if replication is too broken to estimate
1305 * @param string|bool $wiki
1306 * @return int[] Map of (server index => float|int|bool)
1308 public function getLagTimes( $wiki = false ) {
1309 if ( $this->getServerCount() <= 1 ) {
1310 return array( 0 => 0 ); // no replication = no lag
1313 # Send the request to the load monitor
1314 return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
1318 * Get the lag in seconds for a given connection, or zero if this load
1319 * balancer does not have replication enabled.
1321 * This should be used in preference to Database::getLag() in cases where
1322 * replication may not be in use, since there is no way to determine if
1323 * replication is in use at the connection level without running
1324 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1325 * function instead of Database::getLag() avoids a fatal error in this
1326 * case on many installations.
1328 * @param DatabaseBase $conn
1331 public function safeGetLag( $conn ) {
1332 if ( $this->getServerCount() == 1 ) {
1335 return $conn->getLag();
1340 * Clear the cache for slag lag delay times
1342 * This is only used for testing
1344 public function clearLagTimeCache() {
1345 $this->getLoadMonitor()->clearCaches();