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 = [];
77 /** @var string Local Wiki ID and default for selectDB() calls */
79 /** @var callable Exception logger */
82 /** @var integer Warn when this many connection are held */
83 const CONN_HELD_WARN_THRESHOLD
= 10;
84 /** @var integer Default 'max lag' when unspecified */
85 const MAX_LAG_DEFAULT
= 10;
86 /** @var integer Max time to wait for a replica DB to catch up (e.g. ChronologyProtector) */
87 const POS_WAIT_TIMEOUT
= 10;
88 /** @var integer Seconds to cache master server read-only status */
89 const TTL_CACHE_READONLY
= 5;
94 private $disabled = false;
97 * @param array $params Array with keys:
98 * - servers : Required. Array of server info structures.
99 * - loadMonitor : Name of a class used to fetch server lag and load.
100 * - readOnlyReason : Reason the master DB is read-only if so [optional]
101 * - waitTimeout : Maximum time to wait for replicas for consistency [optional]
102 * - srvCache : BagOStuff object [optional]
103 * - wanCache : WANObjectCache object [optional]
104 * - localDomain: The wiki ID of the "local"/"current" wiki [optional]
105 * - errorLogger: Callback that takes an Exception and logs it [optional]
106 * @throws MWException
108 public function __construct( array $params ) {
109 if ( !isset( $params['servers'] ) ) {
110 throw new MWException( __CLASS__
. ': missing servers parameter' );
112 $this->mServers
= $params['servers'];
113 $this->mWaitTimeout
= isset( $params['waitTimeout'] )
114 ?
$params['waitTimeout']
115 : self
::POS_WAIT_TIMEOUT
;
116 $this->localDomain
= isset( $params['localDomain'] ) ?
$params['localDomain'] : '';
118 $this->mReadIndex
= -1;
119 $this->mWriteIndex
= -1;
123 'foreignFree' => [] ];
125 $this->mWaitForPos
= false;
126 $this->mErrorConnection
= false;
127 $this->mAllowLagged
= false;
129 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
130 $this->readOnlyReason
= $params['readOnlyReason'];
133 if ( isset( $params['loadMonitor'] ) ) {
134 $this->mLoadMonitorClass
= $params['loadMonitor'];
136 $master = reset( $params['servers'] );
137 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
138 $this->mLoadMonitorClass
= 'LoadMonitorMySQL';
140 $this->mLoadMonitorClass
= 'LoadMonitorNull';
144 foreach ( $params['servers'] as $i => $server ) {
145 $this->mLoads
[$i] = $server['load'];
146 if ( isset( $server['groupLoads'] ) ) {
147 foreach ( $server['groupLoads'] as $group => $ratio ) {
148 if ( !isset( $this->mGroupLoads
[$group] ) ) {
149 $this->mGroupLoads
[$group] = [];
151 $this->mGroupLoads
[$group][$i] = $ratio;
156 if ( isset( $params['srvCache'] ) ) {
157 $this->srvCache
= $params['srvCache'];
159 $this->srvCache
= new EmptyBagOStuff();
161 if ( isset( $params['wanCache'] ) ) {
162 $this->wanCache
= $params['wanCache'];
164 $this->wanCache
= WANObjectCache
::newEmpty();
166 if ( isset( $params['trxProfiler'] ) ) {
167 $this->trxProfiler
= $params['trxProfiler'];
169 $this->trxProfiler
= new TransactionProfiler();
172 $this->errorLogger
= isset( $params['errorLogger'] )
173 ?
$params['errorLogger']
174 : function ( Exception
$e ) {
175 trigger_error( E_WARNING
, $e->getMessage() );
180 * Get a LoadMonitor instance
182 * @return LoadMonitor
184 private function getLoadMonitor() {
185 if ( !isset( $this->mLoadMonitor
) ) {
186 $class = $this->mLoadMonitorClass
;
187 $this->mLoadMonitor
= new $class( $this );
190 return $this->mLoadMonitor
;
194 * @param array $loads
195 * @param bool|string $wiki Wiki to get non-lagged for
196 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
197 * @return bool|int|string
199 private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = INF
) {
200 $lags = $this->getLagTimes( $wiki );
202 # Unset excessively lagged servers
203 foreach ( $lags as $i => $lag ) {
205 # How much lag this server nominally is allowed to have
206 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
207 ?
$this->mServers
[$i]['max lag']
208 : self
::MAX_LAG_DEFAULT
; // default
209 # Constrain that futher by $maxLag argument
210 $maxServerLag = min( $maxServerLag, $maxLag );
212 $host = $this->getServerName( $i );
213 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
214 wfDebugLog( 'replication', "Server $host (#$i) is not replicating?" );
216 } elseif ( $lag > $maxServerLag ) {
217 wfDebugLog( 'replication', "Server $host (#$i) has >= $lag seconds of lag" );
223 # Find out if all the replica DBs with non-zero load are lagged
225 foreach ( $loads as $load ) {
229 # No appropriate DB servers except maybe the master and some replica DBs with zero load
230 # Do NOT use the master
231 # Instead, this function will return false, triggering read-only mode,
232 # and a lagged replica DB will be used instead.
236 if ( count( $loads ) == 0 ) {
240 # Return a random representative of the remainder
241 return ArrayUtils
::pickRandom( $loads );
245 * Get the index of the reader connection, which may be a replica DB
246 * This takes into account load ratios and lag times. It should
247 * always return a consistent index during a given invocation
249 * Side effect: opens connections to databases
250 * @param string|bool $group Query group, or false for the generic reader
251 * @param string|bool $wiki Wiki ID, or false for the current wiki
252 * @throws MWException
253 * @return bool|int|string
255 public function getReaderIndex( $group = false, $wiki = false ) {
256 if ( count( $this->mServers
) == 1 ) {
257 # Skip the load balancing if there's only one server
258 return $this->getWriterIndex();
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 supported
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
446 * @param int $i Server index
447 * @return DatabaseBase|bool False on failure
449 public function getAnyOpenConnection( $i ) {
450 foreach ( $this->mConns
as $connsByServer ) {
451 if ( !empty( $connsByServer[$i] ) ) {
452 return reset( $connsByServer[$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 === $this->localDomain
) {
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 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
594 # Make master-requested DB handles inherit any read-only mode setting
595 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $wiki, $conn ) );
602 * Mark a foreign connection as being available for reuse under a different
603 * DB name or prefix. This mechanism is reference-counted, and must be called
604 * the same number of times as getConnection() to work.
606 * @param DatabaseBase $conn
607 * @throws MWException
609 public function reuseConnection( $conn ) {
610 $serverIndex = $conn->getLBInfo( 'serverIndex' );
611 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
612 if ( $serverIndex === null ||
$refCount === null ) {
614 * This can happen in code like:
615 * foreach ( $dbs as $db ) {
616 * $conn = $lb->getConnection( DB_REPLICA, [], $db );
618 * $lb->reuseConnection( $conn );
620 * When a connection to the local DB is opened in this way, reuseConnection()
626 $dbName = $conn->getDBname();
627 $prefix = $conn->tablePrefix();
628 if ( strval( $prefix ) !== '' ) {
629 $wiki = "$dbName-$prefix";
633 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
634 throw new MWException( __METHOD__
. ": connection not found, has " .
635 "the connection been freed already?" );
637 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
638 if ( $refCount <= 0 ) {
639 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
640 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
641 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
643 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
648 * Get a database connection handle reference
650 * The handle's methods wrap simply wrap those of a DatabaseBase handle
652 * @see LoadBalancer::getConnection() for parameter information
655 * @param array|string|bool $groups Query group(s), or false for the generic reader
656 * @param string|bool $wiki Wiki ID, or false for the current wiki
659 public function getConnectionRef( $db, $groups = [], $wiki = false ) {
660 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
664 * Get a database connection handle reference without connecting yet
666 * The handle's methods wrap simply wrap those of a DatabaseBase handle
668 * @see LoadBalancer::getConnection() for parameter information
671 * @param array|string|bool $groups Query group(s), or false for the generic reader
672 * @param string|bool $wiki Wiki ID, or false for the current wiki
675 public function getLazyConnectionRef( $db, $groups = [], $wiki = false ) {
676 $wiki = ( $wiki !== false ) ?
$wiki : $this->localDomain
;
678 return new DBConnRef( $this, [ $db, $groups, $wiki ] );
682 * Open a connection to the server given by the specified index
683 * Index must be an actual index into the array.
684 * If the server is already open, returns it.
686 * On error, returns false, and the connection which caused the
687 * error will be available via $this->mErrorConnection.
689 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
691 * @param int $i Server index
692 * @param string|bool $wiki Wiki ID, or false for the current wiki
693 * @return DatabaseBase|bool Returns false on errors
695 public function openConnection( $i, $wiki = false ) {
696 if ( $wiki !== false ) {
697 $conn = $this->openForeignConnection( $i, $wiki );
698 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
699 $conn = $this->mConns
['local'][$i][0];
701 $server = $this->mServers
[$i];
702 $server['serverIndex'] = $i;
703 $conn = $this->reallyOpenConnection( $server, false );
704 $serverName = $this->getServerName( $i );
705 if ( $conn->isOpen() ) {
706 wfDebugLog( 'connect', "Connected to database $i at $serverName\n" );
707 $this->mConns
['local'][$i][0] = $conn;
709 wfDebugLog( 'connect', "Failed to connect to database $i at $serverName\n" );
710 $this->mErrorConnection
= $conn;
715 if ( $conn && !$conn->isOpen() ) {
716 // Connection was made but later unrecoverably lost for some reason.
717 // Do not return a handle that will just throw exceptions on use,
718 // but let the calling code (e.g. getReaderIndex) try another server.
719 // See DatabaseMyslBase::ping() for how this can happen.
720 $this->mErrorConnection
= $conn;
728 * Open a connection to a foreign DB, or return one if it is already open.
730 * Increments a reference count on the returned connection which locks the
731 * connection to the requested wiki. This reference count can be
732 * decremented by calling reuseConnection().
734 * If a connection is open to the appropriate server already, but with the wrong
735 * database, it will be switched to the right database and returned, as long as
736 * it has been freed first with reuseConnection().
738 * On error, returns false, and the connection which caused the
739 * error will be available via $this->mErrorConnection.
741 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
743 * @param int $i Server index
744 * @param string $wiki Wiki ID to open
745 * @return DatabaseBase
747 private function openForeignConnection( $i, $wiki ) {
748 list( $dbName, $prefix ) = explode( '-', $wiki, 2 ) +
[ '', '' ];
750 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
751 // Reuse an already-used connection
752 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
753 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
754 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
755 // Reuse a free connection for the same wiki
756 $conn = $this->mConns
['foreignFree'][$i][$wiki];
757 unset( $this->mConns
['foreignFree'][$i][$wiki] );
758 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
759 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
760 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
761 // Reuse a connection from another wiki
762 $conn = reset( $this->mConns
['foreignFree'][$i] );
763 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
765 // The empty string as a DB name means "don't care".
766 // DatabaseMysqlBase::open() already handle this on connection.
767 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
768 $this->mLastError
= "Error selecting database $dbName on server " .
769 $conn->getServer() . " from client host " . wfHostname() . "\n";
770 $this->mErrorConnection
= $conn;
773 $conn->tablePrefix( $prefix );
774 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
775 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
776 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
779 // Open a new connection
780 $server = $this->mServers
[$i];
781 $server['serverIndex'] = $i;
782 $server['foreignPoolRefCount'] = 0;
783 $server['foreign'] = true;
784 $conn = $this->reallyOpenConnection( $server, $dbName );
785 if ( !$conn->isOpen() ) {
786 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
787 $this->mErrorConnection
= $conn;
790 $conn->tablePrefix( $prefix );
791 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
792 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
796 // Increment reference count
798 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
799 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
806 * Test if the specified index represents an open connection
808 * @param int $index Server index
812 private function isOpen( $index ) {
813 if ( !is_integer( $index ) ) {
817 return (bool)$this->getAnyOpenConnection( $index );
821 * Really opens a connection. Uncached.
822 * Returns a Database object whether or not the connection was successful.
825 * @param array $server
826 * @param bool $dbNameOverride
827 * @throws MWException
828 * @return DatabaseBase
830 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
831 if ( $this->disabled
) {
832 throw new DBAccessError();
835 if ( !is_array( $server ) ) {
836 throw new MWException( 'You must update your load-balancing configuration. ' .
837 'See DefaultSettings.php entry for $wgDBservers.' );
840 if ( $dbNameOverride !== false ) {
841 $server['dbname'] = $dbNameOverride;
844 // Let the handle know what the cluster master is (e.g. "db1052")
845 $masterName = $this->getServerName( $this->getWriterIndex() );
846 $server['clusterMasterHost'] = $masterName;
848 // Log when many connection are made on requests
849 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
850 wfDebugLog( 'DBPerformance', __METHOD__
. ": " .
851 "{$this->connsOpened}+ connections made (master=$masterName)\n" .
852 wfBacktrace( true ) );
857 $db = DatabaseBase
::factory( $server['type'], $server );
858 } catch ( DBConnectionError
$e ) {
859 // FIXME: This is probably the ugliest thing I have ever done to
860 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
864 $db->setLBInfo( $server );
865 $db->setLazyMasterHandle(
866 $this->getLazyConnectionRef( DB_MASTER
, [], $db->getWikiID() )
868 $db->setTransactionProfiler( $this->trxProfiler
);
870 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
871 if ( $this->trxRoundId
!== false ) {
872 $this->applyTransactionRoundFlags( $db );
874 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
875 $db->setTransactionListener( $name, $callback );
883 * @throws DBConnectionError
886 private function reportConnectionError() {
887 $conn = $this->mErrorConnection
; // The connection which caused the error
889 'method' => __METHOD__
,
890 'last_error' => $this->mLastError
,
893 if ( !is_object( $conn ) ) {
894 // No last connection, probably due to all servers being too busy
896 "LB failure with no last connection. Connection error: {last_error}",
900 // If all servers were busy, mLastError will contain something sensible
901 throw new DBConnectionError( null, $this->mLastError
);
903 $context['db_server'] = $conn->getProperty( 'mServer' );
905 "Connection error: {last_error} ({db_server})",
909 // throws DBConnectionError
910 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
913 return false; /* not reached */
920 public function getWriterIndex() {
925 * Returns true if the specified index is a valid server index
930 public function haveIndex( $i ) {
931 return array_key_exists( $i, $this->mServers
);
935 * Returns true if the specified index is valid and has non-zero load
940 public function isNonZeroLoad( $i ) {
941 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
945 * Get the number of defined servers (not the number of open connections)
949 public function getServerCount() {
950 return count( $this->mServers
);
954 * Get the host name or IP address of the server with the specified index
955 * Prefer a readable name if available.
959 public function getServerName( $i ) {
960 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
961 $name = $this->mServers
[$i]['hostName'];
962 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
963 $name = $this->mServers
[$i]['host'];
968 return ( $name != '' ) ?
$name : 'localhost';
972 * Return the server info structure for a given index, or false if the index is invalid.
976 public function getServerInfo( $i ) {
977 if ( isset( $this->mServers
[$i] ) ) {
978 return $this->mServers
[$i];
985 * Sets the server info structure for the given index. Entry at index $i
986 * is created if it doesn't exist
988 * @param array $serverInfo
990 public function setServerInfo( $i, array $serverInfo ) {
991 $this->mServers
[$i] = $serverInfo;
995 * Get the current master position for chronology control purposes
996 * @return DBMasterPos|bool Returns false if not applicable
998 public function getMasterPos() {
999 # If this entire request was served from a replica DB without opening a connection to the
1000 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1001 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1002 if ( !$masterConn ) {
1003 $serverCount = count( $this->mServers
);
1004 for ( $i = 1; $i < $serverCount; $i++
) {
1005 $conn = $this->getAnyOpenConnection( $i );
1007 return $conn->getSlavePos();
1011 return $masterConn->getMasterPos();
1018 * Disable this load balancer. All connections are closed, and any attempt to
1019 * open a new connection will result in a DBAccessError.
1023 public function disable() {
1025 $this->disabled
= true;
1029 * Close all open connections
1031 public function closeAll() {
1032 $this->forEachOpenConnection( function ( DatabaseBase
$conn ) {
1038 'foreignFree' => [],
1039 'foreignUsed' => [],
1041 $this->connsOpened
= 0;
1045 * Close a connection
1047 * Using this function makes sure the LoadBalancer knows the connection is closed.
1048 * If you use $conn->close() directly, the load balancer won't update its state.
1050 * @param DatabaseBase $conn
1052 public function closeConnection( DatabaseBase
$conn ) {
1053 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1054 foreach ( $this->mConns
as $type => $connsByServer ) {
1055 if ( !isset( $connsByServer[$serverIndex] ) ) {
1059 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1060 if ( $conn === $trackedConn ) {
1061 unset( $this->mConns
[$type][$serverIndex][$i] );
1062 --$this->connsOpened
;
1072 * Commit transactions on all open connections
1073 * @param string $fname Caller name
1074 * @throws DBExpectedError
1076 public function commitAll( $fname = __METHOD__
) {
1079 $restore = ( $this->trxRoundId
!== false );
1080 $this->trxRoundId
= false;
1081 $this->forEachOpenConnection(
1082 function ( DatabaseBase
$conn ) use ( $fname, $restore, &$failures ) {
1084 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1085 } catch ( DBError
$e ) {
1086 call_user_func( $this->errorLogger
, $e );
1087 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1089 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1090 $this->undoTransactionRoundFlags( $conn );
1096 throw new DBExpectedError(
1098 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1104 * Perform all pre-commit callbacks that remain part of the atomic transactions
1105 * and disable any post-commit callbacks until runMasterPostTrxCallbacks()
1108 public function finalizeMasterChanges() {
1109 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) {
1110 // Any error should cause all DB transactions to be rolled back together
1111 $conn->setTrxEndCallbackSuppression( false );
1112 $conn->runOnTransactionPreCommitCallbacks();
1113 // Defer post-commit callbacks until COMMIT finishes for all DBs
1114 $conn->setTrxEndCallbackSuppression( true );
1119 * Perform all pre-commit checks for things like replication safety
1120 * @param array $options Includes:
1121 * - maxWriteDuration : max write query duration time in seconds
1122 * @throws DBTransactionError
1125 public function approveMasterChanges( array $options ) {
1126 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1127 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) use ( $limit ) {
1128 // If atomic sections or explicit transactions are still open, some caller must have
1129 // caught an exception but failed to properly rollback any changes. Detect that and
1130 // throw and error (causing rollback).
1131 if ( $conn->explicitTrxActive() ) {
1132 throw new DBTransactionError(
1134 "Explicit transaction still active. A caller may have caught an error."
1137 // Assert that the time to replicate the transaction will be sane.
1138 // If this fails, then all DB transactions will be rollback back together.
1139 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1140 if ( $limit > 0 && $time > $limit ) {
1141 throw new DBTransactionError(
1143 wfMessage( 'transaction-duration-limit-exceeded', $time, $limit )->text()
1146 // If a connection sits idle while slow queries execute on another, that connection
1147 // may end up dropped before the commit round is reached. Ping servers to detect this.
1148 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1149 throw new DBTransactionError(
1151 "A connection to the {$conn->getDBname()} database was lost before commit."
1158 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
1160 * The DBO_TRX setting will be reverted to the default in each of these methods:
1161 * - commitMasterChanges()
1162 * - rollbackMasterChanges()
1164 * This allows for custom transaction rounds from any outer transaction scope.
1166 * @param string $fname
1167 * @throws DBExpectedError
1170 public function beginMasterChanges( $fname = __METHOD__
) {
1171 if ( $this->trxRoundId
!== false ) {
1172 throw new DBTransactionError(
1174 "$fname: Transaction round '{$this->trxRoundId}' already started."
1177 $this->trxRoundId
= $fname;
1180 $this->forEachOpenMasterConnection(
1181 function ( DatabaseBase
$conn ) use ( $fname, &$failures ) {
1182 $conn->setTrxEndCallbackSuppression( true );
1184 $conn->flushSnapshot( $fname );
1185 } catch ( DBError
$e ) {
1186 call_user_func( $this->errorLogger
, $e );
1187 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1189 $conn->setTrxEndCallbackSuppression( false );
1190 $this->applyTransactionRoundFlags( $conn );
1195 throw new DBExpectedError(
1197 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1203 * Issue COMMIT on all master connections where writes where done
1204 * @param string $fname Caller name
1205 * @throws DBExpectedError
1207 public function commitMasterChanges( $fname = __METHOD__
) {
1210 $restore = ( $this->trxRoundId
!== false );
1211 $this->trxRoundId
= false;
1212 $this->forEachOpenMasterConnection(
1213 function ( DatabaseBase
$conn ) use ( $fname, $restore, &$failures ) {
1215 if ( $conn->writesOrCallbacksPending() ) {
1216 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1217 } elseif ( $restore ) {
1218 $conn->flushSnapshot( $fname );
1220 } catch ( DBError
$e ) {
1221 call_user_func( $this->errorLogger
, $e );
1222 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1225 $this->undoTransactionRoundFlags( $conn );
1231 throw new DBExpectedError(
1233 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1239 * Issue all pending post-COMMIT/ROLLBACK callbacks
1240 * @param integer $type IDatabase::TRIGGER_* constant
1241 * @return Exception|null The first exception or null if there were none
1244 public function runMasterPostTrxCallbacks( $type ) {
1245 $e = null; // first exception
1246 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) use ( $type, &$e ) {
1247 $conn->setTrxEndCallbackSuppression( false );
1248 if ( $conn->writesOrCallbacksPending() ) {
1249 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1250 // (which finished its callbacks already). Warn and recover in this case. Let the
1251 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1252 wfWarn( __METHOD__
. ": did not expect writes/callbacks pending." );
1254 } elseif ( $conn->trxLevel() ) {
1255 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1256 // thus leaving an implicit read-only transaction open at this point. It
1257 // also happens if onTransactionIdle() callbacks leave implicit transactions
1258 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1259 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1263 $conn->runOnTransactionIdleCallbacks( $type );
1264 } catch ( Exception
$ex ) {
1268 $conn->runTransactionListenerCallbacks( $type );
1269 } catch ( Exception
$ex ) {
1278 * Issue ROLLBACK only on master, only if queries were done on connection
1279 * @param string $fname Caller name
1280 * @throws DBExpectedError
1283 public function rollbackMasterChanges( $fname = __METHOD__
) {
1284 $restore = ( $this->trxRoundId
!== false );
1285 $this->trxRoundId
= false;
1286 $this->forEachOpenMasterConnection(
1287 function ( DatabaseBase
$conn ) use ( $fname, $restore ) {
1288 if ( $conn->writesOrCallbacksPending() ) {
1289 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1292 $this->undoTransactionRoundFlags( $conn );
1299 * Suppress all pending post-COMMIT/ROLLBACK callbacks
1300 * @return Exception|null The first exception or null if there were none
1303 public function suppressTransactionEndCallbacks() {
1304 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) {
1305 $conn->setTrxEndCallbackSuppression( true );
1310 * @param DatabaseBase $conn
1312 private function applyTransactionRoundFlags( DatabaseBase
$conn ) {
1313 if ( $conn->getFlag( DBO_DEFAULT
) ) {
1314 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1315 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1316 $conn->setFlag( DBO_TRX
, $conn::REMEMBER_PRIOR
);
1317 // If config has explicitly requested DBO_TRX be either on or off by not
1318 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1319 // for things like blob stores (ExternalStore) which want auto-commit mode.
1324 * @param DatabaseBase $conn
1326 private function undoTransactionRoundFlags( DatabaseBase
$conn ) {
1327 if ( $conn->getFlag( DBO_DEFAULT
) ) {
1328 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1333 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
1335 * @param string $fname Caller name
1338 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1339 $this->forEachOpenReplicaConnection( function ( DatabaseBase
$conn ) {
1340 $conn->flushSnapshot( __METHOD__
);
1345 * @return bool Whether a master connection is already open
1348 public function hasMasterConnection() {
1349 return $this->isOpen( $this->getWriterIndex() );
1353 * Determine if there are pending changes in a transaction by this thread
1357 public function hasMasterChanges() {
1359 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) use ( &$pending ) {
1360 $pending |
= $conn->writesOrCallbacksPending();
1363 return (bool)$pending;
1367 * Get the timestamp of the latest write query done by this thread
1369 * @return float|bool UNIX timestamp or false
1371 public function lastMasterChangeTimestamp() {
1373 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) use ( &$lastTime ) {
1374 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1381 * Check if this load balancer object had any recent or still
1382 * pending writes issued against it by this PHP thread
1384 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
1388 public function hasOrMadeRecentMasterChanges( $age = null ) {
1389 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1391 return ( $this->hasMasterChanges()
1392 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1396 * Get the list of callers that have pending master changes
1398 * @return string[] List of method names
1401 public function pendingMasterChangeCallers() {
1403 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) use ( &$fnames ) {
1404 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1411 * @note This method will trigger a DB connection if not yet done
1412 * @param string|bool $wiki Wiki ID, or false for the current wiki
1413 * @return bool Whether the generic connection for reads is highly "lagged"
1415 public function getLaggedReplicaMode( $wiki = false ) {
1416 // No-op if there is only one DB (also avoids recursion)
1417 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1419 // See if laggedReplicaMode gets set
1420 $conn = $this->getConnection( DB_REPLICA
, false, $wiki );
1421 $this->reuseConnection( $conn );
1422 } catch ( DBConnectionError
$e ) {
1423 // Avoid expensive re-connect attempts and failures
1424 $this->allReplicasDownMode
= true;
1425 $this->laggedReplicaMode
= true;
1429 return $this->laggedReplicaMode
;
1435 * @deprecated 1.28; use getLaggedReplicaMode()
1437 public function getLaggedSlaveMode( $wiki = false ) {
1438 return $this->getLaggedReplicaMode( $wiki );
1442 * @note This method will never cause a new DB connection
1443 * @return bool Whether any generic connection used for reads was highly "lagged"
1446 public function laggedReplicaUsed() {
1447 return $this->laggedReplicaMode
;
1453 * @deprecated Since 1.28; use laggedReplicaUsed()
1455 public function laggedSlaveUsed() {
1456 return $this->laggedReplicaUsed();
1460 * @note This method may trigger a DB connection if not yet done
1461 * @param string|bool $wiki Wiki ID, or false for the current wiki
1462 * @param DatabaseBase|null DB master connection; used to avoid loops [optional]
1463 * @return string|bool Reason the master is read-only or false if it is not
1466 public function getReadOnlyReason( $wiki = false, DatabaseBase
$conn = null ) {
1467 if ( $this->readOnlyReason
!== false ) {
1468 return $this->readOnlyReason
;
1469 } elseif ( $this->getLaggedReplicaMode( $wiki ) ) {
1470 if ( $this->allReplicasDownMode
) {
1471 return 'The database has been automatically locked ' .
1472 'until the replica database servers become available';
1474 return 'The database has been automatically locked ' .
1475 'while the replica database servers catch up to the master.';
1477 } elseif ( $this->masterRunningReadOnly( $wiki, $conn ) ) {
1478 return 'The database master is running in read-only mode.';
1485 * @param string $wiki Wiki ID, or false for the current wiki
1486 * @param DatabaseBase|null DB master connectionl used to avoid loops [optional]
1489 private function masterRunningReadOnly( $wiki, DatabaseBase
$conn = null ) {
1490 $cache = $this->wanCache
;
1491 $masterServer = $this->getServerName( $this->getWriterIndex() );
1493 return (bool)$cache->getWithSetCallback(
1494 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1495 self
::TTL_CACHE_READONLY
,
1496 function () use ( $wiki, $conn ) {
1497 $this->trxProfiler
->setSilenced( true );
1499 $dbw = $conn ?
: $this->getConnection( DB_MASTER
, [], $wiki );
1500 $readOnly = (int)$dbw->serverIsReadOnly();
1501 } catch ( DBError
$e ) {
1504 $this->trxProfiler
->setSilenced( false );
1507 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1512 * Disables/enables lag checks
1513 * @param null|bool $mode
1516 public function allowLagged( $mode = null ) {
1517 if ( $mode === null ) {
1518 return $this->mAllowLagged
;
1520 $this->mAllowLagged
= $mode;
1522 return $this->mAllowLagged
;
1528 public function pingAll() {
1530 $this->forEachOpenConnection( function ( DatabaseBase
$conn ) use ( &$success ) {
1531 if ( !$conn->ping() ) {
1540 * Call a function with each open connection object
1541 * @param callable $callback
1542 * @param array $params
1544 public function forEachOpenConnection( $callback, array $params = [] ) {
1545 foreach ( $this->mConns
as $connsByServer ) {
1546 foreach ( $connsByServer as $serverConns ) {
1547 foreach ( $serverConns as $conn ) {
1548 $mergedParams = array_merge( [ $conn ], $params );
1549 call_user_func_array( $callback, $mergedParams );
1556 * Call a function with each open connection object to a master
1557 * @param callable $callback
1558 * @param array $params
1561 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1562 $masterIndex = $this->getWriterIndex();
1563 foreach ( $this->mConns
as $connsByServer ) {
1564 if ( isset( $connsByServer[$masterIndex] ) ) {
1565 /** @var DatabaseBase $conn */
1566 foreach ( $connsByServer[$masterIndex] as $conn ) {
1567 $mergedParams = array_merge( [ $conn ], $params );
1568 call_user_func_array( $callback, $mergedParams );
1575 * Call a function with each open replica DB connection object
1576 * @param callable $callback
1577 * @param array $params
1580 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1581 foreach ( $this->mConns
as $connsByServer ) {
1582 foreach ( $connsByServer as $i => $serverConns ) {
1583 if ( $i === $this->getWriterIndex() ) {
1584 continue; // skip master
1586 foreach ( $serverConns as $conn ) {
1587 $mergedParams = array_merge( [ $conn ], $params );
1588 call_user_func_array( $callback, $mergedParams );
1595 * Get the hostname and lag time of the most-lagged replica DB
1597 * This is useful for maintenance scripts that need to throttle their updates.
1598 * May attempt to open connections to replica DBs on the default DB. If there is
1599 * no lag, the maximum lag will be reported as -1.
1601 * @param bool|string $wiki Wiki ID, or false for the default database
1602 * @return array ( host, max lag, index of max lagged host )
1604 public function getMaxLag( $wiki = false ) {
1609 if ( $this->getServerCount() <= 1 ) {
1610 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1613 $lagTimes = $this->getLagTimes( $wiki );
1614 foreach ( $lagTimes as $i => $lag ) {
1615 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1617 $host = $this->mServers
[$i]['host'];
1622 return [ $host, $maxLag, $maxIndex ];
1626 * Get an estimate of replication lag (in seconds) for each server
1628 * Results are cached for a short time in memcached/process cache
1630 * Values may be "false" if replication is too broken to estimate
1632 * @param string|bool $wiki
1633 * @return int[] Map of (server index => float|int|bool)
1635 public function getLagTimes( $wiki = false ) {
1636 if ( $this->getServerCount() <= 1 ) {
1637 return [ 0 => 0 ]; // no replication = no lag
1640 # Send the request to the load monitor
1641 return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
1645 * Get the lag in seconds for a given connection, or zero if this load
1646 * balancer does not have replication enabled.
1648 * This should be used in preference to Database::getLag() in cases where
1649 * replication may not be in use, since there is no way to determine if
1650 * replication is in use at the connection level without running
1651 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1652 * function instead of Database::getLag() avoids a fatal error in this
1653 * case on many installations.
1655 * @param IDatabase $conn
1656 * @return int|bool Returns false on error
1658 public function safeGetLag( IDatabase
$conn ) {
1659 if ( $this->getServerCount() == 1 ) {
1662 return $conn->getLag();
1667 * Wait for a replica DB to reach a specified master position
1669 * This will connect to the master to get an accurate position if $pos is not given
1671 * @param IDatabase $conn Replica DB
1672 * @param DBMasterPos|bool $pos Master position; default: current position
1673 * @param integer|null $timeout Timeout in seconds [optional]
1674 * @return bool Success
1677 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
1678 if ( $this->getServerCount() == 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1679 return true; // server is not a replica DB
1682 $pos = $pos ?
: $this->getConnection( DB_MASTER
)->getMasterPos();
1683 if ( !( $pos instanceof DBMasterPos
) ) {
1684 return false; // something is misconfigured
1687 $timeout = $timeout ?
: $this->mWaitTimeout
;
1688 $result = $conn->masterPosWait( $pos, $timeout );
1689 if ( $result == -1 ||
is_null( $result ) ) {
1690 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1691 wfDebugLog( 'replication', "$msg\n" );
1692 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1695 wfDebugLog( 'replication', __METHOD__
. ": Done\n" );
1703 * Clear the cache for slag lag delay times
1705 * This is only used for testing
1707 public function clearLagTimeCache() {
1708 $this->getLoadMonitor()->clearCaches();
1712 * Set a callback via DatabaseBase::setTransactionListener() on
1713 * all current and future master connections of this load balancer
1715 * @param string $name Callback name
1716 * @param callable|null $callback
1719 public function setTransactionListener( $name, callable
$callback = null ) {
1721 $this->trxRecurringCallbacks
[$name] = $callback;
1723 unset( $this->trxRecurringCallbacks
[$name] );
1725 $this->forEachOpenMasterConnection(
1726 function ( DatabaseBase
$conn ) use ( $name, $callback ) {
1727 $conn->setTransactionListener( $name, $callback );
1733 * Set a new table prefix for the existing local wiki ID for testing
1735 * @param string $prefix
1738 public function setDomainPrefix( $prefix ) {
1739 list( $dbName, ) = explode( '-', $this->localDomain
, 2 );
1741 $this->localDomain
= "{$dbName}-{$prefix}";