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 replica DB lag as a factor in replica DB selection */
40 private $mAllowLagged;
41 /** @var integer Seconds to spend waiting on replica DB 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;
52 /** @var WANObjectCache */
54 /** @var TransactionProfiler */
55 protected $trxProfiler;
57 /** @var bool|DatabaseBase Database connection that caused a problem */
58 private $mErrorConnection;
59 /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
61 /** @var bool|DBMasterPos False if not set */
63 /** @var bool Whether the generic reader fell back to a lagged replica DB */
64 private $laggedReplicaMode = false;
65 /** @var bool Whether the generic reader fell back to a lagged replica DB */
66 private $allReplicasDownMode = false;
67 /** @var string The last DB selection or connection error */
68 private $mLastError = 'Unknown error';
69 /** @var string|bool Reason the LB is read-only or false if not */
70 private $readOnlyReason = false;
71 /** @var integer Total connections opened */
72 private $connsOpened = 0;
73 /** @var string|bool String if a requested DBO_TRX transaction round is active */
74 private $trxRoundId = false;
75 /** @var array[] Map of (name => callable) */
76 private $trxRecurringCallbacks = [];
78 /** @var integer Warn when this many connection are held */
79 const CONN_HELD_WARN_THRESHOLD
= 10;
80 /** @var integer Default 'max lag' when unspecified */
81 const MAX_LAG_DEFAULT
= 10;
82 /** @var integer Max time to wait for a replica DB to catch up (e.g. ChronologyProtector) */
83 const POS_WAIT_TIMEOUT
= 10;
84 /** @var integer Seconds to cache master server read-only status */
85 const TTL_CACHE_READONLY
= 5;
90 private $disabled = false;
93 * @param array $params Array with keys:
94 * - servers : Required. Array of server info structures.
95 * - loadMonitor : Name of a class used to fetch server lag and load.
96 * - readOnlyReason : Reason the master DB is read-only if so [optional]
97 * - srvCache : BagOStuff object [optional]
98 * - wanCache : WANObjectCache object [optional]
101 public function __construct( array $params ) {
102 if ( !isset( $params['servers'] ) ) {
103 throw new MWException( __CLASS__
. ': missing servers parameter' );
105 $this->mServers
= $params['servers'];
106 $this->mWaitTimeout
= self
::POS_WAIT_TIMEOUT
;
108 $this->mReadIndex
= -1;
109 $this->mWriteIndex
= -1;
113 'foreignFree' => [] ];
115 $this->mWaitForPos
= false;
116 $this->mErrorConnection
= false;
117 $this->mAllowLagged
= false;
119 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
120 $this->readOnlyReason
= $params['readOnlyReason'];
123 if ( isset( $params['loadMonitor'] ) ) {
124 $this->mLoadMonitorClass
= $params['loadMonitor'];
126 $master = reset( $params['servers'] );
127 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
128 $this->mLoadMonitorClass
= 'LoadMonitorMySQL';
130 $this->mLoadMonitorClass
= 'LoadMonitorNull';
134 foreach ( $params['servers'] as $i => $server ) {
135 $this->mLoads
[$i] = $server['load'];
136 if ( isset( $server['groupLoads'] ) ) {
137 foreach ( $server['groupLoads'] as $group => $ratio ) {
138 if ( !isset( $this->mGroupLoads
[$group] ) ) {
139 $this->mGroupLoads
[$group] = [];
141 $this->mGroupLoads
[$group][$i] = $ratio;
146 if ( isset( $params['srvCache'] ) ) {
147 $this->srvCache
= $params['srvCache'];
149 $this->srvCache
= new EmptyBagOStuff();
151 if ( isset( $params['wanCache'] ) ) {
152 $this->wanCache
= $params['wanCache'];
154 $this->wanCache
= WANObjectCache
::newEmpty();
156 if ( isset( $params['trxProfiler'] ) ) {
157 $this->trxProfiler
= $params['trxProfiler'];
159 $this->trxProfiler
= new TransactionProfiler();
164 * Get a LoadMonitor instance
166 * @return LoadMonitor
168 private function getLoadMonitor() {
169 if ( !isset( $this->mLoadMonitor
) ) {
170 $class = $this->mLoadMonitorClass
;
171 $this->mLoadMonitor
= new $class( $this );
174 return $this->mLoadMonitor
;
178 * Get or set arbitrary data used by the parent object, usually an LBFactory
182 public function parentInfo( $x = null ) {
183 return wfSetVar( $this->mParentInfo
, $x );
187 * @param array $loads
188 * @param bool|string $wiki Wiki to get non-lagged for
189 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
190 * @return bool|int|string
192 private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = INF
) {
193 $lags = $this->getLagTimes( $wiki );
195 # Unset excessively lagged servers
196 foreach ( $lags as $i => $lag ) {
198 # How much lag this server nominally is allowed to have
199 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
200 ?
$this->mServers
[$i]['max lag']
201 : self
::MAX_LAG_DEFAULT
; // default
202 # Constrain that futher by $maxLag argument
203 $maxServerLag = min( $maxServerLag, $maxLag );
205 $host = $this->getServerName( $i );
206 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
207 wfDebugLog( 'replication', "Server $host (#$i) is not replicating?" );
209 } elseif ( $lag > $maxServerLag ) {
210 wfDebugLog( 'replication', "Server $host (#$i) has >= $lag seconds of lag" );
216 # Find out if all the replica DBs with non-zero load are lagged
218 foreach ( $loads as $load ) {
222 # No appropriate DB servers except maybe the master and some replica DBs with zero load
223 # Do NOT use the master
224 # Instead, this function will return false, triggering read-only mode,
225 # and a lagged replica DB will be used instead.
229 if ( count( $loads ) == 0 ) {
233 # Return a random representative of the remainder
234 return ArrayUtils
::pickRandom( $loads );
238 * Get the index of the reader connection, which may be a replica DB
239 * This takes into account load ratios and lag times. It should
240 * always return a consistent index during a given invocation
242 * Side effect: opens connections to databases
243 * @param string|bool $group Query group, or false for the generic reader
244 * @param string|bool $wiki Wiki ID, or false for the current wiki
245 * @throws MWException
246 * @return bool|int|string
248 public function getReaderIndex( $group = false, $wiki = false ) {
251 # @todo FIXME: For now, only go through all this for mysql databases
252 if ( $wgDBtype != 'mysql' ) {
253 return $this->getWriterIndex();
256 if ( count( $this->mServers
) == 1 ) {
257 # Skip the load balancing if there's only one server
259 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
260 # Shortcut if generic reader exists already
261 return $this->mReadIndex
;
264 # Find the relevant load array
265 if ( $group !== false ) {
266 if ( isset( $this->mGroupLoads
[$group] ) ) {
267 $nonErrorLoads = $this->mGroupLoads
[$group];
269 # No loads for this group, return false and the caller can use some other group
270 wfDebugLog( 'connect', __METHOD__
. ": no loads for group $group\n" );
275 $nonErrorLoads = $this->mLoads
;
278 if ( !count( $nonErrorLoads ) ) {
279 throw new MWException( "Empty server array given to LoadBalancer" );
282 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
283 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
285 $laggedReplicaMode = false;
287 # No server found yet
289 # First try quickly looking through the available servers for a server that
291 $currentLoads = $nonErrorLoads;
292 while ( count( $currentLoads ) ) {
293 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
294 $i = ArrayUtils
::pickRandom( $currentLoads );
297 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
298 # ChronologyProtecter causes mWaitForPos to be set via sessions.
299 # This triggers doWait() after connect, so it's especially good to
300 # avoid lagged servers so as to avoid just blocking in that method.
301 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
302 # Aim for <= 1 second of waiting (being too picky can backfire)
303 $i = $this->getRandomNonLagged( $currentLoads, $wiki, $ago +
1 );
305 if ( $i === false ) {
306 # Any server with less lag than it's 'max lag' param is preferable
307 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
309 if ( $i === false && count( $currentLoads ) != 0 ) {
310 # All replica DBs lagged. Switch to read-only mode
311 wfDebugLog( 'replication', "All replica DBs lagged. Switch to read-only mode" );
312 $i = ArrayUtils
::pickRandom( $currentLoads );
313 $laggedReplicaMode = true;
317 if ( $i === false ) {
318 # pickRandom() returned false
319 # This is permanent and means the configuration or the load monitor
320 # wants us to return false.
321 wfDebugLog( 'connect', __METHOD__
. ": pickRandom() returned false" );
326 $serverName = $this->getServerName( $i );
327 wfDebugLog( 'connect', __METHOD__
. ": Using reader #$i: $serverName..." );
329 $conn = $this->openConnection( $i, $wiki );
331 wfDebugLog( 'connect', __METHOD__
. ": Failed connecting to $i/$wiki" );
332 unset( $nonErrorLoads[$i] );
333 unset( $currentLoads[$i] );
338 // Decrement reference counter, we are finished with this connection.
339 // It will be incremented for the caller later.
340 if ( $wiki !== false ) {
341 $this->reuseConnection( $conn );
348 # If all servers were down, quit now
349 if ( !count( $nonErrorLoads ) ) {
350 wfDebugLog( 'connect', "All servers down" );
353 if ( $i !== false ) {
354 # Replica DB connection successful.
355 # Wait for the session master pos for a short time.
356 if ( $this->mWaitForPos
&& $i > 0 ) {
359 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
360 $this->mReadIndex
= $i;
361 # Record if the generic reader index is in "lagged replica DB" mode
362 if ( $laggedReplicaMode ) {
363 $this->laggedReplicaMode
= true;
366 $serverName = $this->getServerName( $i );
367 wfDebugLog( 'connect', __METHOD__
.
368 ": using server $serverName for group '$group'\n" );
375 * Set the master wait position
376 * If a DB_REPLICA connection has been opened already, waits
377 * Otherwise sets a variable telling it to wait if such a connection is opened
378 * @param DBMasterPos $pos
380 public function waitFor( $pos ) {
381 $this->mWaitForPos
= $pos;
382 $i = $this->mReadIndex
;
385 if ( !$this->doWait( $i ) ) {
386 $this->laggedReplicaMode
= true;
392 * Set the master wait position and wait for a "generic" replica DB to catch up to it
394 * This can be used a faster proxy for waitForAll()
396 * @param DBMasterPos $pos
397 * @param int $timeout Max seconds to wait; default is mWaitTimeout
398 * @return bool Success (able to connect and no timeouts reached)
401 public function waitForOne( $pos, $timeout = null ) {
402 $this->mWaitForPos
= $pos;
404 $i = $this->mReadIndex
;
406 // Pick a generic replica DB if there isn't one yet
407 $readLoads = $this->mLoads
;
408 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
409 $readLoads = array_filter( $readLoads ); // with non-zero load
410 $i = ArrayUtils
::pickRandom( $readLoads );
414 $ok = $this->doWait( $i, true, $timeout );
416 $ok = true; // no applicable loads
423 * Set the master wait position and wait for ALL replica DBs to catch up to it
424 * @param DBMasterPos $pos
425 * @param int $timeout Max seconds to wait; default is mWaitTimeout
426 * @return bool Success (able to connect and no timeouts reached)
428 public function waitForAll( $pos, $timeout = null ) {
429 $this->mWaitForPos
= $pos;
430 $serverCount = count( $this->mServers
);
433 for ( $i = 1; $i < $serverCount; $i++
) {
434 if ( $this->mLoads
[$i] > 0 ) {
435 $ok = $this->doWait( $i, true, $timeout ) && $ok;
443 * Get any open connection to a given server index, local or foreign
444 * Returns false if there is no connection open
447 * @return DatabaseBase|bool False on failure
449 public function getAnyOpenConnection( $i ) {
450 foreach ( $this->mConns
as $conns ) {
451 if ( !empty( $conns[$i] ) ) {
452 return reset( $conns[$i] );
460 * Wait for a given replica DB to catch up to the master pos stored in $this
461 * @param int $index Server index
462 * @param bool $open Check the server even if a new connection has to be made
463 * @param int $timeout Max seconds to wait; default is mWaitTimeout
466 protected function doWait( $index, $open = false, $timeout = null ) {
467 $close = false; // close the connection afterwards
469 // Check if we already know that the DB has reached this point
470 $server = $this->getServerName( $index );
471 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server );
472 /** @var DBMasterPos $knownReachedPos */
473 $knownReachedPos = $this->srvCache
->get( $key );
474 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos
) ) {
475 wfDebugLog( 'replication', __METHOD__
.
476 ": replica DB $server known to be caught up (pos >= $knownReachedPos).\n" );
480 // Find a connection to wait on, creating one if needed and allowed
481 $conn = $this->getAnyOpenConnection( $index );
484 wfDebugLog( 'replication', __METHOD__
. ": no connection open for $server\n" );
488 $conn = $this->openConnection( $index, '' );
490 wfDebugLog( 'replication', __METHOD__
. ": failed to connect to $server\n" );
494 // Avoid connection spam in waitForAll() when connections
495 // are made just for the sake of doing this lag check.
500 wfDebugLog( 'replication', __METHOD__
. ": Waiting for replica DB $server to catch up...\n" );
501 $timeout = $timeout ?
: $this->mWaitTimeout
;
502 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
504 if ( $result == -1 ||
is_null( $result ) ) {
505 // Timed out waiting for replica DB, use master instead
506 $msg = __METHOD__
. ": Timed out waiting on $server pos {$this->mWaitForPos}";
507 wfDebugLog( 'replication', "$msg\n" );
508 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
511 wfDebugLog( 'replication', __METHOD__
. ": Done\n" );
513 // Remember that the DB reached this point
514 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
518 $this->closeConnection( $conn );
525 * Get a connection by index
526 * This is the main entry point for this class.
528 * @param int $i Server index
529 * @param array|string|bool $groups Query group(s), or false for the generic reader
530 * @param string|bool $wiki Wiki ID, or false for the current wiki
532 * @throws MWException
533 * @return DatabaseBase
535 public function getConnection( $i, $groups = [], $wiki = false ) {
536 if ( $i === null ||
$i === false ) {
537 throw new MWException( 'Attempt to call ' . __METHOD__
.
538 ' with invalid server index' );
541 if ( $wiki === wfWikiID() ) {
545 $groups = ( $groups === false ||
$groups === [] )
546 ?
[ false ] // check one "group": the generic pool
549 $masterOnly = ( $i == DB_MASTER ||
$i == $this->getWriterIndex() );
550 $oldConnsOpened = $this->connsOpened
; // connections open now
552 if ( $i == DB_MASTER
) {
553 $i = $this->getWriterIndex();
555 # Try to find an available server in any the query groups (in order)
556 foreach ( $groups as $group ) {
557 $groupIndex = $this->getReaderIndex( $group, $wiki );
558 if ( $groupIndex !== false ) {
565 # Operation-based index
566 if ( $i == DB_REPLICA
) {
567 $this->mLastError
= 'Unknown error'; // reset error string
568 # Try the general server pool if $groups are unavailable.
569 $i = in_array( false, $groups, true )
570 ?
false // don't bother with this if that is what was tried above
571 : $this->getReaderIndex( false, $wiki );
572 # Couldn't find a working server in getReaderIndex()?
573 if ( $i === false ) {
574 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
576 return $this->reportConnectionError();
580 # Now we have an explicit index into the servers array
581 $conn = $this->openConnection( $i, $wiki );
583 return $this->reportConnectionError();
586 # Profile any new connections that happen
587 if ( $this->connsOpened
> $oldConnsOpened ) {
588 $host = $conn->getServer();
589 $dbname = $conn->getDBname();
590 $trxProf = Profiler
::instance()->getTransactionProfiler();
591 $trxProf->recordConnection( $host, $dbname, $masterOnly );
595 # Make master-requested DB handles inherit any read-only mode setting
596 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $wiki, $conn ) );
603 * Mark a foreign connection as being available for reuse under a different
604 * DB name or prefix. This mechanism is reference-counted, and must be called
605 * the same number of times as getConnection() to work.
607 * @param DatabaseBase $conn
608 * @throws MWException
610 public function reuseConnection( $conn ) {
611 $serverIndex = $conn->getLBInfo( 'serverIndex' );
612 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
613 if ( $serverIndex === null ||
$refCount === null ) {
615 * This can happen in code like:
616 * foreach ( $dbs as $db ) {
617 * $conn = $lb->getConnection( DB_REPLICA, [], $db );
619 * $lb->reuseConnection( $conn );
621 * When a connection to the local DB is opened in this way, reuseConnection()
627 $dbName = $conn->getDBname();
628 $prefix = $conn->tablePrefix();
629 if ( strval( $prefix ) !== '' ) {
630 $wiki = "$dbName-$prefix";
634 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
635 throw new MWException( __METHOD__
. ": connection not found, has " .
636 "the connection been freed already?" );
638 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
639 if ( $refCount <= 0 ) {
640 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
641 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
642 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
644 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
649 * Get a database connection handle reference
651 * The handle's methods wrap simply wrap those of a DatabaseBase handle
653 * @see LoadBalancer::getConnection() for parameter information
656 * @param array|string|bool $groups Query group(s), or false for the generic reader
657 * @param string|bool $wiki Wiki ID, or false for the current wiki
660 public function getConnectionRef( $db, $groups = [], $wiki = false ) {
661 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
665 * Get a database connection handle reference without connecting yet
667 * The handle's methods wrap simply wrap those of a DatabaseBase handle
669 * @see LoadBalancer::getConnection() for parameter information
672 * @param array|string|bool $groups Query group(s), or false for the generic reader
673 * @param string|bool $wiki Wiki ID, or false for the current wiki
676 public function getLazyConnectionRef( $db, $groups = [], $wiki = false ) {
677 return new DBConnRef( $this, [ $db, $groups, $wiki ] );
681 * Open a connection to the server given by the specified index
682 * Index must be an actual index into the array.
683 * If the server is already open, returns it.
685 * On error, returns false, and the connection which caused the
686 * error will be available via $this->mErrorConnection.
688 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
690 * @param int $i Server index
691 * @param string|bool $wiki Wiki ID, or false for the current wiki
692 * @return DatabaseBase|bool Returns false on errors
694 public function openConnection( $i, $wiki = false ) {
695 if ( $wiki !== false ) {
696 $conn = $this->openForeignConnection( $i, $wiki );
697 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
698 $conn = $this->mConns
['local'][$i][0];
700 $server = $this->mServers
[$i];
701 $server['serverIndex'] = $i;
702 $conn = $this->reallyOpenConnection( $server, false );
703 $serverName = $this->getServerName( $i );
704 if ( $conn->isOpen() ) {
705 wfDebugLog( 'connect', "Connected to database $i at $serverName\n" );
706 $this->mConns
['local'][$i][0] = $conn;
708 wfDebugLog( 'connect', "Failed to connect to database $i at $serverName\n" );
709 $this->mErrorConnection
= $conn;
714 if ( $conn && !$conn->isOpen() ) {
715 // Connection was made but later unrecoverably lost for some reason.
716 // Do not return a handle that will just throw exceptions on use,
717 // but let the calling code (e.g. getReaderIndex) try another server.
718 // See DatabaseMyslBase::ping() for how this can happen.
719 $this->mErrorConnection
= $conn;
727 * Open a connection to a foreign DB, or return one if it is already open.
729 * Increments a reference count on the returned connection which locks the
730 * connection to the requested wiki. This reference count can be
731 * decremented by calling reuseConnection().
733 * If a connection is open to the appropriate server already, but with the wrong
734 * database, it will be switched to the right database and returned, as long as
735 * it has been freed first with reuseConnection().
737 * On error, returns false, and the connection which caused the
738 * error will be available via $this->mErrorConnection.
740 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
742 * @param int $i Server index
743 * @param string $wiki Wiki ID to open
744 * @return DatabaseBase
746 private function openForeignConnection( $i, $wiki ) {
747 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
748 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
749 // Reuse an already-used connection
750 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
751 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
752 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
753 // Reuse a free connection for the same wiki
754 $conn = $this->mConns
['foreignFree'][$i][$wiki];
755 unset( $this->mConns
['foreignFree'][$i][$wiki] );
756 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
757 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
758 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
759 // Reuse a connection from another wiki
760 $conn = reset( $this->mConns
['foreignFree'][$i] );
761 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
763 // The empty string as a DB name means "don't care".
764 // DatabaseMysqlBase::open() already handle this on connection.
765 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
766 $this->mLastError
= "Error selecting database $dbName on server " .
767 $conn->getServer() . " from client host " . wfHostname() . "\n";
768 $this->mErrorConnection
= $conn;
771 $conn->tablePrefix( $prefix );
772 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
773 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
774 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
777 // Open a new connection
778 $server = $this->mServers
[$i];
779 $server['serverIndex'] = $i;
780 $server['foreignPoolRefCount'] = 0;
781 $server['foreign'] = true;
782 $conn = $this->reallyOpenConnection( $server, $dbName );
783 if ( !$conn->isOpen() ) {
784 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
785 $this->mErrorConnection
= $conn;
788 $conn->tablePrefix( $prefix );
789 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
790 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
794 // Increment reference count
796 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
797 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
804 * Test if the specified index represents an open connection
806 * @param int $index Server index
810 private function isOpen( $index ) {
811 if ( !is_integer( $index ) ) {
815 return (bool)$this->getAnyOpenConnection( $index );
819 * Really opens a connection. Uncached.
820 * Returns a Database object whether or not the connection was successful.
823 * @param array $server
824 * @param bool $dbNameOverride
825 * @throws MWException
826 * @return DatabaseBase
828 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
829 if ( $this->disabled
) {
830 throw new DBAccessError();
833 if ( !is_array( $server ) ) {
834 throw new MWException( 'You must update your load-balancing configuration. ' .
835 'See DefaultSettings.php entry for $wgDBservers.' );
838 if ( $dbNameOverride !== false ) {
839 $server['dbname'] = $dbNameOverride;
842 // Let the handle know what the cluster master is (e.g. "db1052")
843 $masterName = $this->getServerName( 0 );
844 $server['clusterMasterHost'] = $masterName;
846 // Log when many connection are made on requests
847 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
848 wfDebugLog( 'DBPerformance', __METHOD__
. ": " .
849 "{$this->connsOpened}+ connections made (master=$masterName)\n" .
850 wfBacktrace( true ) );
855 $db = DatabaseBase
::factory( $server['type'], $server );
856 } catch ( DBConnectionError
$e ) {
857 // FIXME: This is probably the ugliest thing I have ever done to
858 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
862 $db->setLBInfo( $server );
863 $db->setLazyMasterHandle(
864 $this->getLazyConnectionRef( DB_MASTER
, [], $db->getWikiID() )
866 $db->setTransactionProfiler( $this->trxProfiler
);
868 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
869 if ( $this->trxRoundId
!== false ) {
870 $this->applyTransactionRoundFlags( $db );
872 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
873 $db->setTransactionListener( $name, $callback );
881 * @throws DBConnectionError
884 private function reportConnectionError() {
885 $conn = $this->mErrorConnection
; // The connection which caused the error
887 'method' => __METHOD__
,
888 'last_error' => $this->mLastError
,
891 if ( !is_object( $conn ) ) {
892 // No last connection, probably due to all servers being too busy
894 "LB failure with no last connection. Connection error: {last_error}",
898 // If all servers were busy, mLastError will contain something sensible
899 throw new DBConnectionError( null, $this->mLastError
);
901 $context['db_server'] = $conn->getProperty( 'mServer' );
903 "Connection error: {last_error} ({db_server})",
907 // throws DBConnectionError
908 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
911 return false; /* not reached */
918 public function getWriterIndex() {
923 * Returns true if the specified index is a valid server index
928 public function haveIndex( $i ) {
929 return array_key_exists( $i, $this->mServers
);
933 * Returns true if the specified index is valid and has non-zero load
938 public function isNonZeroLoad( $i ) {
939 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
943 * Get the number of defined servers (not the number of open connections)
947 public function getServerCount() {
948 return count( $this->mServers
);
952 * Get the host name or IP address of the server with the specified index
953 * Prefer a readable name if available.
957 public function getServerName( $i ) {
958 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
959 $name = $this->mServers
[$i]['hostName'];
960 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
961 $name = $this->mServers
[$i]['host'];
966 return ( $name != '' ) ?
$name : 'localhost';
970 * Return the server info structure for a given index, or false if the index is invalid.
974 public function getServerInfo( $i ) {
975 if ( isset( $this->mServers
[$i] ) ) {
976 return $this->mServers
[$i];
983 * Sets the server info structure for the given index. Entry at index $i
984 * is created if it doesn't exist
986 * @param array $serverInfo
988 public function setServerInfo( $i, array $serverInfo ) {
989 $this->mServers
[$i] = $serverInfo;
993 * Get the current master position for chronology control purposes
996 public function getMasterPos() {
997 # If this entire request was served from a replica DB without opening a connection to the
998 # master (however unlikely that may be), then we can fetch the position from the replica DB.
999 $masterConn = $this->getAnyOpenConnection( 0 );
1000 if ( !$masterConn ) {
1001 $serverCount = count( $this->mServers
);
1002 for ( $i = 1; $i < $serverCount; $i++
) {
1003 $conn = $this->getAnyOpenConnection( $i );
1005 return $conn->getSlavePos();
1009 return $masterConn->getMasterPos();
1016 * Disable this load balancer. All connections are closed, and any attempt to
1017 * open a new connection will result in a DBAccessError.
1021 public function disable() {
1023 $this->disabled
= true;
1027 * Close all open connections
1029 public function closeAll() {
1030 $this->forEachOpenConnection( function ( DatabaseBase
$conn ) {
1036 'foreignFree' => [],
1037 'foreignUsed' => [],
1039 $this->connsOpened
= 0;
1043 * Close a connection
1044 * Using this function makes sure the LoadBalancer knows the connection is closed.
1045 * If you use $conn->close() directly, the load balancer won't update its state.
1046 * @param DatabaseBase $conn
1048 public function closeConnection( $conn ) {
1050 foreach ( $this->mConns
as $i1 => $conns2 ) {
1051 foreach ( $conns2 as $i2 => $conns3 ) {
1052 foreach ( $conns3 as $i3 => $candidateConn ) {
1053 if ( $conn === $candidateConn ) {
1055 unset( $this->mConns
[$i1][$i2][$i3] );
1056 --$this->connsOpened
;
1069 * Commit transactions on all open connections
1070 * @param string $fname Caller name
1071 * @throws DBExpectedError
1073 public function commitAll( $fname = __METHOD__
) {
1076 $restore = ( $this->trxRoundId
!== false );
1077 $this->trxRoundId
= false;
1078 $this->forEachOpenConnection(
1079 function ( DatabaseBase
$conn ) use ( $fname, $restore, &$failures ) {
1081 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1082 } catch ( DBError
$e ) {
1083 MWExceptionHandler
::logException( $e );
1084 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1086 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1087 $this->undoTransactionRoundFlags( $conn );
1093 throw new DBExpectedError(
1095 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1101 * Perform all pre-commit callbacks that remain part of the atomic transactions
1102 * and disable any post-commit callbacks until runMasterPostTrxCallbacks()
1105 public function finalizeMasterChanges() {
1106 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) {
1107 // Any error should cause all DB transactions to be rolled back together
1108 $conn->setTrxEndCallbackSuppression( false );
1109 $conn->runOnTransactionPreCommitCallbacks();
1110 // Defer post-commit callbacks until COMMIT finishes for all DBs
1111 $conn->setTrxEndCallbackSuppression( true );
1116 * Perform all pre-commit checks for things like replication safety
1117 * @param array $options Includes:
1118 * - maxWriteDuration : max write query duration time in seconds
1119 * @throws DBTransactionError
1122 public function approveMasterChanges( array $options ) {
1123 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1124 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) use ( $limit ) {
1125 // If atomic sections or explicit transactions are still open, some caller must have
1126 // caught an exception but failed to properly rollback any changes. Detect that and
1127 // throw and error (causing rollback).
1128 if ( $conn->explicitTrxActive() ) {
1129 throw new DBTransactionError(
1131 "Explicit transaction still active. A caller may have caught an error."
1134 // Assert that the time to replicate the transaction will be sane.
1135 // If this fails, then all DB transactions will be rollback back together.
1136 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1137 if ( $limit > 0 && $time > $limit ) {
1138 throw new DBTransactionError(
1140 wfMessage( 'transaction-duration-limit-exceeded', $time, $limit )->text()
1143 // If a connection sits idle while slow queries execute on another, that connection
1144 // may end up dropped before the commit round is reached. Ping servers to detect this.
1145 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1146 throw new DBTransactionError(
1148 "A connection to the {$conn->getDBname()} database was lost before commit."
1155 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
1157 * The DBO_TRX setting will be reverted to the default in each of these methods:
1158 * - commitMasterChanges()
1159 * - rollbackMasterChanges()
1161 * This allows for custom transaction rounds from any outer transaction scope.
1163 * @param string $fname
1164 * @throws DBExpectedError
1167 public function beginMasterChanges( $fname = __METHOD__
) {
1168 if ( $this->trxRoundId
!== false ) {
1169 throw new DBTransactionError(
1171 "$fname: Transaction round '{$this->trxRoundId}' already started."
1174 $this->trxRoundId
= $fname;
1177 $this->forEachOpenMasterConnection(
1178 function ( DatabaseBase
$conn ) use ( $fname, &$failures ) {
1179 $conn->setTrxEndCallbackSuppression( true );
1181 $conn->clearSnapshot( $fname );
1182 } catch ( DBError
$e ) {
1183 MWExceptionHandler
::logException( $e );
1184 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1186 $conn->setTrxEndCallbackSuppression( false );
1187 $this->applyTransactionRoundFlags( $conn );
1192 throw new DBExpectedError(
1194 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1200 * Issue COMMIT on all master connections where writes where done
1201 * @param string $fname Caller name
1202 * @throws DBExpectedError
1204 public function commitMasterChanges( $fname = __METHOD__
) {
1207 $restore = ( $this->trxRoundId
!== false );
1208 $this->trxRoundId
= false;
1209 $this->forEachOpenMasterConnection(
1210 function ( DatabaseBase
$conn ) use ( $fname, $restore, &$failures ) {
1212 if ( $conn->writesOrCallbacksPending() ) {
1213 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1214 } elseif ( $restore ) {
1215 $conn->clearSnapshot( $fname );
1217 } catch ( DBError
$e ) {
1218 MWExceptionHandler
::logException( $e );
1219 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1222 $this->undoTransactionRoundFlags( $conn );
1228 throw new DBExpectedError(
1230 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1236 * Issue all pending post-COMMIT/ROLLBACK callbacks
1237 * @param integer $type IDatabase::TRIGGER_* constant
1238 * @return Exception|null The first exception or null if there were none
1241 public function runMasterPostTrxCallbacks( $type ) {
1242 $e = null; // first exception
1243 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) use ( $type, &$e ) {
1244 $conn->clearSnapshot( __METHOD__
); // clear no-op transactions
1246 $conn->setTrxEndCallbackSuppression( false );
1248 $conn->runOnTransactionIdleCallbacks( $type );
1249 } catch ( Exception
$ex ) {
1253 $conn->runTransactionListenerCallbacks( $type );
1254 } catch ( Exception
$ex ) {
1263 * Issue ROLLBACK only on master, only if queries were done on connection
1264 * @param string $fname Caller name
1265 * @throws DBExpectedError
1268 public function rollbackMasterChanges( $fname = __METHOD__
) {
1269 $restore = ( $this->trxRoundId
!== false );
1270 $this->trxRoundId
= false;
1271 $this->forEachOpenMasterConnection(
1272 function ( DatabaseBase
$conn ) use ( $fname, $restore ) {
1273 if ( $conn->writesOrCallbacksPending() ) {
1274 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1277 $this->undoTransactionRoundFlags( $conn );
1284 * Suppress all pending post-COMMIT/ROLLBACK callbacks
1285 * @return Exception|null The first exception or null if there were none
1288 public function suppressTransactionEndCallbacks() {
1289 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) {
1290 $conn->setTrxEndCallbackSuppression( true );
1295 * @param DatabaseBase $conn
1297 private function applyTransactionRoundFlags( DatabaseBase
$conn ) {
1298 if ( $conn->getFlag( DBO_DEFAULT
) ) {
1299 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1300 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1301 $conn->setFlag( DBO_TRX
, $conn::REMEMBER_PRIOR
);
1302 // If config has explicitly requested DBO_TRX be either on or off by not
1303 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1304 // for things like blob stores (ExternalStore) which want auto-commit mode.
1309 * @param DatabaseBase $conn
1311 private function undoTransactionRoundFlags( DatabaseBase
$conn ) {
1312 if ( $conn->getFlag( DBO_DEFAULT
) ) {
1313 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1318 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
1320 * @param string $fname Caller name
1323 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1324 $this->forEachOpenReplicaConnection( function ( DatabaseBase
$conn ) {
1325 $conn->clearSnapshot( __METHOD__
);
1330 * @return bool Whether a master connection is already open
1333 public function hasMasterConnection() {
1334 return $this->isOpen( $this->getWriterIndex() );
1338 * Determine if there are pending changes in a transaction by this thread
1342 public function hasMasterChanges() {
1343 $masterIndex = $this->getWriterIndex();
1344 foreach ( $this->mConns
as $conns2 ) {
1345 if ( empty( $conns2[$masterIndex] ) ) {
1348 /** @var DatabaseBase $conn */
1349 foreach ( $conns2[$masterIndex] as $conn ) {
1350 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1359 * Get the timestamp of the latest write query done by this thread
1361 * @return float|bool UNIX timestamp or false
1363 public function lastMasterChangeTimestamp() {
1365 $masterIndex = $this->getWriterIndex();
1366 foreach ( $this->mConns
as $conns2 ) {
1367 if ( empty( $conns2[$masterIndex] ) ) {
1370 /** @var DatabaseBase $conn */
1371 foreach ( $conns2[$masterIndex] as $conn ) {
1372 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1379 * Check if this load balancer object had any recent or still
1380 * pending writes issued against it by this PHP thread
1382 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
1386 public function hasOrMadeRecentMasterChanges( $age = null ) {
1387 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1389 return ( $this->hasMasterChanges()
1390 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1394 * Get the list of callers that have pending master changes
1399 public function pendingMasterChangeCallers() {
1402 $masterIndex = $this->getWriterIndex();
1403 foreach ( $this->mConns
as $conns2 ) {
1404 if ( empty( $conns2[$masterIndex] ) ) {
1407 /** @var DatabaseBase $conn */
1408 foreach ( $conns2[$masterIndex] as $conn ) {
1409 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1417 * @param mixed $value
1420 public function waitTimeout( $value = null ) {
1421 return wfSetVar( $this->mWaitTimeout
, $value );
1425 * @note This method will trigger a DB connection if not yet done
1426 * @param string|bool $wiki Wiki ID, or false for the current wiki
1427 * @return bool Whether the generic connection for reads is highly "lagged"
1429 public function getLaggedReplicaMode( $wiki = false ) {
1430 // No-op if there is only one DB (also avoids recursion)
1431 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1433 // See if laggedReplicaMode gets set
1434 $conn = $this->getConnection( DB_REPLICA
, false, $wiki );
1435 $this->reuseConnection( $conn );
1436 } catch ( DBConnectionError
$e ) {
1437 // Avoid expensive re-connect attempts and failures
1438 $this->allReplicasDownMode
= true;
1439 $this->laggedReplicaMode
= true;
1443 return $this->laggedReplicaMode
;
1449 * @deprecated 1.28; use getLaggedReplicaMode()
1451 public function getLaggedSlaveMode( $wiki = false ) {
1452 return $this->getLaggedReplicaMode( $wiki );
1456 * @note This method will never cause a new DB connection
1457 * @return bool Whether any generic connection used for reads was highly "lagged"
1460 public function laggedReplicaUsed() {
1461 return $this->laggedReplicaMode
;
1467 * @deprecated Since 1.28; use laggedReplicaUsed()
1469 public function laggedSlaveUsed() {
1470 return $this->laggedReplicaUsed();
1474 * @note This method may trigger a DB connection if not yet done
1475 * @param string|bool $wiki Wiki ID, or false for the current wiki
1476 * @param DatabaseBase|null DB master connection; used to avoid loops [optional]
1477 * @return string|bool Reason the master is read-only or false if it is not
1480 public function getReadOnlyReason( $wiki = false, DatabaseBase
$conn = null ) {
1481 if ( $this->readOnlyReason
!== false ) {
1482 return $this->readOnlyReason
;
1483 } elseif ( $this->getLaggedReplicaMode( $wiki ) ) {
1484 if ( $this->allReplicasDownMode
) {
1485 return 'The database has been automatically locked ' .
1486 'until the replica database servers become available';
1488 return 'The database has been automatically locked ' .
1489 'while the replica database servers catch up to the master.';
1491 } elseif ( $this->masterRunningReadOnly( $wiki, $conn ) ) {
1492 return 'The database master is running in read-only mode.';
1499 * @param string $wiki Wiki ID, or false for the current wiki
1500 * @param DatabaseBase|null DB master connectionl used to avoid loops [optional]
1503 private function masterRunningReadOnly( $wiki, DatabaseBase
$conn = null ) {
1504 $cache = $this->wanCache
;
1505 $masterServer = $this->getServerName( $this->getWriterIndex() );
1507 return (bool)$cache->getWithSetCallback(
1508 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1509 self
::TTL_CACHE_READONLY
,
1510 function () use ( $wiki, $conn ) {
1511 $this->trxProfiler
->setSilenced( true );
1513 $dbw = $conn ?
: $this->getConnection( DB_MASTER
, [], $wiki );
1514 $readOnly = (int)$dbw->serverIsReadOnly();
1515 } catch ( DBError
$e ) {
1518 $this->trxProfiler
->setSilenced( false );
1521 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1526 * Disables/enables lag checks
1527 * @param null|bool $mode
1530 public function allowLagged( $mode = null ) {
1531 if ( $mode === null ) {
1532 return $this->mAllowLagged
;
1534 $this->mAllowLagged
= $mode;
1536 return $this->mAllowLagged
;
1542 public function pingAll() {
1544 $this->forEachOpenConnection( function ( DatabaseBase
$conn ) use ( &$success ) {
1545 if ( !$conn->ping() ) {
1554 * Call a function with each open connection object
1555 * @param callable $callback
1556 * @param array $params
1558 public function forEachOpenConnection( $callback, array $params = [] ) {
1559 foreach ( $this->mConns
as $connsByServer ) {
1560 foreach ( $connsByServer as $serverConns ) {
1561 foreach ( $serverConns as $conn ) {
1562 $mergedParams = array_merge( [ $conn ], $params );
1563 call_user_func_array( $callback, $mergedParams );
1570 * Call a function with each open connection object to a master
1571 * @param callable $callback
1572 * @param array $params
1575 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1576 $masterIndex = $this->getWriterIndex();
1577 foreach ( $this->mConns
as $connsByServer ) {
1578 if ( isset( $connsByServer[$masterIndex] ) ) {
1579 /** @var DatabaseBase $conn */
1580 foreach ( $connsByServer[$masterIndex] as $conn ) {
1581 $mergedParams = array_merge( [ $conn ], $params );
1582 call_user_func_array( $callback, $mergedParams );
1589 * Call a function with each open replica DB connection object
1590 * @param callable $callback
1591 * @param array $params
1594 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1595 foreach ( $this->mConns
as $connsByServer ) {
1596 foreach ( $connsByServer as $i => $serverConns ) {
1597 if ( $i === $this->getWriterIndex() ) {
1598 continue; // skip master
1600 foreach ( $serverConns as $conn ) {
1601 $mergedParams = array_merge( [ $conn ], $params );
1602 call_user_func_array( $callback, $mergedParams );
1609 * Get the hostname and lag time of the most-lagged replica DB
1611 * This is useful for maintenance scripts that need to throttle their updates.
1612 * May attempt to open connections to replica DBs on the default DB. If there is
1613 * no lag, the maximum lag will be reported as -1.
1615 * @param bool|string $wiki Wiki ID, or false for the default database
1616 * @return array ( host, max lag, index of max lagged host )
1618 public function getMaxLag( $wiki = false ) {
1623 if ( $this->getServerCount() <= 1 ) {
1624 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1627 $lagTimes = $this->getLagTimes( $wiki );
1628 foreach ( $lagTimes as $i => $lag ) {
1629 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1631 $host = $this->mServers
[$i]['host'];
1636 return [ $host, $maxLag, $maxIndex ];
1640 * Get an estimate of replication lag (in seconds) for each server
1642 * Results are cached for a short time in memcached/process cache
1644 * Values may be "false" if replication is too broken to estimate
1646 * @param string|bool $wiki
1647 * @return int[] Map of (server index => float|int|bool)
1649 public function getLagTimes( $wiki = false ) {
1650 if ( $this->getServerCount() <= 1 ) {
1651 return [ 0 => 0 ]; // no replication = no lag
1654 # Send the request to the load monitor
1655 return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
1659 * Get the lag in seconds for a given connection, or zero if this load
1660 * balancer does not have replication enabled.
1662 * This should be used in preference to Database::getLag() in cases where
1663 * replication may not be in use, since there is no way to determine if
1664 * replication is in use at the connection level without running
1665 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1666 * function instead of Database::getLag() avoids a fatal error in this
1667 * case on many installations.
1669 * @param IDatabase $conn
1670 * @return int|bool Returns false on error
1672 public function safeGetLag( IDatabase
$conn ) {
1673 if ( $this->getServerCount() == 1 ) {
1676 return $conn->getLag();
1681 * Wait for a replica DB to reach a specified master position
1683 * This will connect to the master to get an accurate position if $pos is not given
1685 * @param IDatabase $conn Replica DB
1686 * @param DBMasterPos|bool $pos Master position; default: current position
1687 * @param integer $timeout Timeout in seconds
1688 * @return bool Success
1691 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1692 if ( $this->getServerCount() == 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1693 return true; // server is not a replica DB
1696 $pos = $pos ?
: $this->getConnection( DB_MASTER
)->getMasterPos();
1697 if ( !( $pos instanceof DBMasterPos
) ) {
1698 return false; // something is misconfigured
1701 $result = $conn->masterPosWait( $pos, $timeout );
1702 if ( $result == -1 ||
is_null( $result ) ) {
1703 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1704 wfDebugLog( 'replication', "$msg\n" );
1705 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1708 wfDebugLog( 'replication', __METHOD__
. ": Done\n" );
1716 * Clear the cache for slag lag delay times
1718 * This is only used for testing
1720 public function clearLagTimeCache() {
1721 $this->getLoadMonitor()->clearCaches();
1725 * Set a callback via DatabaseBase::setTransactionListener() on
1726 * all current and future master connections of this load balancer
1728 * @param string $name Callback name
1729 * @param callable|null $callback
1732 public function setTransactionListener( $name, callable
$callback = null ) {
1734 $this->trxRecurringCallbacks
[$name] = $callback;
1736 unset( $this->trxRecurringCallbacks
[$name] );
1738 $this->forEachOpenMasterConnection(
1739 function ( DatabaseBase
$conn ) use ( $name, $callback ) {
1740 $conn->setTransactionListener( $name, $callback );