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;
43 /** @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 TransactionProfiler */
71 protected $trxProfiler;
73 /** @var integer Warn when this many connection are held */
74 const CONN_HELD_WARN_THRESHOLD
= 10;
75 /** @var integer Default 'max lag' when unspecified */
77 /** @var integer Max time to wait for a slave to catch up (e.g. ChronologyProtector) */
78 const POS_WAIT_TIMEOUT
= 10;
81 * @param array $params Array with keys:
82 * - servers : Required. Array of server info structures.
83 * - loadMonitor : Name of a class used to fetch server lag and load.
84 * - readOnlyReason : Reason the master DB is read-only if so [optional]
87 public function __construct( array $params ) {
88 if ( !isset( $params['servers'] ) ) {
89 throw new MWException( __CLASS__
. ': missing servers parameter' );
91 $this->mServers
= $params['servers'];
92 $this->mWaitTimeout
= self
::POS_WAIT_TIMEOUT
;
94 $this->mReadIndex
= -1;
95 $this->mWriteIndex
= -1;
96 $this->mConns
= array(
98 'foreignUsed' => array(),
99 'foreignFree' => array() );
100 $this->mLoads
= array();
101 $this->mWaitForPos
= false;
102 $this->mErrorConnection
= false;
103 $this->mAllowLagged
= false;
105 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
106 $this->readOnlyReason
= $params['readOnlyReason'];
109 if ( isset( $params['loadMonitor'] ) ) {
110 $this->mLoadMonitorClass
= $params['loadMonitor'];
112 $master = reset( $params['servers'] );
113 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
114 $this->mLoadMonitorClass
= 'LoadMonitorMySQL';
116 $this->mLoadMonitorClass
= 'LoadMonitorNull';
120 foreach ( $params['servers'] as $i => $server ) {
121 $this->mLoads
[$i] = $server['load'];
122 if ( isset( $server['groupLoads'] ) ) {
123 foreach ( $server['groupLoads'] as $group => $ratio ) {
124 if ( !isset( $this->mGroupLoads
[$group] ) ) {
125 $this->mGroupLoads
[$group] = array();
127 $this->mGroupLoads
[$group][$i] = $ratio;
132 $this->srvCache
= ObjectCache
::getLocalServerInstance();
134 if ( isset( $params['trxProfiler'] ) ) {
135 $this->trxProfiler
= $params['trxProfiler'];
137 $this->trxProfiler
= new TransactionProfiler();
142 * Get a LoadMonitor instance
144 * @return LoadMonitor
146 private function getLoadMonitor() {
147 if ( !isset( $this->mLoadMonitor
) ) {
148 $class = $this->mLoadMonitorClass
;
149 $this->mLoadMonitor
= new $class( $this );
152 return $this->mLoadMonitor
;
156 * Get or set arbitrary data used by the parent object, usually an LBFactory
160 public function parentInfo( $x = null ) {
161 return wfSetVar( $this->mParentInfo
, $x );
165 * Given an array of non-normalised probabilities, this function will select
166 * an element and return the appropriate key
168 * @deprecated since 1.21, use ArrayUtils::pickRandom()
170 * @param array $weights
171 * @return bool|int|string
173 public function pickRandom( array $weights ) {
174 return ArrayUtils
::pickRandom( $weights );
178 * @param array $loads
179 * @param bool|string $wiki Wiki to get non-lagged for
180 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
181 * @return bool|int|string
183 private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = self
::MAX_LAG
) {
184 $lags = $this->getLagTimes( $wiki );
186 # Unset excessively lagged servers
187 foreach ( $lags as $i => $lag ) {
189 $maxServerLag = $maxLag;
190 if ( isset( $this->mServers
[$i]['max lag'] ) ) {
191 $maxServerLag = min( $maxServerLag, $this->mServers
[$i]['max lag'] );
194 $host = $this->getServerName( $i );
195 if ( $lag === false ) {
196 wfDebugLog( 'replication', "Server $host (#$i) is not replicating?" );
198 } elseif ( $lag > $maxServerLag ) {
199 wfDebugLog( 'replication', "Server $host (#$i) has >= $lag seconds of lag" );
205 # Find out if all the slaves with non-zero load are lagged
207 foreach ( $loads as $load ) {
211 # No appropriate DB servers except maybe the master and some slaves with zero load
212 # Do NOT use the master
213 # Instead, this function will return false, triggering read-only mode,
214 # and a lagged slave will be used instead.
218 if ( count( $loads ) == 0 ) {
222 # Return a random representative of the remainder
223 return ArrayUtils
::pickRandom( $loads );
227 * Get the index of the reader connection, which may be a slave
228 * This takes into account load ratios and lag times. It should
229 * always return a consistent index during a given invocation
231 * Side effect: opens connections to databases
232 * @param string|bool $group Query group, or false for the generic reader
233 * @param string|bool $wiki Wiki ID, or false for the current wiki
234 * @throws MWException
235 * @return bool|int|string
237 public function getReaderIndex( $group = false, $wiki = false ) {
240 # @todo FIXME: For now, only go through all this for mysql databases
241 if ( $wgDBtype != 'mysql' ) {
242 return $this->getWriterIndex();
245 if ( count( $this->mServers
) == 1 ) {
246 # Skip the load balancing if there's only one server
248 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
249 # Shortcut if generic reader exists already
250 return $this->mReadIndex
;
253 # Find the relevant load array
254 if ( $group !== false ) {
255 if ( isset( $this->mGroupLoads
[$group] ) ) {
256 $nonErrorLoads = $this->mGroupLoads
[$group];
258 # No loads for this group, return false and the caller can use some other group
259 wfDebugLog( 'connect', __METHOD__
. ": no loads for group $group\n" );
264 $nonErrorLoads = $this->mLoads
;
267 if ( !count( $nonErrorLoads ) ) {
268 throw new MWException( "Empty server array given to LoadBalancer" );
271 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
272 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
274 $laggedSlaveMode = false;
276 # No server found yet
279 # First try quickly looking through the available servers for a server that
281 $currentLoads = $nonErrorLoads;
282 while ( count( $currentLoads ) ) {
283 if ( $this->mAllowLagged ||
$laggedSlaveMode ) {
284 $i = ArrayUtils
::pickRandom( $currentLoads );
287 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
288 # ChronologyProtecter causes mWaitForPos to be set via sessions.
289 # This triggers doWait() after connect, so it's especially good to
290 # avoid lagged servers so as to avoid just blocking in that method.
291 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
292 # Aim for <= 1 second of waiting (being too picky can backfire)
293 $i = $this->getRandomNonLagged( $currentLoads, $wiki, $ago +
1 );
295 if ( $i === false ) {
296 # Any server with less lag than it's 'max lag' param is preferable
297 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
299 if ( $i === false && count( $currentLoads ) != 0 ) {
300 # All slaves lagged. Switch to read-only mode
301 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode" );
302 $i = ArrayUtils
::pickRandom( $currentLoads );
303 $laggedSlaveMode = true;
307 if ( $i === false ) {
308 # pickRandom() returned false
309 # This is permanent and means the configuration or the load monitor
310 # wants us to return false.
311 wfDebugLog( 'connect', __METHOD__
. ": pickRandom() returned false" );
316 $serverName = $this->getServerName( $i );
317 wfDebugLog( 'connect', __METHOD__
. ": Using reader #$i: $serverName..." );
319 $conn = $this->openConnection( $i, $wiki );
321 wfDebugLog( 'connect', __METHOD__
. ": Failed connecting to $i/$wiki" );
322 unset( $nonErrorLoads[$i] );
323 unset( $currentLoads[$i] );
328 // Decrement reference counter, we are finished with this connection.
329 // It will be incremented for the caller later.
330 if ( $wiki !== false ) {
331 $this->reuseConnection( $conn );
338 # If all servers were down, quit now
339 if ( !count( $nonErrorLoads ) ) {
340 wfDebugLog( 'connect', "All servers down" );
343 if ( $i !== false ) {
344 # Slave connection successful
345 # Wait for the session master pos for a short time
346 if ( $this->mWaitForPos
&& $i > 0 ) {
347 if ( !$this->doWait( $i ) ) {
348 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
351 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
352 $this->mReadIndex
= $i;
353 # Record if the generic reader index is in "lagged slave" mode
354 if ( $laggedSlaveMode ) {
355 $this->laggedSlaveMode
= true;
358 $serverName = $this->getServerName( $i );
359 wfDebugLog( 'connect', __METHOD__
.
360 ": using server $serverName for group '$group'\n" );
367 * Set the master wait position
368 * If a DB_SLAVE connection has been opened already, waits
369 * Otherwise sets a variable telling it to wait if such a connection is opened
370 * @param DBMasterPos $pos
372 public function waitFor( $pos ) {
373 $this->mWaitForPos
= $pos;
374 $i = $this->mReadIndex
;
377 if ( !$this->doWait( $i ) ) {
378 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
379 $this->laggedSlaveMode
= true;
385 * Set the master wait position and wait for a "generic" slave to catch up to it
387 * This can be used a faster proxy for waitForAll()
389 * @param DBMasterPos $pos
390 * @param int $timeout Max seconds to wait; default is mWaitTimeout
391 * @return bool Success (able to connect and no timeouts reached)
394 public function waitForOne( $pos, $timeout = null ) {
395 $this->mWaitForPos
= $pos;
397 $i = $this->mReadIndex
;
399 // Pick a generic slave if there isn't one yet
400 $readLoads = $this->mLoads
;
401 unset( $readLoads[$this->getWriterIndex()] ); // slaves only
402 $readLoads = array_filter( $readLoads ); // with non-zero load
403 $i = ArrayUtils
::pickRandom( $readLoads );
407 $ok = $this->doWait( $i, true, $timeout );
409 $ok = true; // no applicable loads
416 * Set the master wait position and wait for ALL slaves to catch up to it
417 * @param DBMasterPos $pos
418 * @param int $timeout Max seconds to wait; default is mWaitTimeout
419 * @return bool Success (able to connect and no timeouts reached)
421 public function waitForAll( $pos, $timeout = null ) {
422 $this->mWaitForPos
= $pos;
423 $serverCount = count( $this->mServers
);
426 for ( $i = 1; $i < $serverCount; $i++
) {
427 if ( $this->mLoads
[$i] > 0 ) {
428 $ok = $this->doWait( $i, true, $timeout ) && $ok;
436 * Get any open connection to a given server index, local or foreign
437 * Returns false if there is no connection open
440 * @return DatabaseBase|bool False on failure
442 public function getAnyOpenConnection( $i ) {
443 foreach ( $this->mConns
as $conns ) {
444 if ( !empty( $conns[$i] ) ) {
445 return reset( $conns[$i] );
453 * Wait for a given slave to catch up to the master pos stored in $this
454 * @param int $index Server index
455 * @param bool $open Check the server even if a new connection has to be made
456 * @param int $timeout Max seconds to wait; default is mWaitTimeout
459 protected function doWait( $index, $open = false, $timeout = null ) {
460 $close = false; // close the connection afterwards
462 // Check if we already know that the DB has reached this point
463 $server = $this->getServerName( $index );
464 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server );
465 /** @var DBMasterPos $knownReachedPos */
466 $knownReachedPos = $this->srvCache
->get( $key );
467 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos
) ) {
468 wfDebugLog( 'replication', __METHOD__
.
469 ": slave $server known to be caught up (pos >= $knownReachedPos).\n" );
473 // Find a connection to wait on, creating one if needed and allowed
474 $conn = $this->getAnyOpenConnection( $index );
477 wfDebugLog( 'replication', __METHOD__
. ": no connection open for $server\n" );
481 $conn = $this->openConnection( $index, '' );
483 wfDebugLog( 'replication', __METHOD__
. ": failed to connect to $server\n" );
487 // Avoid connection spam in waitForAll() when connections
488 // are made just for the sake of doing this lag check.
493 wfDebugLog( 'replication', __METHOD__
. ": Waiting for slave $server to catch up...\n" );
494 $timeout = $timeout ?
: $this->mWaitTimeout
;
495 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
497 if ( $result == -1 ||
is_null( $result ) ) {
498 // Timed out waiting for slave, use master instead
499 $msg = __METHOD__
. ": Timed out waiting on $server pos {$this->mWaitForPos}";
500 wfDebugLog( 'replication', "$msg\n" );
501 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
504 wfDebugLog( 'replication', __METHOD__
. ": Done\n" );
506 // Remember that the DB reached this point
507 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
511 $this->closeConnection( $conn );
518 * Get a connection by index
519 * This is the main entry point for this class.
521 * @param int $i Server index
522 * @param array|string|bool $groups Query group(s), or false for the generic reader
523 * @param string|bool $wiki Wiki ID, or false for the current wiki
525 * @throws MWException
526 * @return DatabaseBase
528 public function getConnection( $i, $groups = array(), $wiki = false ) {
529 if ( $i === null ||
$i === false ) {
530 throw new MWException( 'Attempt to call ' . __METHOD__
.
531 ' with invalid server index' );
534 if ( $wiki === wfWikiID() ) {
538 $groups = ( $groups === false ||
$groups === array() )
539 ?
array( false ) // check one "group": the generic pool
542 $masterOnly = ( $i == DB_MASTER ||
$i == $this->getWriterIndex() );
543 $oldConnsOpened = $this->connsOpened
; // connections open now
545 if ( $i == DB_MASTER
) {
546 $i = $this->getWriterIndex();
548 # Try to find an available server in any the query groups (in order)
549 foreach ( $groups as $group ) {
550 $groupIndex = $this->getReaderIndex( $group, $wiki );
551 if ( $groupIndex !== false ) {
558 # Operation-based index
559 if ( $i == DB_SLAVE
) {
560 $this->mLastError
= 'Unknown error'; // reset error string
561 # Try the general server pool if $groups are unavailable.
562 $i = in_array( false, $groups, true )
563 ?
false // don't bother with this if that is what was tried above
564 : $this->getReaderIndex( false, $wiki );
565 # Couldn't find a working server in getReaderIndex()?
566 if ( $i === false ) {
567 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
569 return $this->reportConnectionError();
573 # Now we have an explicit index into the servers array
574 $conn = $this->openConnection( $i, $wiki );
576 return $this->reportConnectionError();
579 # Profile any new connections that happen
580 if ( $this->connsOpened
> $oldConnsOpened ) {
581 $host = $conn->getServer();
582 $dbname = $conn->getDBname();
583 $trxProf = Profiler
::instance()->getTransactionProfiler();
584 $trxProf->recordConnection( $host, $dbname, $masterOnly );
588 # Make master-requested DB handles inherit any read-only mode setting
589 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $wiki ) );
596 * Mark a foreign connection as being available for reuse under a different
597 * DB name or prefix. This mechanism is reference-counted, and must be called
598 * the same number of times as getConnection() to work.
600 * @param DatabaseBase $conn
601 * @throws MWException
603 public function reuseConnection( $conn ) {
604 $serverIndex = $conn->getLBInfo( 'serverIndex' );
605 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
606 if ( $serverIndex === null ||
$refCount === null ) {
607 wfDebug( __METHOD__
. ": this connection was not opened as a foreign connection\n" );
609 * This can happen in code like:
610 * foreach ( $dbs as $db ) {
611 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
613 * $lb->reuseConnection( $conn );
615 * When a connection to the local DB is opened in this way, reuseConnection()
621 $dbName = $conn->getDBname();
622 $prefix = $conn->tablePrefix();
623 if ( strval( $prefix ) !== '' ) {
624 $wiki = "$dbName-$prefix";
628 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
629 throw new MWException( __METHOD__
. ": connection not found, has " .
630 "the connection been freed already?" );
632 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
633 if ( $refCount <= 0 ) {
634 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
635 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
636 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
638 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
643 * Get a database connection handle reference
645 * The handle's methods wrap simply wrap those of a DatabaseBase handle
647 * @see LoadBalancer::getConnection() for parameter information
650 * @param array|string|bool $groups Query group(s), or false for the generic reader
651 * @param string|bool $wiki Wiki ID, or false for the current wiki
654 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
655 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
659 * Get a database connection handle reference without connecting yet
661 * The handle's methods wrap simply wrap those of a DatabaseBase handle
663 * @see LoadBalancer::getConnection() for parameter information
666 * @param array|string|bool $groups Query group(s), or false for the generic reader
667 * @param string|bool $wiki Wiki ID, or false for the current wiki
670 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
671 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
675 * Open a connection to the server given by the specified index
676 * Index must be an actual index into the array.
677 * If the server is already open, returns it.
679 * On error, returns false, and the connection which caused the
680 * error will be available via $this->mErrorConnection.
682 * @param int $i Server index
683 * @param string|bool $wiki Wiki ID, or false for the current wiki
684 * @return DatabaseBase|bool Returns false on errors
686 public function openConnection( $i, $wiki = false ) {
687 if ( $wiki !== false ) {
688 $conn = $this->openForeignConnection( $i, $wiki );
689 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
690 $conn = $this->mConns
['local'][$i][0];
692 $server = $this->mServers
[$i];
693 $server['serverIndex'] = $i;
694 $conn = $this->reallyOpenConnection( $server, false );
695 $serverName = $this->getServerName( $i );
696 if ( $conn->isOpen() ) {
697 wfDebugLog( 'connect', "Connected to database $i at $serverName\n" );
698 $this->mConns
['local'][$i][0] = $conn;
700 wfDebugLog( 'connect', "Failed to connect to database $i at $serverName\n" );
701 $this->mErrorConnection
= $conn;
706 if ( $conn && !$conn->isOpen() ) {
707 // Connection was made but later unrecoverably lost for some reason.
708 // Do not return a handle that will just throw exceptions on use,
709 // but let the calling code (e.g. getReaderIndex) try another server.
710 // See DatabaseMyslBase::ping() for how this can happen.
711 $this->mErrorConnection
= $conn;
719 * Open a connection to a foreign DB, or return one if it is already open.
721 * Increments a reference count on the returned connection which locks the
722 * connection to the requested wiki. This reference count can be
723 * decremented by calling reuseConnection().
725 * If a connection is open to the appropriate server already, but with the wrong
726 * database, it will be switched to the right database and returned, as long as
727 * it has been freed first with reuseConnection().
729 * On error, returns false, and the connection which caused the
730 * error will be available via $this->mErrorConnection.
732 * @param int $i Server index
733 * @param string $wiki Wiki ID to open
734 * @return DatabaseBase
736 private function openForeignConnection( $i, $wiki ) {
737 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
738 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
739 // Reuse an already-used connection
740 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
741 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
742 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
743 // Reuse a free connection for the same wiki
744 $conn = $this->mConns
['foreignFree'][$i][$wiki];
745 unset( $this->mConns
['foreignFree'][$i][$wiki] );
746 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
747 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
748 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
749 // Reuse a connection from another wiki
750 $conn = reset( $this->mConns
['foreignFree'][$i] );
751 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
753 // The empty string as a DB name means "don't care".
754 // DatabaseMysqlBase::open() already handle this on connection.
755 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
756 $this->mLastError
= "Error selecting database $dbName on server " .
757 $conn->getServer() . " from client host " . wfHostname() . "\n";
758 $this->mErrorConnection
= $conn;
761 $conn->tablePrefix( $prefix );
762 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
763 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
764 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
767 // Open a new connection
768 $server = $this->mServers
[$i];
769 $server['serverIndex'] = $i;
770 $server['foreignPoolRefCount'] = 0;
771 $server['foreign'] = true;
772 $conn = $this->reallyOpenConnection( $server, $dbName );
773 if ( !$conn->isOpen() ) {
774 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
775 $this->mErrorConnection
= $conn;
778 $conn->tablePrefix( $prefix );
779 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
780 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
784 // Increment reference count
786 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
787 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
794 * Test if the specified index represents an open connection
796 * @param int $index Server index
800 private function isOpen( $index ) {
801 if ( !is_integer( $index ) ) {
805 return (bool)$this->getAnyOpenConnection( $index );
809 * Really opens a connection. Uncached.
810 * Returns a Database object whether or not the connection was successful.
813 * @param array $server
814 * @param bool $dbNameOverride
815 * @throws MWException
816 * @return DatabaseBase
818 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
819 if ( !is_array( $server ) ) {
820 throw new MWException( 'You must update your load-balancing configuration. ' .
821 'See DefaultSettings.php entry for $wgDBservers.' );
824 if ( $dbNameOverride !== false ) {
825 $server['dbname'] = $dbNameOverride;
828 // Let the handle know what the cluster master is (e.g. "db1052")
829 $masterName = $this->getServerName( 0 );
830 $server['clusterMasterHost'] = $masterName;
832 // Log when many connection are made on requests
833 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
834 wfDebugLog( 'DBPerformance', __METHOD__
. ": " .
835 "{$this->connsOpened}+ connections made (master=$masterName)\n" .
836 wfBacktrace( true ) );
841 $db = DatabaseBase
::factory( $server['type'], $server );
842 } catch ( DBConnectionError
$e ) {
843 // FIXME: This is probably the ugliest thing I have ever done to
844 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
848 $db->setLBInfo( $server );
849 $db->setLazyMasterHandle(
850 $this->getLazyConnectionRef( DB_MASTER
, array(), $db->getWikiID() )
852 $db->setTransactionProfiler( $this->trxProfiler
);
858 * @throws DBConnectionError
861 private function reportConnectionError() {
862 $conn = $this->mErrorConnection
; // The connection which caused the error
864 'method' => __METHOD__
,
865 'last_error' => $this->mLastError
,
868 if ( !is_object( $conn ) ) {
869 // No last connection, probably due to all servers being too busy
871 "LB failure with no last connection. Connection error: {last_error}",
875 // If all servers were busy, mLastError will contain something sensible
876 throw new DBConnectionError( null, $this->mLastError
);
878 $context['db_server'] = $conn->getProperty( 'mServer' );
880 "Connection error: {last_error} ({db_server})",
884 // throws DBConnectionError
885 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
888 return false; /* not reached */
895 public function getWriterIndex() {
900 * Returns true if the specified index is a valid server index
905 public function haveIndex( $i ) {
906 return array_key_exists( $i, $this->mServers
);
910 * Returns true if the specified index is valid and has non-zero load
915 public function isNonZeroLoad( $i ) {
916 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
920 * Get the number of defined servers (not the number of open connections)
924 public function getServerCount() {
925 return count( $this->mServers
);
929 * Get the host name or IP address of the server with the specified index
930 * Prefer a readable name if available.
934 public function getServerName( $i ) {
935 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
936 $name = $this->mServers
[$i]['hostName'];
937 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
938 $name = $this->mServers
[$i]['host'];
943 return ( $name != '' ) ?
$name : 'localhost';
947 * Return the server info structure for a given index, or false if the index is invalid.
951 public function getServerInfo( $i ) {
952 if ( isset( $this->mServers
[$i] ) ) {
953 return $this->mServers
[$i];
960 * Sets the server info structure for the given index. Entry at index $i
961 * is created if it doesn't exist
963 * @param array $serverInfo
965 public function setServerInfo( $i, array $serverInfo ) {
966 $this->mServers
[$i] = $serverInfo;
970 * Get the current master position for chronology control purposes
973 public function getMasterPos() {
974 # If this entire request was served from a slave without opening a connection to the
975 # master (however unlikely that may be), then we can fetch the position from the slave.
976 $masterConn = $this->getAnyOpenConnection( 0 );
977 if ( !$masterConn ) {
978 $serverCount = count( $this->mServers
);
979 for ( $i = 1; $i < $serverCount; $i++
) {
980 $conn = $this->getAnyOpenConnection( $i );
982 return $conn->getSlavePos();
986 return $masterConn->getMasterPos();
993 * Close all open connections
995 public function closeAll() {
996 foreach ( $this->mConns
as $conns2 ) {
997 foreach ( $conns2 as $conns3 ) {
998 /** @var DatabaseBase $conn */
999 foreach ( $conns3 as $conn ) {
1004 $this->mConns
= array(
1006 'foreignFree' => array(),
1007 'foreignUsed' => array(),
1009 $this->connsOpened
= 0;
1013 * Close a connection
1014 * Using this function makes sure the LoadBalancer knows the connection is closed.
1015 * If you use $conn->close() directly, the load balancer won't update its state.
1016 * @param DatabaseBase $conn
1018 public function closeConnection( $conn ) {
1020 foreach ( $this->mConns
as $i1 => $conns2 ) {
1021 foreach ( $conns2 as $i2 => $conns3 ) {
1022 foreach ( $conns3 as $i3 => $candidateConn ) {
1023 if ( $conn === $candidateConn ) {
1025 unset( $this->mConns
[$i1][$i2][$i3] );
1026 --$this->connsOpened
;
1039 * Commit transactions on all open connections
1040 * @param string $fname Caller name
1042 public function commitAll( $fname = __METHOD__
) {
1043 foreach ( $this->mConns
as $conns2 ) {
1044 foreach ( $conns2 as $conns3 ) {
1045 /** @var DatabaseBase[] $conns3 */
1046 foreach ( $conns3 as $conn ) {
1047 if ( $conn->trxLevel() ) {
1048 $conn->commit( $fname, 'flush' );
1056 * Issue COMMIT only on master, only if queries were done on connection
1057 * @param string $fname Caller name
1059 public function commitMasterChanges( $fname = __METHOD__
) {
1060 $masterIndex = $this->getWriterIndex();
1061 foreach ( $this->mConns
as $conns2 ) {
1062 if ( empty( $conns2[$masterIndex] ) ) {
1065 /** @var DatabaseBase $conn */
1066 foreach ( $conns2[$masterIndex] as $conn ) {
1067 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1068 $conn->commit( $fname, 'flush' );
1075 * Issue ROLLBACK only on master, only if queries were done on connection
1076 * @param string $fname Caller name
1077 * @throws DBExpectedError
1080 public function rollbackMasterChanges( $fname = __METHOD__
) {
1081 $failedServers = array();
1083 $masterIndex = $this->getWriterIndex();
1084 foreach ( $this->mConns
as $conns2 ) {
1085 if ( empty( $conns2[$masterIndex] ) ) {
1088 /** @var DatabaseBase $conn */
1089 foreach ( $conns2[$masterIndex] as $conn ) {
1090 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1092 $conn->rollback( $fname, 'flush' );
1093 } catch ( DBError
$e ) {
1094 MWExceptionHandler
::logException( $e );
1095 $failedServers[] = $conn->getServer();
1101 if ( $failedServers ) {
1102 throw new DBExpectedError( null, "Rollback failed on server(s) " .
1103 implode( ', ', array_unique( $failedServers ) ) );
1108 * @return bool Whether a master connection is already open
1111 public function hasMasterConnection() {
1112 return $this->isOpen( $this->getWriterIndex() );
1116 * Determine if there are pending changes in a transaction by this thread
1120 public function hasMasterChanges() {
1121 $masterIndex = $this->getWriterIndex();
1122 foreach ( $this->mConns
as $conns2 ) {
1123 if ( empty( $conns2[$masterIndex] ) ) {
1126 /** @var DatabaseBase $conn */
1127 foreach ( $conns2[$masterIndex] as $conn ) {
1128 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1137 * Get the timestamp of the latest write query done by this thread
1139 * @return float|bool UNIX timestamp or false
1141 public function lastMasterChangeTimestamp() {
1143 $masterIndex = $this->getWriterIndex();
1144 foreach ( $this->mConns
as $conns2 ) {
1145 if ( empty( $conns2[$masterIndex] ) ) {
1148 /** @var DatabaseBase $conn */
1149 foreach ( $conns2[$masterIndex] as $conn ) {
1150 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1157 * Check if this load balancer object had any recent or still
1158 * pending writes issued against it by this PHP thread
1160 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
1164 public function hasOrMadeRecentMasterChanges( $age = null ) {
1165 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1167 return ( $this->hasMasterChanges()
1168 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1172 * Get the list of callers that have pending master changes
1177 public function pendingMasterChangeCallers() {
1180 $masterIndex = $this->getWriterIndex();
1181 foreach ( $this->mConns
as $conns2 ) {
1182 if ( empty( $conns2[$masterIndex] ) ) {
1185 /** @var DatabaseBase $conn */
1186 foreach ( $conns2[$masterIndex] as $conn ) {
1187 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1195 * @param mixed $value
1198 public function waitTimeout( $value = null ) {
1199 return wfSetVar( $this->mWaitTimeout
, $value );
1203 * @note This method will trigger a DB connection if not yet done
1205 * @param string|bool $wiki Wiki ID, or false for the current wiki
1206 * @return bool Whether the generic connection for reads is highly "lagged"
1208 public function getLaggedSlaveMode( $wiki = false ) {
1209 // No-op if there is only one DB (also avoids recursion)
1210 if ( !$this->laggedSlaveMode
&& $this->getServerCount() > 1 ) {
1212 // See if laggedSlaveMode gets set
1213 $conn = $this->getConnection( DB_SLAVE
, false, $wiki );
1214 $this->reuseConnection( $conn );
1215 } catch ( DBConnectionError
$e ) {
1216 // Avoid expensive re-connect attempts and failures
1217 $this->slavesDownMode
= true;
1218 $this->laggedSlaveMode
= true;
1222 return $this->laggedSlaveMode
;
1226 * @note This method will never cause a new DB connection
1227 * @return bool Whether any generic connection used for reads was highly "lagged"
1230 public function laggedSlaveUsed() {
1231 return $this->laggedSlaveMode
;
1235 * @note This method may trigger a DB connection if not yet done
1236 * @param string|bool $wiki Wiki ID, or false for the current wiki
1237 * @return string|bool Reason the master is read-only or false if it is not
1240 public function getReadOnlyReason( $wiki = false ) {
1241 if ( $this->readOnlyReason
!== false ) {
1242 return $this->readOnlyReason
;
1243 } elseif ( $this->getLaggedSlaveMode( $wiki ) ) {
1244 if ( $this->slavesDownMode
) {
1245 return 'The database has been automatically locked ' .
1246 'until the slave database servers become available';
1248 return 'The database has been automatically locked ' .
1249 'while the slave database servers catch up to the master.';
1257 * Disables/enables lag checks
1258 * @param null|bool $mode
1261 public function allowLagged( $mode = null ) {
1262 if ( $mode === null ) {
1263 return $this->mAllowLagged
;
1265 $this->mAllowLagged
= $mode;
1267 return $this->mAllowLagged
;
1273 public function pingAll() {
1275 foreach ( $this->mConns
as $conns2 ) {
1276 foreach ( $conns2 as $conns3 ) {
1277 /** @var DatabaseBase[] $conns3 */
1278 foreach ( $conns3 as $conn ) {
1279 if ( !$conn->ping() ) {
1290 * Call a function with each open connection object
1291 * @param callable $callback
1292 * @param array $params
1294 public function forEachOpenConnection( $callback, array $params = array() ) {
1295 foreach ( $this->mConns
as $conns2 ) {
1296 foreach ( $conns2 as $conns3 ) {
1297 foreach ( $conns3 as $conn ) {
1298 $mergedParams = array_merge( array( $conn ), $params );
1299 call_user_func_array( $callback, $mergedParams );
1306 * Get the hostname and lag time of the most-lagged slave
1308 * This is useful for maintenance scripts that need to throttle their updates.
1309 * May attempt to open connections to slaves on the default DB. If there is
1310 * no lag, the maximum lag will be reported as -1.
1312 * @param bool|string $wiki Wiki ID, or false for the default database
1313 * @return array ( host, max lag, index of max lagged host )
1315 public function getMaxLag( $wiki = false ) {
1320 if ( $this->getServerCount() <= 1 ) {
1321 return array( $host, $maxLag, $maxIndex ); // no replication = no lag
1324 $lagTimes = $this->getLagTimes( $wiki );
1325 foreach ( $lagTimes as $i => $lag ) {
1326 if ( $lag > $maxLag ) {
1328 $host = $this->mServers
[$i]['host'];
1333 return array( $host, $maxLag, $maxIndex );
1337 * Get an estimate of replication lag (in seconds) for each server
1339 * Results are cached for a short time in memcached/process cache
1341 * Values may be "false" if replication is too broken to estimate
1343 * @param string|bool $wiki
1344 * @return int[] Map of (server index => float|int|bool)
1346 public function getLagTimes( $wiki = false ) {
1347 if ( $this->getServerCount() <= 1 ) {
1348 return array( 0 => 0 ); // no replication = no lag
1351 # Send the request to the load monitor
1352 return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
1356 * Get the lag in seconds for a given connection, or zero if this load
1357 * balancer does not have replication enabled.
1359 * This should be used in preference to Database::getLag() in cases where
1360 * replication may not be in use, since there is no way to determine if
1361 * replication is in use at the connection level without running
1362 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1363 * function instead of Database::getLag() avoids a fatal error in this
1364 * case on many installations.
1366 * @param IDatabase $conn
1367 * @return int|bool Returns false on error
1369 public function safeGetLag( IDatabase
$conn ) {
1370 if ( $this->getServerCount() == 1 ) {
1373 return $conn->getLag();
1378 * Wait for a slave DB to reach a specified master position
1380 * This will connect to the master to get an accurate position if $pos is not given
1382 * @param IDatabase $conn Slave DB
1383 * @param DBMasterPos|bool $pos Master position; default: current position
1384 * @param integer $timeout Timeout in seconds
1385 * @return bool Success
1388 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1389 if ( $this->getServerCount() == 1 ||
!$conn->getLBInfo( 'slave' ) ) {
1390 return true; // server is not a slave DB
1393 $pos = $pos ?
: $this->getConnection( DB_MASTER
)->getMasterPos();
1395 return false; // something is misconfigured
1398 $result = $conn->masterPosWait( $pos, $timeout );
1399 if ( $result == -1 ||
is_null( $result ) ) {
1400 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1401 wfDebugLog( 'replication', "$msg\n" );
1402 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1405 wfDebugLog( 'replication', __METHOD__
. ": Done\n" );
1413 * Clear the cache for slag lag delay times
1415 * This is only used for testing
1417 public function clearLagTimeCache() {
1418 $this->getLoadMonitor()->clearCaches();