3 * Database load balancing manager
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
23 use Psr\Log\LoggerInterface
;
26 * Database load balancing, tracking, and transaction management 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 string The LoadMonitor subclass name */
44 private $mLoadMonitorClass;
46 /** @var LoadMonitor */
47 private $mLoadMonitor;
50 /** @var WANObjectCache */
52 /** @var TransactionProfiler */
53 protected $trxProfiler;
54 /** @var LoggerInterface */
55 protected $replLogger;
56 /** @var LoggerInterface */
57 protected $connLogger;
58 /** @var LoggerInterface */
59 protected $queryLogger;
60 /** @var LoggerInterface */
61 protected $perfLogger;
63 /** @var bool|DatabaseBase Database connection that caused a problem */
64 private $mErrorConnection;
65 /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
67 /** @var bool|DBMasterPos False if not set */
69 /** @var bool Whether the generic reader fell back to a lagged replica DB */
70 private $laggedReplicaMode = false;
71 /** @var bool Whether the generic reader fell back to a lagged replica DB */
72 private $allReplicasDownMode = false;
73 /** @var string The last DB selection or connection error */
74 private $mLastError = 'Unknown error';
75 /** @var string|bool Reason the LB is read-only or false if not */
76 private $readOnlyReason = false;
77 /** @var integer Total connections opened */
78 private $connsOpened = 0;
79 /** @var string|bool String if a requested DBO_TRX transaction round is active */
80 private $trxRoundId = false;
81 /** @var array[] Map of (name => callable) */
82 private $trxRecurringCallbacks = [];
83 /** @var string Local Wiki ID and default for selectDB() calls */
85 /** @var callable Exception logger */
89 private $disabled = false;
91 /** @var integer Warn when this many connection are held */
92 const CONN_HELD_WARN_THRESHOLD
= 10;
93 /** @var integer Default 'max lag' when unspecified */
94 const MAX_LAG_DEFAULT
= 10;
95 /** @var integer Max time to wait for a replica DB to catch up (e.g. ChronologyProtector) */
96 const POS_WAIT_TIMEOUT
= 10;
97 /** @var integer Seconds to cache master server read-only status */
98 const TTL_CACHE_READONLY
= 5;
101 * @param array $params Array with keys:
102 * - servers : Required. Array of server info structures.
103 * - loadMonitor : Name of a class used to fetch server lag and load.
104 * - readOnlyReason : Reason the master DB is read-only if so [optional]
105 * - waitTimeout : Maximum time to wait for replicas for consistency [optional]
106 * - srvCache : BagOStuff object [optional]
107 * - wanCache : WANObjectCache object [optional]
108 * - localDomain: The wiki ID of the "local"/"current" wiki [optional]
109 * - errorLogger: Callback that takes an Exception and logs it [optional]
110 * - connLogger : LoggerInterface object [optional]
111 * - queryLogger : LoggerInterface object [optional]
112 * - replLogger : LoggerInterface object [optional]
113 * - perfLogger : LoggerInterface object [optional]
114 * @throws InvalidArgumentException
116 public function __construct( array $params ) {
117 if ( !isset( $params['servers'] ) ) {
118 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
120 $this->mServers
= $params['servers'];
121 $this->mWaitTimeout
= isset( $params['waitTimeout'] )
122 ?
$params['waitTimeout']
123 : self
::POS_WAIT_TIMEOUT
;
124 $this->localDomain
= isset( $params['localDomain'] ) ?
$params['localDomain'] : '';
126 $this->mReadIndex
= -1;
130 'foreignFree' => [] ];
132 $this->mWaitForPos
= false;
133 $this->mErrorConnection
= false;
134 $this->mAllowLagged
= false;
136 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
137 $this->readOnlyReason
= $params['readOnlyReason'];
140 if ( isset( $params['loadMonitor'] ) ) {
141 $this->mLoadMonitorClass
= $params['loadMonitor'];
143 $master = reset( $params['servers'] );
144 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
145 $this->mLoadMonitorClass
= 'LoadMonitorMySQL';
147 $this->mLoadMonitorClass
= 'LoadMonitorNull';
151 foreach ( $params['servers'] as $i => $server ) {
152 $this->mLoads
[$i] = $server['load'];
153 if ( isset( $server['groupLoads'] ) ) {
154 foreach ( $server['groupLoads'] as $group => $ratio ) {
155 if ( !isset( $this->mGroupLoads
[$group] ) ) {
156 $this->mGroupLoads
[$group] = [];
158 $this->mGroupLoads
[$group][$i] = $ratio;
163 if ( isset( $params['srvCache'] ) ) {
164 $this->srvCache
= $params['srvCache'];
166 $this->srvCache
= new EmptyBagOStuff();
168 if ( isset( $params['wanCache'] ) ) {
169 $this->wanCache
= $params['wanCache'];
171 $this->wanCache
= WANObjectCache
::newEmpty();
173 if ( isset( $params['trxProfiler'] ) ) {
174 $this->trxProfiler
= $params['trxProfiler'];
176 $this->trxProfiler
= new TransactionProfiler();
179 $this->errorLogger
= isset( $params['errorLogger'] )
180 ?
$params['errorLogger']
181 : function ( Exception
$e ) {
182 trigger_error( E_WARNING
, $e->getMessage() );
185 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
186 $this->$key = isset( $params[$key] ) ?
$params[$key] : new \Psr\Log\
NullLogger();
191 * Get a LoadMonitor instance
193 * @return LoadMonitor
195 private function getLoadMonitor() {
196 if ( !isset( $this->mLoadMonitor
) ) {
197 $class = $this->mLoadMonitorClass
;
198 $this->mLoadMonitor
= new $class( $this );
199 $this->mLoadMonitor
->setLogger( $this->replLogger
);
202 return $this->mLoadMonitor
;
206 * @param array $loads
207 * @param bool|string $wiki Wiki to get non-lagged for
208 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
209 * @return bool|int|string
211 private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = INF
) {
212 $lags = $this->getLagTimes( $wiki );
214 # Unset excessively lagged servers
215 foreach ( $lags as $i => $lag ) {
217 # How much lag this server nominally is allowed to have
218 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
219 ?
$this->mServers
[$i]['max lag']
220 : self
::MAX_LAG_DEFAULT
; // default
221 # Constrain that futher by $maxLag argument
222 $maxServerLag = min( $maxServerLag, $maxLag );
224 $host = $this->getServerName( $i );
225 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
226 $this->replLogger
->error( "Server $host (#$i) is not replicating?" );
228 } elseif ( $lag > $maxServerLag ) {
229 $this->replLogger
->warning( "Server $host (#$i) has >= $lag seconds of lag" );
235 # Find out if all the replica DBs with non-zero load are lagged
237 foreach ( $loads as $load ) {
241 # No appropriate DB servers except maybe the master and some replica DBs with zero load
242 # Do NOT use the master
243 # Instead, this function will return false, triggering read-only mode,
244 # and a lagged replica DB will be used instead.
248 if ( count( $loads ) == 0 ) {
252 # Return a random representative of the remainder
253 return ArrayUtils
::pickRandom( $loads );
257 * Get the index of the reader connection, which may be a replica DB
258 * This takes into account load ratios and lag times. It should
259 * always return a consistent index during a given invocation
261 * Side effect: opens connections to databases
262 * @param string|bool $group Query group, or false for the generic reader
263 * @param string|bool $wiki Wiki ID, or false for the current wiki
264 * @throws MWException
265 * @return bool|int|string
267 public function getReaderIndex( $group = false, $wiki = false ) {
268 if ( count( $this->mServers
) == 1 ) {
269 # Skip the load balancing if there's only one server
270 return $this->getWriterIndex();
271 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
272 # Shortcut if generic reader exists already
273 return $this->mReadIndex
;
276 # Find the relevant load array
277 if ( $group !== false ) {
278 if ( isset( $this->mGroupLoads
[$group] ) ) {
279 $nonErrorLoads = $this->mGroupLoads
[$group];
281 # No loads for this group, return false and the caller can use some other group
282 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
287 $nonErrorLoads = $this->mLoads
;
290 if ( !count( $nonErrorLoads ) ) {
291 throw new MWException( "Empty server array given to LoadBalancer" );
294 # Scale the configured load ratios according to the dynamic load if supported
295 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
297 $laggedReplicaMode = false;
299 # No server found yet
301 # First try quickly looking through the available servers for a server that
303 $currentLoads = $nonErrorLoads;
304 while ( count( $currentLoads ) ) {
305 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
306 $i = ArrayUtils
::pickRandom( $currentLoads );
309 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
310 # ChronologyProtecter causes mWaitForPos to be set via sessions.
311 # This triggers doWait() after connect, so it's especially good to
312 # avoid lagged servers so as to avoid just blocking in that method.
313 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
314 # Aim for <= 1 second of waiting (being too picky can backfire)
315 $i = $this->getRandomNonLagged( $currentLoads, $wiki, $ago +
1 );
317 if ( $i === false ) {
318 # Any server with less lag than it's 'max lag' param is preferable
319 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
321 if ( $i === false && count( $currentLoads ) != 0 ) {
322 # All replica DBs lagged. Switch to read-only mode
323 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
324 $i = ArrayUtils
::pickRandom( $currentLoads );
325 $laggedReplicaMode = true;
329 if ( $i === false ) {
330 # pickRandom() returned false
331 # This is permanent and means the configuration or the load monitor
332 # wants us to return false.
333 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
338 $serverName = $this->getServerName( $i );
339 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
341 $conn = $this->openConnection( $i, $wiki );
343 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$wiki" );
344 unset( $nonErrorLoads[$i] );
345 unset( $currentLoads[$i] );
350 // Decrement reference counter, we are finished with this connection.
351 // It will be incremented for the caller later.
352 if ( $wiki !== false ) {
353 $this->reuseConnection( $conn );
360 # If all servers were down, quit now
361 if ( !count( $nonErrorLoads ) ) {
362 $this->connLogger
->error( "All servers down" );
365 if ( $i !== false ) {
366 # Replica DB connection successful.
367 # Wait for the session master pos for a short time.
368 if ( $this->mWaitForPos
&& $i > 0 ) {
371 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
372 $this->mReadIndex
= $i;
373 # Record if the generic reader index is in "lagged replica DB" mode
374 if ( $laggedReplicaMode ) {
375 $this->laggedReplicaMode
= true;
378 $serverName = $this->getServerName( $i );
379 $this->connLogger
->debug(
380 __METHOD__
. ": using server $serverName for group '$group'\n" );
387 * Set the master wait position
388 * If a DB_REPLICA connection has been opened already, waits
389 * Otherwise sets a variable telling it to wait if such a connection is opened
390 * @param DBMasterPos $pos
392 public function waitFor( $pos ) {
393 $this->mWaitForPos
= $pos;
394 $i = $this->mReadIndex
;
397 if ( !$this->doWait( $i ) ) {
398 $this->laggedReplicaMode
= true;
404 * Set the master wait position and wait for a "generic" replica DB to catch up to it
406 * This can be used a faster proxy for waitForAll()
408 * @param DBMasterPos $pos
409 * @param int $timeout Max seconds to wait; default is mWaitTimeout
410 * @return bool Success (able to connect and no timeouts reached)
413 public function waitForOne( $pos, $timeout = null ) {
414 $this->mWaitForPos
= $pos;
416 $i = $this->mReadIndex
;
418 // Pick a generic replica DB if there isn't one yet
419 $readLoads = $this->mLoads
;
420 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
421 $readLoads = array_filter( $readLoads ); // with non-zero load
422 $i = ArrayUtils
::pickRandom( $readLoads );
426 $ok = $this->doWait( $i, true, $timeout );
428 $ok = true; // no applicable loads
435 * Set the master wait position and wait for ALL replica DBs to catch up to it
436 * @param DBMasterPos $pos
437 * @param int $timeout Max seconds to wait; default is mWaitTimeout
438 * @return bool Success (able to connect and no timeouts reached)
440 public function waitForAll( $pos, $timeout = null ) {
441 $this->mWaitForPos
= $pos;
442 $serverCount = count( $this->mServers
);
445 for ( $i = 1; $i < $serverCount; $i++
) {
446 if ( $this->mLoads
[$i] > 0 ) {
447 $ok = $this->doWait( $i, true, $timeout ) && $ok;
455 * Get any open connection to a given server index, local or foreign
456 * Returns false if there is no connection open
458 * @param int $i Server index
459 * @return DatabaseBase|bool False on failure
461 public function getAnyOpenConnection( $i ) {
462 foreach ( $this->mConns
as $connsByServer ) {
463 if ( !empty( $connsByServer[$i] ) ) {
464 return reset( $connsByServer[$i] );
472 * Wait for a given replica DB to catch up to the master pos stored in $this
473 * @param int $index Server index
474 * @param bool $open Check the server even if a new connection has to be made
475 * @param int $timeout Max seconds to wait; default is mWaitTimeout
478 protected function doWait( $index, $open = false, $timeout = null ) {
479 $close = false; // close the connection afterwards
481 // Check if we already know that the DB has reached this point
482 $server = $this->getServerName( $index );
483 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server );
484 /** @var DBMasterPos $knownReachedPos */
485 $knownReachedPos = $this->srvCache
->get( $key );
486 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos
) ) {
487 $this->replLogger
->debug( __METHOD__
.
488 ": replica DB $server known to be caught up (pos >= $knownReachedPos).\n" );
492 // Find a connection to wait on, creating one if needed and allowed
493 $conn = $this->getAnyOpenConnection( $index );
496 $this->replLogger
->debug( __METHOD__
. ": no connection open for $server\n" );
500 $conn = $this->openConnection( $index, '' );
502 $this->replLogger
->warning( __METHOD__
. ": failed to connect to $server\n" );
506 // Avoid connection spam in waitForAll() when connections
507 // are made just for the sake of doing this lag check.
512 $this->replLogger
->info( __METHOD__
. ": Waiting for replica DB $server to catch up...\n" );
513 $timeout = $timeout ?
: $this->mWaitTimeout
;
514 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
516 if ( $result == -1 ||
is_null( $result ) ) {
517 // Timed out waiting for replica DB, use master instead
518 $msg = __METHOD__
. ": Timed out waiting on $server pos {$this->mWaitForPos}";
519 $this->replLogger
->warning( "$msg\n" );
520 $this->perfLogger
->warning( "$msg:\n" . wfBacktrace( true ) );
523 $this->replLogger
->info( __METHOD__
. ": Done\n" );
525 // Remember that the DB reached this point
526 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
530 $this->closeConnection( $conn );
537 * Get a connection by index
538 * This is the main entry point for this class.
540 * @param int $i Server index
541 * @param array|string|bool $groups Query group(s), or false for the generic reader
542 * @param string|bool $wiki Wiki ID, or false for the current wiki
544 * @throws MWException
545 * @return DatabaseBase
547 public function getConnection( $i, $groups = [], $wiki = false ) {
548 if ( $i === null ||
$i === false ) {
549 throw new MWException( 'Attempt to call ' . __METHOD__
.
550 ' with invalid server index' );
553 if ( $wiki === $this->localDomain
) {
557 $groups = ( $groups === false ||
$groups === [] )
558 ?
[ false ] // check one "group": the generic pool
561 $masterOnly = ( $i == DB_MASTER ||
$i == $this->getWriterIndex() );
562 $oldConnsOpened = $this->connsOpened
; // connections open now
564 if ( $i == DB_MASTER
) {
565 $i = $this->getWriterIndex();
567 # Try to find an available server in any the query groups (in order)
568 foreach ( $groups as $group ) {
569 $groupIndex = $this->getReaderIndex( $group, $wiki );
570 if ( $groupIndex !== false ) {
577 # Operation-based index
578 if ( $i == DB_REPLICA
) {
579 $this->mLastError
= 'Unknown error'; // reset error string
580 # Try the general server pool if $groups are unavailable.
581 $i = in_array( false, $groups, true )
582 ?
false // don't bother with this if that is what was tried above
583 : $this->getReaderIndex( false, $wiki );
584 # Couldn't find a working server in getReaderIndex()?
585 if ( $i === false ) {
586 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
588 return $this->reportConnectionError();
592 # Now we have an explicit index into the servers array
593 $conn = $this->openConnection( $i, $wiki );
595 return $this->reportConnectionError();
598 # Profile any new connections that happen
599 if ( $this->connsOpened
> $oldConnsOpened ) {
600 $host = $conn->getServer();
601 $dbname = $conn->getDBname();
602 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
606 # Make master-requested DB handles inherit any read-only mode setting
607 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $wiki, $conn ) );
614 * Mark a foreign connection as being available for reuse under a different
615 * DB name or prefix. This mechanism is reference-counted, and must be called
616 * the same number of times as getConnection() to work.
618 * @param DatabaseBase $conn
619 * @throws MWException
621 public function reuseConnection( $conn ) {
622 $serverIndex = $conn->getLBInfo( 'serverIndex' );
623 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
624 if ( $serverIndex === null ||
$refCount === null ) {
626 * This can happen in code like:
627 * foreach ( $dbs as $db ) {
628 * $conn = $lb->getConnection( DB_REPLICA, [], $db );
630 * $lb->reuseConnection( $conn );
632 * When a connection to the local DB is opened in this way, reuseConnection()
638 $dbName = $conn->getDBname();
639 $prefix = $conn->tablePrefix();
640 if ( strval( $prefix ) !== '' ) {
641 $wiki = "$dbName-$prefix";
645 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
646 throw new MWException( __METHOD__
. ": connection not found, has " .
647 "the connection been freed already?" );
649 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
650 if ( $refCount <= 0 ) {
651 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
652 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
653 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
655 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
660 * Get a database connection handle reference
662 * The handle's methods wrap simply wrap those of a DatabaseBase handle
664 * @see LoadBalancer::getConnection() for parameter information
667 * @param array|string|bool $groups Query group(s), or false for the generic reader
668 * @param string|bool $wiki Wiki ID, or false for the current wiki
671 public function getConnectionRef( $db, $groups = [], $wiki = false ) {
672 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
676 * Get a database connection handle reference without connecting yet
678 * The handle's methods wrap simply wrap those of a DatabaseBase handle
680 * @see LoadBalancer::getConnection() for parameter information
683 * @param array|string|bool $groups Query group(s), or false for the generic reader
684 * @param string|bool $wiki Wiki ID, or false for the current wiki
687 public function getLazyConnectionRef( $db, $groups = [], $wiki = false ) {
688 $wiki = ( $wiki !== false ) ?
$wiki : $this->localDomain
;
690 return new DBConnRef( $this, [ $db, $groups, $wiki ] );
694 * Open a connection to the server given by the specified index
695 * Index must be an actual index into the array.
696 * If the server is already open, returns it.
698 * On error, returns false, and the connection which caused the
699 * error will be available via $this->mErrorConnection.
701 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
703 * @param int $i Server index
704 * @param string|bool $wiki Wiki ID, or false for the current wiki
705 * @return DatabaseBase|bool Returns false on errors
707 public function openConnection( $i, $wiki = false ) {
708 if ( $wiki !== false ) {
709 $conn = $this->openForeignConnection( $i, $wiki );
710 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
711 $conn = $this->mConns
['local'][$i][0];
713 $server = $this->mServers
[$i];
714 $server['serverIndex'] = $i;
715 $conn = $this->reallyOpenConnection( $server, false );
716 $serverName = $this->getServerName( $i );
717 if ( $conn->isOpen() ) {
718 $this->connLogger
->debug( "Connected to database $i at '$serverName'." );
719 $this->mConns
['local'][$i][0] = $conn;
721 $this->connLogger
->warning( "Failed to connect to database $i at '$serverName'." );
722 $this->mErrorConnection
= $conn;
727 if ( $conn && !$conn->isOpen() ) {
728 // Connection was made but later unrecoverably lost for some reason.
729 // Do not return a handle that will just throw exceptions on use,
730 // but let the calling code (e.g. getReaderIndex) try another server.
731 // See DatabaseMyslBase::ping() for how this can happen.
732 $this->mErrorConnection
= $conn;
740 * Open a connection to a foreign DB, or return one if it is already open.
742 * Increments a reference count on the returned connection which locks the
743 * connection to the requested wiki. This reference count can be
744 * decremented by calling reuseConnection().
746 * If a connection is open to the appropriate server already, but with the wrong
747 * database, it will be switched to the right database and returned, as long as
748 * it has been freed first with reuseConnection().
750 * On error, returns false, and the connection which caused the
751 * error will be available via $this->mErrorConnection.
753 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
755 * @param int $i Server index
756 * @param string $wiki Wiki ID to open
757 * @return DatabaseBase
759 private function openForeignConnection( $i, $wiki ) {
760 list( $dbName, $prefix ) = explode( '-', $wiki, 2 ) +
[ '', '' ];
762 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
763 // Reuse an already-used connection
764 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
765 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
766 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
767 // Reuse a free connection for the same wiki
768 $conn = $this->mConns
['foreignFree'][$i][$wiki];
769 unset( $this->mConns
['foreignFree'][$i][$wiki] );
770 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
771 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
772 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
773 // Reuse a connection from another wiki
774 $conn = reset( $this->mConns
['foreignFree'][$i] );
775 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
777 // The empty string as a DB name means "don't care".
778 // DatabaseMysqlBase::open() already handle this on connection.
779 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
780 $this->mLastError
= "Error selecting database $dbName on server " .
781 $conn->getServer() . " from client host " . wfHostname() . "\n";
782 $this->mErrorConnection
= $conn;
785 $conn->tablePrefix( $prefix );
786 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
787 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
788 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
791 // Open a new connection
792 $server = $this->mServers
[$i];
793 $server['serverIndex'] = $i;
794 $server['foreignPoolRefCount'] = 0;
795 $server['foreign'] = true;
796 $conn = $this->reallyOpenConnection( $server, $dbName );
797 if ( !$conn->isOpen() ) {
798 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
799 $this->mErrorConnection
= $conn;
802 $conn->tablePrefix( $prefix );
803 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
804 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
808 // Increment reference count
810 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
811 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
818 * Test if the specified index represents an open connection
820 * @param int $index Server index
824 private function isOpen( $index ) {
825 if ( !is_integer( $index ) ) {
829 return (bool)$this->getAnyOpenConnection( $index );
833 * Really opens a connection. Uncached.
834 * Returns a Database object whether or not the connection was successful.
837 * @param array $server
838 * @param bool $dbNameOverride
839 * @throws MWException
840 * @return DatabaseBase
842 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
843 if ( $this->disabled
) {
844 throw new DBAccessError();
847 if ( !is_array( $server ) ) {
848 throw new MWException( 'You must update your load-balancing configuration. ' .
849 'See DefaultSettings.php entry for $wgDBservers.' );
852 if ( $dbNameOverride !== false ) {
853 $server['dbname'] = $dbNameOverride;
856 // Let the handle know what the cluster master is (e.g. "db1052")
857 $masterName = $this->getServerName( $this->getWriterIndex() );
858 $server['clusterMasterHost'] = $masterName;
860 // Log when many connection are made on requests
861 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
862 $this->perfLogger
->warning( __METHOD__
. ": " .
863 "{$this->connsOpened}+ connections made (master=$masterName)\n" .
864 wfBacktrace( true ) );
868 $server['connLogger'] = $this->connLogger
;
869 $server['queryLogger'] = $this->queryLogger
;
871 // Create a live connection object
873 $db = DatabaseBase
::factory( $server['type'], $server );
874 } catch ( DBConnectionError
$e ) {
875 // FIXME: This is probably the ugliest thing I have ever done to
876 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
880 $db->setLBInfo( $server );
881 $db->setLazyMasterHandle(
882 $this->getLazyConnectionRef( DB_MASTER
, [], $db->getWikiID() )
884 $db->setTransactionProfiler( $this->trxProfiler
);
886 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
887 if ( $this->trxRoundId
!== false ) {
888 $this->applyTransactionRoundFlags( $db );
890 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
891 $db->setTransactionListener( $name, $callback );
899 * @throws DBConnectionError
902 private function reportConnectionError() {
903 $conn = $this->mErrorConnection
; // The connection which caused the error
905 'method' => __METHOD__
,
906 'last_error' => $this->mLastError
,
909 if ( !is_object( $conn ) ) {
910 // No last connection, probably due to all servers being too busy
912 "LB failure with no last connection. Connection error: {last_error}",
916 // If all servers were busy, mLastError will contain something sensible
917 throw new DBConnectionError( null, $this->mLastError
);
919 $context['db_server'] = $conn->getProperty( 'mServer' );
921 "Connection error: {last_error} ({db_server})",
925 // throws DBConnectionError
926 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
929 return false; /* not reached */
936 public function getWriterIndex() {
941 * Returns true if the specified index is a valid server index
946 public function haveIndex( $i ) {
947 return array_key_exists( $i, $this->mServers
);
951 * Returns true if the specified index is valid and has non-zero load
956 public function isNonZeroLoad( $i ) {
957 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
961 * Get the number of defined servers (not the number of open connections)
965 public function getServerCount() {
966 return count( $this->mServers
);
970 * Get the host name or IP address of the server with the specified index
971 * Prefer a readable name if available.
975 public function getServerName( $i ) {
976 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
977 $name = $this->mServers
[$i]['hostName'];
978 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
979 $name = $this->mServers
[$i]['host'];
984 return ( $name != '' ) ?
$name : 'localhost';
988 * Return the server info structure for a given index, or false if the index is invalid.
992 public function getServerInfo( $i ) {
993 if ( isset( $this->mServers
[$i] ) ) {
994 return $this->mServers
[$i];
1001 * Sets the server info structure for the given index. Entry at index $i
1002 * is created if it doesn't exist
1004 * @param array $serverInfo
1006 public function setServerInfo( $i, array $serverInfo ) {
1007 $this->mServers
[$i] = $serverInfo;
1011 * Get the current master position for chronology control purposes
1012 * @return DBMasterPos|bool Returns false if not applicable
1014 public function getMasterPos() {
1015 # If this entire request was served from a replica DB without opening a connection to the
1016 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1017 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1018 if ( !$masterConn ) {
1019 $serverCount = count( $this->mServers
);
1020 for ( $i = 1; $i < $serverCount; $i++
) {
1021 $conn = $this->getAnyOpenConnection( $i );
1023 return $conn->getSlavePos();
1027 return $masterConn->getMasterPos();
1034 * Disable this load balancer. All connections are closed, and any attempt to
1035 * open a new connection will result in a DBAccessError.
1039 public function disable() {
1041 $this->disabled
= true;
1045 * Close all open connections
1047 public function closeAll() {
1048 $this->forEachOpenConnection( function ( DatabaseBase
$conn ) {
1054 'foreignFree' => [],
1055 'foreignUsed' => [],
1057 $this->connsOpened
= 0;
1061 * Close a connection
1063 * Using this function makes sure the LoadBalancer knows the connection is closed.
1064 * If you use $conn->close() directly, the load balancer won't update its state.
1066 * @param DatabaseBase $conn
1068 public function closeConnection( DatabaseBase
$conn ) {
1069 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1070 foreach ( $this->mConns
as $type => $connsByServer ) {
1071 if ( !isset( $connsByServer[$serverIndex] ) ) {
1075 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1076 if ( $conn === $trackedConn ) {
1077 unset( $this->mConns
[$type][$serverIndex][$i] );
1078 --$this->connsOpened
;
1088 * Commit transactions on all open connections
1089 * @param string $fname Caller name
1090 * @throws DBExpectedError
1092 public function commitAll( $fname = __METHOD__
) {
1095 $restore = ( $this->trxRoundId
!== false );
1096 $this->trxRoundId
= false;
1097 $this->forEachOpenConnection(
1098 function ( DatabaseBase
$conn ) use ( $fname, $restore, &$failures ) {
1100 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1101 } catch ( DBError
$e ) {
1102 call_user_func( $this->errorLogger
, $e );
1103 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1105 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1106 $this->undoTransactionRoundFlags( $conn );
1112 throw new DBExpectedError(
1114 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1120 * Perform all pre-commit callbacks that remain part of the atomic transactions
1121 * and disable any post-commit callbacks until runMasterPostTrxCallbacks()
1124 public function finalizeMasterChanges() {
1125 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) {
1126 // Any error should cause all DB transactions to be rolled back together
1127 $conn->setTrxEndCallbackSuppression( false );
1128 $conn->runOnTransactionPreCommitCallbacks();
1129 // Defer post-commit callbacks until COMMIT finishes for all DBs
1130 $conn->setTrxEndCallbackSuppression( true );
1135 * Perform all pre-commit checks for things like replication safety
1136 * @param array $options Includes:
1137 * - maxWriteDuration : max write query duration time in seconds
1138 * @throws DBTransactionError
1141 public function approveMasterChanges( array $options ) {
1142 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1143 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) use ( $limit ) {
1144 // If atomic sections or explicit transactions are still open, some caller must have
1145 // caught an exception but failed to properly rollback any changes. Detect that and
1146 // throw and error (causing rollback).
1147 if ( $conn->explicitTrxActive() ) {
1148 throw new DBTransactionError(
1150 "Explicit transaction still active. A caller may have caught an error."
1153 // Assert that the time to replicate the transaction will be sane.
1154 // If this fails, then all DB transactions will be rollback back together.
1155 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1156 if ( $limit > 0 && $time > $limit ) {
1157 throw new DBTransactionError(
1159 wfMessage( 'transaction-duration-limit-exceeded', $time, $limit )->text()
1162 // If a connection sits idle while slow queries execute on another, that connection
1163 // may end up dropped before the commit round is reached. Ping servers to detect this.
1164 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1165 throw new DBTransactionError(
1167 "A connection to the {$conn->getDBname()} database was lost before commit."
1174 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
1176 * The DBO_TRX setting will be reverted to the default in each of these methods:
1177 * - commitMasterChanges()
1178 * - rollbackMasterChanges()
1180 * This allows for custom transaction rounds from any outer transaction scope.
1182 * @param string $fname
1183 * @throws DBExpectedError
1186 public function beginMasterChanges( $fname = __METHOD__
) {
1187 if ( $this->trxRoundId
!== false ) {
1188 throw new DBTransactionError(
1190 "$fname: Transaction round '{$this->trxRoundId}' already started."
1193 $this->trxRoundId
= $fname;
1196 $this->forEachOpenMasterConnection(
1197 function ( DatabaseBase
$conn ) use ( $fname, &$failures ) {
1198 $conn->setTrxEndCallbackSuppression( true );
1200 $conn->flushSnapshot( $fname );
1201 } catch ( DBError
$e ) {
1202 call_user_func( $this->errorLogger
, $e );
1203 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1205 $conn->setTrxEndCallbackSuppression( false );
1206 $this->applyTransactionRoundFlags( $conn );
1211 throw new DBExpectedError(
1213 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1219 * Issue COMMIT on all master connections where writes where done
1220 * @param string $fname Caller name
1221 * @throws DBExpectedError
1223 public function commitMasterChanges( $fname = __METHOD__
) {
1226 $restore = ( $this->trxRoundId
!== false );
1227 $this->trxRoundId
= false;
1228 $this->forEachOpenMasterConnection(
1229 function ( DatabaseBase
$conn ) use ( $fname, $restore, &$failures ) {
1231 if ( $conn->writesOrCallbacksPending() ) {
1232 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1233 } elseif ( $restore ) {
1234 $conn->flushSnapshot( $fname );
1236 } catch ( DBError
$e ) {
1237 call_user_func( $this->errorLogger
, $e );
1238 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1241 $this->undoTransactionRoundFlags( $conn );
1247 throw new DBExpectedError(
1249 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1255 * Issue all pending post-COMMIT/ROLLBACK callbacks
1256 * @param integer $type IDatabase::TRIGGER_* constant
1257 * @return Exception|null The first exception or null if there were none
1260 public function runMasterPostTrxCallbacks( $type ) {
1261 $e = null; // first exception
1262 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) use ( $type, &$e ) {
1263 $conn->setTrxEndCallbackSuppression( false );
1264 if ( $conn->writesOrCallbacksPending() ) {
1265 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1266 // (which finished its callbacks already). Warn and recover in this case. Let the
1267 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1268 wfWarn( __METHOD__
. ": did not expect writes/callbacks pending." );
1270 } elseif ( $conn->trxLevel() ) {
1271 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1272 // thus leaving an implicit read-only transaction open at this point. It
1273 // also happens if onTransactionIdle() callbacks leave implicit transactions
1274 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1275 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1279 $conn->runOnTransactionIdleCallbacks( $type );
1280 } catch ( Exception
$ex ) {
1284 $conn->runTransactionListenerCallbacks( $type );
1285 } catch ( Exception
$ex ) {
1294 * Issue ROLLBACK only on master, only if queries were done on connection
1295 * @param string $fname Caller name
1296 * @throws DBExpectedError
1299 public function rollbackMasterChanges( $fname = __METHOD__
) {
1300 $restore = ( $this->trxRoundId
!== false );
1301 $this->trxRoundId
= false;
1302 $this->forEachOpenMasterConnection(
1303 function ( DatabaseBase
$conn ) use ( $fname, $restore ) {
1304 if ( $conn->writesOrCallbacksPending() ) {
1305 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1308 $this->undoTransactionRoundFlags( $conn );
1315 * Suppress all pending post-COMMIT/ROLLBACK callbacks
1316 * @return Exception|null The first exception or null if there were none
1319 public function suppressTransactionEndCallbacks() {
1320 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) {
1321 $conn->setTrxEndCallbackSuppression( true );
1326 * @param DatabaseBase $conn
1328 private function applyTransactionRoundFlags( DatabaseBase
$conn ) {
1329 if ( $conn->getFlag( DBO_DEFAULT
) ) {
1330 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1331 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1332 $conn->setFlag( DBO_TRX
, $conn::REMEMBER_PRIOR
);
1333 // If config has explicitly requested DBO_TRX be either on or off by not
1334 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1335 // for things like blob stores (ExternalStore) which want auto-commit mode.
1340 * @param DatabaseBase $conn
1342 private function undoTransactionRoundFlags( DatabaseBase
$conn ) {
1343 if ( $conn->getFlag( DBO_DEFAULT
) ) {
1344 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1349 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
1351 * @param string $fname Caller name
1354 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1355 $this->forEachOpenReplicaConnection( function ( DatabaseBase
$conn ) {
1356 $conn->flushSnapshot( __METHOD__
);
1361 * @return bool Whether a master connection is already open
1364 public function hasMasterConnection() {
1365 return $this->isOpen( $this->getWriterIndex() );
1369 * Determine if there are pending changes in a transaction by this thread
1373 public function hasMasterChanges() {
1375 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) use ( &$pending ) {
1376 $pending |
= $conn->writesOrCallbacksPending();
1379 return (bool)$pending;
1383 * Get the timestamp of the latest write query done by this thread
1385 * @return float|bool UNIX timestamp or false
1387 public function lastMasterChangeTimestamp() {
1389 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) use ( &$lastTime ) {
1390 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1397 * Check if this load balancer object had any recent or still
1398 * pending writes issued against it by this PHP thread
1400 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
1404 public function hasOrMadeRecentMasterChanges( $age = null ) {
1405 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1407 return ( $this->hasMasterChanges()
1408 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1412 * Get the list of callers that have pending master changes
1414 * @return string[] List of method names
1417 public function pendingMasterChangeCallers() {
1419 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) use ( &$fnames ) {
1420 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1427 * @note This method will trigger a DB connection if not yet done
1428 * @param string|bool $wiki Wiki ID, or false for the current wiki
1429 * @return bool Whether the generic connection for reads is highly "lagged"
1431 public function getLaggedReplicaMode( $wiki = false ) {
1432 // No-op if there is only one DB (also avoids recursion)
1433 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1435 // See if laggedReplicaMode gets set
1436 $conn = $this->getConnection( DB_REPLICA
, false, $wiki );
1437 $this->reuseConnection( $conn );
1438 } catch ( DBConnectionError
$e ) {
1439 // Avoid expensive re-connect attempts and failures
1440 $this->allReplicasDownMode
= true;
1441 $this->laggedReplicaMode
= true;
1445 return $this->laggedReplicaMode
;
1451 * @deprecated 1.28; use getLaggedReplicaMode()
1453 public function getLaggedSlaveMode( $wiki = false ) {
1454 return $this->getLaggedReplicaMode( $wiki );
1458 * @note This method will never cause a new DB connection
1459 * @return bool Whether any generic connection used for reads was highly "lagged"
1462 public function laggedReplicaUsed() {
1463 return $this->laggedReplicaMode
;
1469 * @deprecated Since 1.28; use laggedReplicaUsed()
1471 public function laggedSlaveUsed() {
1472 return $this->laggedReplicaUsed();
1476 * @note This method may trigger a DB connection if not yet done
1477 * @param string|bool $wiki Wiki ID, or false for the current wiki
1478 * @param DatabaseBase|null DB master connection; used to avoid loops [optional]
1479 * @return string|bool Reason the master is read-only or false if it is not
1482 public function getReadOnlyReason( $wiki = false, DatabaseBase
$conn = null ) {
1483 if ( $this->readOnlyReason
!== false ) {
1484 return $this->readOnlyReason
;
1485 } elseif ( $this->getLaggedReplicaMode( $wiki ) ) {
1486 if ( $this->allReplicasDownMode
) {
1487 return 'The database has been automatically locked ' .
1488 'until the replica database servers become available';
1490 return 'The database has been automatically locked ' .
1491 'while the replica database servers catch up to the master.';
1493 } elseif ( $this->masterRunningReadOnly( $wiki, $conn ) ) {
1494 return 'The database master is running in read-only mode.';
1501 * @param string $wiki Wiki ID, or false for the current wiki
1502 * @param DatabaseBase|null DB master connectionl used to avoid loops [optional]
1505 private function masterRunningReadOnly( $wiki, DatabaseBase
$conn = null ) {
1506 $cache = $this->wanCache
;
1507 $masterServer = $this->getServerName( $this->getWriterIndex() );
1509 return (bool)$cache->getWithSetCallback(
1510 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1511 self
::TTL_CACHE_READONLY
,
1512 function () use ( $wiki, $conn ) {
1513 $this->trxProfiler
->setSilenced( true );
1515 $dbw = $conn ?
: $this->getConnection( DB_MASTER
, [], $wiki );
1516 $readOnly = (int)$dbw->serverIsReadOnly();
1517 } catch ( DBError
$e ) {
1520 $this->trxProfiler
->setSilenced( false );
1523 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1528 * Disables/enables lag checks
1529 * @param null|bool $mode
1532 public function allowLagged( $mode = null ) {
1533 if ( $mode === null ) {
1534 return $this->mAllowLagged
;
1536 $this->mAllowLagged
= $mode;
1538 return $this->mAllowLagged
;
1544 public function pingAll() {
1546 $this->forEachOpenConnection( function ( DatabaseBase
$conn ) use ( &$success ) {
1547 if ( !$conn->ping() ) {
1556 * Call a function with each open connection object
1557 * @param callable $callback
1558 * @param array $params
1560 public function forEachOpenConnection( $callback, array $params = [] ) {
1561 foreach ( $this->mConns
as $connsByServer ) {
1562 foreach ( $connsByServer as $serverConns ) {
1563 foreach ( $serverConns as $conn ) {
1564 $mergedParams = array_merge( [ $conn ], $params );
1565 call_user_func_array( $callback, $mergedParams );
1572 * Call a function with each open connection object to a master
1573 * @param callable $callback
1574 * @param array $params
1577 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1578 $masterIndex = $this->getWriterIndex();
1579 foreach ( $this->mConns
as $connsByServer ) {
1580 if ( isset( $connsByServer[$masterIndex] ) ) {
1581 /** @var DatabaseBase $conn */
1582 foreach ( $connsByServer[$masterIndex] as $conn ) {
1583 $mergedParams = array_merge( [ $conn ], $params );
1584 call_user_func_array( $callback, $mergedParams );
1591 * Call a function with each open replica DB connection object
1592 * @param callable $callback
1593 * @param array $params
1596 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1597 foreach ( $this->mConns
as $connsByServer ) {
1598 foreach ( $connsByServer as $i => $serverConns ) {
1599 if ( $i === $this->getWriterIndex() ) {
1600 continue; // skip master
1602 foreach ( $serverConns as $conn ) {
1603 $mergedParams = array_merge( [ $conn ], $params );
1604 call_user_func_array( $callback, $mergedParams );
1611 * Get the hostname and lag time of the most-lagged replica DB
1613 * This is useful for maintenance scripts that need to throttle their updates.
1614 * May attempt to open connections to replica DBs on the default DB. If there is
1615 * no lag, the maximum lag will be reported as -1.
1617 * @param bool|string $wiki Wiki ID, or false for the default database
1618 * @return array ( host, max lag, index of max lagged host )
1620 public function getMaxLag( $wiki = false ) {
1625 if ( $this->getServerCount() <= 1 ) {
1626 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1629 $lagTimes = $this->getLagTimes( $wiki );
1630 foreach ( $lagTimes as $i => $lag ) {
1631 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1633 $host = $this->mServers
[$i]['host'];
1638 return [ $host, $maxLag, $maxIndex ];
1642 * Get an estimate of replication lag (in seconds) for each server
1644 * Results are cached for a short time in memcached/process cache
1646 * Values may be "false" if replication is too broken to estimate
1648 * @param string|bool $wiki
1649 * @return int[] Map of (server index => float|int|bool)
1651 public function getLagTimes( $wiki = false ) {
1652 if ( $this->getServerCount() <= 1 ) {
1653 return [ 0 => 0 ]; // no replication = no lag
1656 # Send the request to the load monitor
1657 return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
1661 * Get the lag in seconds for a given connection, or zero if this load
1662 * balancer does not have replication enabled.
1664 * This should be used in preference to Database::getLag() in cases where
1665 * replication may not be in use, since there is no way to determine if
1666 * replication is in use at the connection level without running
1667 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1668 * function instead of Database::getLag() avoids a fatal error in this
1669 * case on many installations.
1671 * @param IDatabase $conn
1672 * @return int|bool Returns false on error
1674 public function safeGetLag( IDatabase
$conn ) {
1675 if ( $this->getServerCount() == 1 ) {
1678 return $conn->getLag();
1683 * Wait for a replica DB to reach a specified master position
1685 * This will connect to the master to get an accurate position if $pos is not given
1687 * @param IDatabase $conn Replica DB
1688 * @param DBMasterPos|bool $pos Master position; default: current position
1689 * @param integer $timeout Timeout in seconds
1690 * @return bool Success
1693 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1694 if ( $this->getServerCount() == 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1695 return true; // server is not a replica DB
1698 $pos = $pos ?
: $this->getConnection( DB_MASTER
)->getMasterPos();
1699 if ( !( $pos instanceof DBMasterPos
) ) {
1700 return false; // something is misconfigured
1703 $result = $conn->masterPosWait( $pos, $timeout );
1704 if ( $result == -1 ||
is_null( $result ) ) {
1705 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1706 $this->replLogger
->warning( "$msg\n" );
1707 $this->perfLogger
->warning( "$msg:\n" . wfBacktrace( true ) );
1710 $this->replLogger
->info( __METHOD__
. ": Done\n" );
1718 * Clear the cache for slag lag delay times
1720 * This is only used for testing
1722 public function clearLagTimeCache() {
1723 $this->getLoadMonitor()->clearCaches();
1727 * Set a callback via DatabaseBase::setTransactionListener() on
1728 * all current and future master connections of this load balancer
1730 * @param string $name Callback name
1731 * @param callable|null $callback
1734 public function setTransactionListener( $name, callable
$callback = null ) {
1736 $this->trxRecurringCallbacks
[$name] = $callback;
1738 unset( $this->trxRecurringCallbacks
[$name] );
1740 $this->forEachOpenMasterConnection(
1741 function ( DatabaseBase
$conn ) use ( $name, $callback ) {
1742 $conn->setTransactionListener( $name, $callback );
1748 * Set a new table prefix for the existing local wiki ID for testing
1750 * @param string $prefix
1753 public function setDomainPrefix( $prefix ) {
1754 list( $dbName, ) = explode( '-', $this->localDomain
, 2 );
1756 $this->localDomain
= "{$dbName}-{$prefix}";