3 * Database load balancing.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * Database load balancing object
31 /** @var array[] Map of (server index => server config array) */
33 /** @var array[] Map of (local/foreignUsed/foreignFree => server index => DatabaseBase array) */
35 /** @var array Map of (server index => weight) */
37 /** @var array[] Map of (group => server index => weight) */
39 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
40 private $mAllowLagged;
41 /** @var integer Seconds to spend waiting on replica DB lag to resolve */
42 private $mWaitTimeout;
43 /** @var array LBFactory information */
46 /** @var string The LoadMonitor subclass name */
47 private $mLoadMonitorClass;
48 /** @var LoadMonitor */
49 private $mLoadMonitor;
52 /** @var WANObjectCache */
54 /** @var TransactionProfiler */
55 protected $trxProfiler;
57 /** @var bool|DatabaseBase Database connection that caused a problem */
58 private $mErrorConnection;
59 /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
61 /** @var bool|DBMasterPos False if not set */
63 /** @var bool Whether the generic reader fell back to a lagged replica DB */
64 private $laggedReplicaMode = false;
65 /** @var bool Whether the generic reader fell back to a lagged replica DB */
66 private $allReplicasDownMode = false;
67 /** @var string The last DB selection or connection error */
68 private $mLastError = 'Unknown error';
69 /** @var string|bool Reason the LB is read-only or false if not */
70 private $readOnlyReason = false;
71 /** @var integer Total connections opened */
72 private $connsOpened = 0;
73 /** @var string|bool String if a requested DBO_TRX transaction round is active */
74 private $trxRoundId = false;
75 /** @var array[] Map of (name => callable) */
76 private $trxRecurringCallbacks = [];
78 /** @var integer Warn when this many connection are held */
79 const CONN_HELD_WARN_THRESHOLD
= 10;
80 /** @var integer Default 'max lag' when unspecified */
81 const MAX_LAG_DEFAULT
= 10;
82 /** @var integer Max time to wait for a replica DB to catch up (e.g. ChronologyProtector) */
83 const POS_WAIT_TIMEOUT
= 10;
84 /** @var integer Seconds to cache master server read-only status */
85 const TTL_CACHE_READONLY
= 5;
90 private $disabled = false;
93 * @param array $params Array with keys:
94 * - servers : Required. Array of server info structures.
95 * - loadMonitor : Name of a class used to fetch server lag and load.
96 * - readOnlyReason : Reason the master DB is read-only if so [optional]
97 * - waitTimeout : Maximum time to wait for replicas for consistency [optional]
98 * - srvCache : BagOStuff object [optional]
99 * - wanCache : WANObjectCache object [optional]
100 * @throws MWException
102 public function __construct( array $params ) {
103 if ( !isset( $params['servers'] ) ) {
104 throw new MWException( __CLASS__
. ': missing servers parameter' );
106 $this->mServers
= $params['servers'];
107 $this->mWaitTimeout
= isset( $params['waitTimeout'] )
108 ?
$params['waitTimeout']
109 : self
::POS_WAIT_TIMEOUT
;
111 $this->mReadIndex
= -1;
112 $this->mWriteIndex
= -1;
116 'foreignFree' => [] ];
118 $this->mWaitForPos
= false;
119 $this->mErrorConnection
= false;
120 $this->mAllowLagged
= false;
122 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
123 $this->readOnlyReason
= $params['readOnlyReason'];
126 if ( isset( $params['loadMonitor'] ) ) {
127 $this->mLoadMonitorClass
= $params['loadMonitor'];
129 $master = reset( $params['servers'] );
130 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
131 $this->mLoadMonitorClass
= 'LoadMonitorMySQL';
133 $this->mLoadMonitorClass
= 'LoadMonitorNull';
137 foreach ( $params['servers'] as $i => $server ) {
138 $this->mLoads
[$i] = $server['load'];
139 if ( isset( $server['groupLoads'] ) ) {
140 foreach ( $server['groupLoads'] as $group => $ratio ) {
141 if ( !isset( $this->mGroupLoads
[$group] ) ) {
142 $this->mGroupLoads
[$group] = [];
144 $this->mGroupLoads
[$group][$i] = $ratio;
149 if ( isset( $params['srvCache'] ) ) {
150 $this->srvCache
= $params['srvCache'];
152 $this->srvCache
= new EmptyBagOStuff();
154 if ( isset( $params['wanCache'] ) ) {
155 $this->wanCache
= $params['wanCache'];
157 $this->wanCache
= WANObjectCache
::newEmpty();
159 if ( isset( $params['trxProfiler'] ) ) {
160 $this->trxProfiler
= $params['trxProfiler'];
162 $this->trxProfiler
= new TransactionProfiler();
167 * Get a LoadMonitor instance
169 * @return LoadMonitor
171 private function getLoadMonitor() {
172 if ( !isset( $this->mLoadMonitor
) ) {
173 $class = $this->mLoadMonitorClass
;
174 $this->mLoadMonitor
= new $class( $this );
177 return $this->mLoadMonitor
;
181 * Get or set arbitrary data used by the parent object, usually an LBFactory
185 public function parentInfo( $x = null ) {
186 return wfSetVar( $this->mParentInfo
, $x );
190 * @param array $loads
191 * @param bool|string $wiki Wiki to get non-lagged for
192 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
193 * @return bool|int|string
195 private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = INF
) {
196 $lags = $this->getLagTimes( $wiki );
198 # Unset excessively lagged servers
199 foreach ( $lags as $i => $lag ) {
201 # How much lag this server nominally is allowed to have
202 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
203 ?
$this->mServers
[$i]['max lag']
204 : self
::MAX_LAG_DEFAULT
; // default
205 # Constrain that futher by $maxLag argument
206 $maxServerLag = min( $maxServerLag, $maxLag );
208 $host = $this->getServerName( $i );
209 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
210 wfDebugLog( 'replication', "Server $host (#$i) is not replicating?" );
212 } elseif ( $lag > $maxServerLag ) {
213 wfDebugLog( 'replication', "Server $host (#$i) has >= $lag seconds of lag" );
219 # Find out if all the replica DBs with non-zero load are lagged
221 foreach ( $loads as $load ) {
225 # No appropriate DB servers except maybe the master and some replica DBs with zero load
226 # Do NOT use the master
227 # Instead, this function will return false, triggering read-only mode,
228 # and a lagged replica DB will be used instead.
232 if ( count( $loads ) == 0 ) {
236 # Return a random representative of the remainder
237 return ArrayUtils
::pickRandom( $loads );
241 * Get the index of the reader connection, which may be a replica DB
242 * This takes into account load ratios and lag times. It should
243 * always return a consistent index during a given invocation
245 * Side effect: opens connections to databases
246 * @param string|bool $group Query group, or false for the generic reader
247 * @param string|bool $wiki Wiki ID, or false for the current wiki
248 * @throws MWException
249 * @return bool|int|string
251 public function getReaderIndex( $group = false, $wiki = false ) {
254 # @todo FIXME: For now, only go through all this for mysql databases
255 if ( $wgDBtype != 'mysql' ) {
256 return $this->getWriterIndex();
259 if ( count( $this->mServers
) == 1 ) {
260 # Skip the load balancing if there's only one server
262 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
263 # Shortcut if generic reader exists already
264 return $this->mReadIndex
;
267 # Find the relevant load array
268 if ( $group !== false ) {
269 if ( isset( $this->mGroupLoads
[$group] ) ) {
270 $nonErrorLoads = $this->mGroupLoads
[$group];
272 # No loads for this group, return false and the caller can use some other group
273 wfDebugLog( 'connect', __METHOD__
. ": no loads for group $group\n" );
278 $nonErrorLoads = $this->mLoads
;
281 if ( !count( $nonErrorLoads ) ) {
282 throw new MWException( "Empty server array given to LoadBalancer" );
285 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
286 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
288 $laggedReplicaMode = false;
290 # No server found yet
292 # First try quickly looking through the available servers for a server that
294 $currentLoads = $nonErrorLoads;
295 while ( count( $currentLoads ) ) {
296 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
297 $i = ArrayUtils
::pickRandom( $currentLoads );
300 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
301 # ChronologyProtecter causes mWaitForPos to be set via sessions.
302 # This triggers doWait() after connect, so it's especially good to
303 # avoid lagged servers so as to avoid just blocking in that method.
304 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
305 # Aim for <= 1 second of waiting (being too picky can backfire)
306 $i = $this->getRandomNonLagged( $currentLoads, $wiki, $ago +
1 );
308 if ( $i === false ) {
309 # Any server with less lag than it's 'max lag' param is preferable
310 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
312 if ( $i === false && count( $currentLoads ) != 0 ) {
313 # All replica DBs lagged. Switch to read-only mode
314 wfDebugLog( 'replication', "All replica DBs lagged. Switch to read-only mode" );
315 $i = ArrayUtils
::pickRandom( $currentLoads );
316 $laggedReplicaMode = true;
320 if ( $i === false ) {
321 # pickRandom() returned false
322 # This is permanent and means the configuration or the load monitor
323 # wants us to return false.
324 wfDebugLog( 'connect', __METHOD__
. ": pickRandom() returned false" );
329 $serverName = $this->getServerName( $i );
330 wfDebugLog( 'connect', __METHOD__
. ": Using reader #$i: $serverName..." );
332 $conn = $this->openConnection( $i, $wiki );
334 wfDebugLog( 'connect', __METHOD__
. ": Failed connecting to $i/$wiki" );
335 unset( $nonErrorLoads[$i] );
336 unset( $currentLoads[$i] );
341 // Decrement reference counter, we are finished with this connection.
342 // It will be incremented for the caller later.
343 if ( $wiki !== false ) {
344 $this->reuseConnection( $conn );
351 # If all servers were down, quit now
352 if ( !count( $nonErrorLoads ) ) {
353 wfDebugLog( 'connect', "All servers down" );
356 if ( $i !== false ) {
357 # Replica DB connection successful.
358 # Wait for the session master pos for a short time.
359 if ( $this->mWaitForPos
&& $i > 0 ) {
362 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
363 $this->mReadIndex
= $i;
364 # Record if the generic reader index is in "lagged replica DB" mode
365 if ( $laggedReplicaMode ) {
366 $this->laggedReplicaMode
= true;
369 $serverName = $this->getServerName( $i );
370 wfDebugLog( 'connect', __METHOD__
.
371 ": using server $serverName for group '$group'\n" );
378 * Set the master wait position
379 * If a DB_REPLICA connection has been opened already, waits
380 * Otherwise sets a variable telling it to wait if such a connection is opened
381 * @param DBMasterPos $pos
383 public function waitFor( $pos ) {
384 $this->mWaitForPos
= $pos;
385 $i = $this->mReadIndex
;
388 if ( !$this->doWait( $i ) ) {
389 $this->laggedReplicaMode
= true;
395 * Set the master wait position and wait for a "generic" replica DB to catch up to it
397 * This can be used a faster proxy for waitForAll()
399 * @param DBMasterPos $pos
400 * @param int $timeout Max seconds to wait; default is mWaitTimeout
401 * @return bool Success (able to connect and no timeouts reached)
404 public function waitForOne( $pos, $timeout = null ) {
405 $this->mWaitForPos
= $pos;
407 $i = $this->mReadIndex
;
409 // Pick a generic replica DB if there isn't one yet
410 $readLoads = $this->mLoads
;
411 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
412 $readLoads = array_filter( $readLoads ); // with non-zero load
413 $i = ArrayUtils
::pickRandom( $readLoads );
417 $ok = $this->doWait( $i, true, $timeout );
419 $ok = true; // no applicable loads
426 * Set the master wait position and wait for ALL replica DBs to catch up to it
427 * @param DBMasterPos $pos
428 * @param int $timeout Max seconds to wait; default is mWaitTimeout
429 * @return bool Success (able to connect and no timeouts reached)
431 public function waitForAll( $pos, $timeout = null ) {
432 $this->mWaitForPos
= $pos;
433 $serverCount = count( $this->mServers
);
436 for ( $i = 1; $i < $serverCount; $i++
) {
437 if ( $this->mLoads
[$i] > 0 ) {
438 $ok = $this->doWait( $i, true, $timeout ) && $ok;
446 * Get any open connection to a given server index, local or foreign
447 * Returns false if there is no connection open
450 * @return DatabaseBase|bool False on failure
452 public function getAnyOpenConnection( $i ) {
453 foreach ( $this->mConns
as $conns ) {
454 if ( !empty( $conns[$i] ) ) {
455 return reset( $conns[$i] );
463 * Wait for a given replica DB to catch up to the master pos stored in $this
464 * @param int $index Server index
465 * @param bool $open Check the server even if a new connection has to be made
466 * @param int $timeout Max seconds to wait; default is mWaitTimeout
469 protected function doWait( $index, $open = false, $timeout = null ) {
470 $close = false; // close the connection afterwards
472 // Check if we already know that the DB has reached this point
473 $server = $this->getServerName( $index );
474 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server );
475 /** @var DBMasterPos $knownReachedPos */
476 $knownReachedPos = $this->srvCache
->get( $key );
477 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos
) ) {
478 wfDebugLog( 'replication', __METHOD__
.
479 ": replica DB $server known to be caught up (pos >= $knownReachedPos).\n" );
483 // Find a connection to wait on, creating one if needed and allowed
484 $conn = $this->getAnyOpenConnection( $index );
487 wfDebugLog( 'replication', __METHOD__
. ": no connection open for $server\n" );
491 $conn = $this->openConnection( $index, '' );
493 wfDebugLog( 'replication', __METHOD__
. ": failed to connect to $server\n" );
497 // Avoid connection spam in waitForAll() when connections
498 // are made just for the sake of doing this lag check.
503 wfDebugLog( 'replication', __METHOD__
. ": Waiting for replica DB $server to catch up...\n" );
504 $timeout = $timeout ?
: $this->mWaitTimeout
;
505 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
507 if ( $result == -1 ||
is_null( $result ) ) {
508 // Timed out waiting for replica DB, use master instead
509 $msg = __METHOD__
. ": Timed out waiting on $server pos {$this->mWaitForPos}";
510 wfDebugLog( 'replication', "$msg\n" );
511 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
514 wfDebugLog( 'replication', __METHOD__
. ": Done\n" );
516 // Remember that the DB reached this point
517 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
521 $this->closeConnection( $conn );
528 * Get a connection by index
529 * This is the main entry point for this class.
531 * @param int $i Server index
532 * @param array|string|bool $groups Query group(s), or false for the generic reader
533 * @param string|bool $wiki Wiki ID, or false for the current wiki
535 * @throws MWException
536 * @return DatabaseBase
538 public function getConnection( $i, $groups = [], $wiki = false ) {
539 if ( $i === null ||
$i === false ) {
540 throw new MWException( 'Attempt to call ' . __METHOD__
.
541 ' with invalid server index' );
544 if ( $wiki === wfWikiID() ) {
548 $groups = ( $groups === false ||
$groups === [] )
549 ?
[ false ] // check one "group": the generic pool
552 $masterOnly = ( $i == DB_MASTER ||
$i == $this->getWriterIndex() );
553 $oldConnsOpened = $this->connsOpened
; // connections open now
555 if ( $i == DB_MASTER
) {
556 $i = $this->getWriterIndex();
558 # Try to find an available server in any the query groups (in order)
559 foreach ( $groups as $group ) {
560 $groupIndex = $this->getReaderIndex( $group, $wiki );
561 if ( $groupIndex !== false ) {
568 # Operation-based index
569 if ( $i == DB_REPLICA
) {
570 $this->mLastError
= 'Unknown error'; // reset error string
571 # Try the general server pool if $groups are unavailable.
572 $i = in_array( false, $groups, true )
573 ?
false // don't bother with this if that is what was tried above
574 : $this->getReaderIndex( false, $wiki );
575 # Couldn't find a working server in getReaderIndex()?
576 if ( $i === false ) {
577 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
579 return $this->reportConnectionError();
583 # Now we have an explicit index into the servers array
584 $conn = $this->openConnection( $i, $wiki );
586 return $this->reportConnectionError();
589 # Profile any new connections that happen
590 if ( $this->connsOpened
> $oldConnsOpened ) {
591 $host = $conn->getServer();
592 $dbname = $conn->getDBname();
593 $trxProf = Profiler
::instance()->getTransactionProfiler();
594 $trxProf->recordConnection( $host, $dbname, $masterOnly );
598 # Make master-requested DB handles inherit any read-only mode setting
599 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $wiki, $conn ) );
606 * Mark a foreign connection as being available for reuse under a different
607 * DB name or prefix. This mechanism is reference-counted, and must be called
608 * the same number of times as getConnection() to work.
610 * @param DatabaseBase $conn
611 * @throws MWException
613 public function reuseConnection( $conn ) {
614 $serverIndex = $conn->getLBInfo( 'serverIndex' );
615 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
616 if ( $serverIndex === null ||
$refCount === null ) {
618 * This can happen in code like:
619 * foreach ( $dbs as $db ) {
620 * $conn = $lb->getConnection( DB_REPLICA, [], $db );
622 * $lb->reuseConnection( $conn );
624 * When a connection to the local DB is opened in this way, reuseConnection()
630 $dbName = $conn->getDBname();
631 $prefix = $conn->tablePrefix();
632 if ( strval( $prefix ) !== '' ) {
633 $wiki = "$dbName-$prefix";
637 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
638 throw new MWException( __METHOD__
. ": connection not found, has " .
639 "the connection been freed already?" );
641 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
642 if ( $refCount <= 0 ) {
643 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
644 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
645 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
647 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
652 * Get a database connection handle reference
654 * The handle's methods wrap simply wrap those of a DatabaseBase handle
656 * @see LoadBalancer::getConnection() for parameter information
659 * @param array|string|bool $groups Query group(s), or false for the generic reader
660 * @param string|bool $wiki Wiki ID, or false for the current wiki
663 public function getConnectionRef( $db, $groups = [], $wiki = false ) {
664 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
668 * Get a database connection handle reference without connecting yet
670 * The handle's methods wrap simply wrap those of a DatabaseBase handle
672 * @see LoadBalancer::getConnection() for parameter information
675 * @param array|string|bool $groups Query group(s), or false for the generic reader
676 * @param string|bool $wiki Wiki ID, or false for the current wiki
679 public function getLazyConnectionRef( $db, $groups = [], $wiki = false ) {
680 return new DBConnRef( $this, [ $db, $groups, $wiki ] );
684 * Open a connection to the server given by the specified index
685 * Index must be an actual index into the array.
686 * If the server is already open, returns it.
688 * On error, returns false, and the connection which caused the
689 * error will be available via $this->mErrorConnection.
691 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
693 * @param int $i Server index
694 * @param string|bool $wiki Wiki ID, or false for the current wiki
695 * @return DatabaseBase|bool Returns false on errors
697 public function openConnection( $i, $wiki = false ) {
698 if ( $wiki !== false ) {
699 $conn = $this->openForeignConnection( $i, $wiki );
700 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
701 $conn = $this->mConns
['local'][$i][0];
703 $server = $this->mServers
[$i];
704 $server['serverIndex'] = $i;
705 $conn = $this->reallyOpenConnection( $server, false );
706 $serverName = $this->getServerName( $i );
707 if ( $conn->isOpen() ) {
708 wfDebugLog( 'connect', "Connected to database $i at $serverName\n" );
709 $this->mConns
['local'][$i][0] = $conn;
711 wfDebugLog( 'connect', "Failed to connect to database $i at $serverName\n" );
712 $this->mErrorConnection
= $conn;
717 if ( $conn && !$conn->isOpen() ) {
718 // Connection was made but later unrecoverably lost for some reason.
719 // Do not return a handle that will just throw exceptions on use,
720 // but let the calling code (e.g. getReaderIndex) try another server.
721 // See DatabaseMyslBase::ping() for how this can happen.
722 $this->mErrorConnection
= $conn;
730 * Open a connection to a foreign DB, or return one if it is already open.
732 * Increments a reference count on the returned connection which locks the
733 * connection to the requested wiki. This reference count can be
734 * decremented by calling reuseConnection().
736 * If a connection is open to the appropriate server already, but with the wrong
737 * database, it will be switched to the right database and returned, as long as
738 * it has been freed first with reuseConnection().
740 * On error, returns false, and the connection which caused the
741 * error will be available via $this->mErrorConnection.
743 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
745 * @param int $i Server index
746 * @param string $wiki Wiki ID to open
747 * @return DatabaseBase
749 private function openForeignConnection( $i, $wiki ) {
750 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
751 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
752 // Reuse an already-used connection
753 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
754 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
755 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
756 // Reuse a free connection for the same wiki
757 $conn = $this->mConns
['foreignFree'][$i][$wiki];
758 unset( $this->mConns
['foreignFree'][$i][$wiki] );
759 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
760 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
761 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
762 // Reuse a connection from another wiki
763 $conn = reset( $this->mConns
['foreignFree'][$i] );
764 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
766 // The empty string as a DB name means "don't care".
767 // DatabaseMysqlBase::open() already handle this on connection.
768 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
769 $this->mLastError
= "Error selecting database $dbName on server " .
770 $conn->getServer() . " from client host " . wfHostname() . "\n";
771 $this->mErrorConnection
= $conn;
774 $conn->tablePrefix( $prefix );
775 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
776 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
777 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
780 // Open a new connection
781 $server = $this->mServers
[$i];
782 $server['serverIndex'] = $i;
783 $server['foreignPoolRefCount'] = 0;
784 $server['foreign'] = true;
785 $conn = $this->reallyOpenConnection( $server, $dbName );
786 if ( !$conn->isOpen() ) {
787 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
788 $this->mErrorConnection
= $conn;
791 $conn->tablePrefix( $prefix );
792 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
793 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
797 // Increment reference count
799 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
800 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
807 * Test if the specified index represents an open connection
809 * @param int $index Server index
813 private function isOpen( $index ) {
814 if ( !is_integer( $index ) ) {
818 return (bool)$this->getAnyOpenConnection( $index );
822 * Really opens a connection. Uncached.
823 * Returns a Database object whether or not the connection was successful.
826 * @param array $server
827 * @param bool $dbNameOverride
828 * @throws MWException
829 * @return DatabaseBase
831 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
832 if ( $this->disabled
) {
833 throw new DBAccessError();
836 if ( !is_array( $server ) ) {
837 throw new MWException( 'You must update your load-balancing configuration. ' .
838 'See DefaultSettings.php entry for $wgDBservers.' );
841 if ( $dbNameOverride !== false ) {
842 $server['dbname'] = $dbNameOverride;
845 // Let the handle know what the cluster master is (e.g. "db1052")
846 $masterName = $this->getServerName( 0 );
847 $server['clusterMasterHost'] = $masterName;
849 // Log when many connection are made on requests
850 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
851 wfDebugLog( 'DBPerformance', __METHOD__
. ": " .
852 "{$this->connsOpened}+ connections made (master=$masterName)\n" .
853 wfBacktrace( true ) );
858 $db = DatabaseBase
::factory( $server['type'], $server );
859 } catch ( DBConnectionError
$e ) {
860 // FIXME: This is probably the ugliest thing I have ever done to
861 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
865 $db->setLBInfo( $server );
866 $db->setLazyMasterHandle(
867 $this->getLazyConnectionRef( DB_MASTER
, [], $db->getWikiID() )
869 $db->setTransactionProfiler( $this->trxProfiler
);
871 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
872 if ( $this->trxRoundId
!== false ) {
873 $this->applyTransactionRoundFlags( $db );
875 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
876 $db->setTransactionListener( $name, $callback );
884 * @throws DBConnectionError
887 private function reportConnectionError() {
888 $conn = $this->mErrorConnection
; // The connection which caused the error
890 'method' => __METHOD__
,
891 'last_error' => $this->mLastError
,
894 if ( !is_object( $conn ) ) {
895 // No last connection, probably due to all servers being too busy
897 "LB failure with no last connection. Connection error: {last_error}",
901 // If all servers were busy, mLastError will contain something sensible
902 throw new DBConnectionError( null, $this->mLastError
);
904 $context['db_server'] = $conn->getProperty( 'mServer' );
906 "Connection error: {last_error} ({db_server})",
910 // throws DBConnectionError
911 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
914 return false; /* not reached */
921 public function getWriterIndex() {
926 * Returns true if the specified index is a valid server index
931 public function haveIndex( $i ) {
932 return array_key_exists( $i, $this->mServers
);
936 * Returns true if the specified index is valid and has non-zero load
941 public function isNonZeroLoad( $i ) {
942 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
946 * Get the number of defined servers (not the number of open connections)
950 public function getServerCount() {
951 return count( $this->mServers
);
955 * Get the host name or IP address of the server with the specified index
956 * Prefer a readable name if available.
960 public function getServerName( $i ) {
961 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
962 $name = $this->mServers
[$i]['hostName'];
963 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
964 $name = $this->mServers
[$i]['host'];
969 return ( $name != '' ) ?
$name : 'localhost';
973 * Return the server info structure for a given index, or false if the index is invalid.
977 public function getServerInfo( $i ) {
978 if ( isset( $this->mServers
[$i] ) ) {
979 return $this->mServers
[$i];
986 * Sets the server info structure for the given index. Entry at index $i
987 * is created if it doesn't exist
989 * @param array $serverInfo
991 public function setServerInfo( $i, array $serverInfo ) {
992 $this->mServers
[$i] = $serverInfo;
996 * Get the current master position for chronology control purposes
999 public function getMasterPos() {
1000 # If this entire request was served from a replica DB without opening a connection to the
1001 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1002 $masterConn = $this->getAnyOpenConnection( 0 );
1003 if ( !$masterConn ) {
1004 $serverCount = count( $this->mServers
);
1005 for ( $i = 1; $i < $serverCount; $i++
) {
1006 $conn = $this->getAnyOpenConnection( $i );
1008 return $conn->getSlavePos();
1012 return $masterConn->getMasterPos();
1019 * Disable this load balancer. All connections are closed, and any attempt to
1020 * open a new connection will result in a DBAccessError.
1024 public function disable() {
1026 $this->disabled
= true;
1030 * Close all open connections
1032 public function closeAll() {
1033 $this->forEachOpenConnection( function ( DatabaseBase
$conn ) {
1039 'foreignFree' => [],
1040 'foreignUsed' => [],
1042 $this->connsOpened
= 0;
1046 * 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.
1049 * @param DatabaseBase $conn
1051 public function closeConnection( $conn ) {
1053 foreach ( $this->mConns
as $i1 => $conns2 ) {
1054 foreach ( $conns2 as $i2 => $conns3 ) {
1055 foreach ( $conns3 as $i3 => $candidateConn ) {
1056 if ( $conn === $candidateConn ) {
1058 unset( $this->mConns
[$i1][$i2][$i3] );
1059 --$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 MWExceptionHandler
::logException( $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 MWExceptionHandler
::logException( $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 MWExceptionHandler
::logException( $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() {
1358 $masterIndex = $this->getWriterIndex();
1359 foreach ( $this->mConns
as $conns2 ) {
1360 if ( empty( $conns2[$masterIndex] ) ) {
1363 /** @var DatabaseBase $conn */
1364 foreach ( $conns2[$masterIndex] as $conn ) {
1365 if ( $conn->writesOrCallbacksPending() ) {
1374 * Get the timestamp of the latest write query done by this thread
1376 * @return float|bool UNIX timestamp or false
1378 public function lastMasterChangeTimestamp() {
1380 $masterIndex = $this->getWriterIndex();
1381 foreach ( $this->mConns
as $conns2 ) {
1382 if ( empty( $conns2[$masterIndex] ) ) {
1385 /** @var DatabaseBase $conn */
1386 foreach ( $conns2[$masterIndex] as $conn ) {
1387 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1394 * Check if this load balancer object had any recent or still
1395 * pending writes issued against it by this PHP thread
1397 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
1401 public function hasOrMadeRecentMasterChanges( $age = null ) {
1402 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1404 return ( $this->hasMasterChanges()
1405 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1409 * Get the list of callers that have pending master changes
1414 public function pendingMasterChangeCallers() {
1417 $masterIndex = $this->getWriterIndex();
1418 foreach ( $this->mConns
as $conns2 ) {
1419 if ( empty( $conns2[$masterIndex] ) ) {
1422 /** @var DatabaseBase $conn */
1423 foreach ( $conns2[$masterIndex] as $conn ) {
1424 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1432 * @note This method will trigger a DB connection if not yet done
1433 * @param string|bool $wiki Wiki ID, or false for the current wiki
1434 * @return bool Whether the generic connection for reads is highly "lagged"
1436 public function getLaggedReplicaMode( $wiki = false ) {
1437 // No-op if there is only one DB (also avoids recursion)
1438 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1440 // See if laggedReplicaMode gets set
1441 $conn = $this->getConnection( DB_REPLICA
, false, $wiki );
1442 $this->reuseConnection( $conn );
1443 } catch ( DBConnectionError
$e ) {
1444 // Avoid expensive re-connect attempts and failures
1445 $this->allReplicasDownMode
= true;
1446 $this->laggedReplicaMode
= true;
1450 return $this->laggedReplicaMode
;
1456 * @deprecated 1.28; use getLaggedReplicaMode()
1458 public function getLaggedSlaveMode( $wiki = false ) {
1459 return $this->getLaggedReplicaMode( $wiki );
1463 * @note This method will never cause a new DB connection
1464 * @return bool Whether any generic connection used for reads was highly "lagged"
1467 public function laggedReplicaUsed() {
1468 return $this->laggedReplicaMode
;
1474 * @deprecated Since 1.28; use laggedReplicaUsed()
1476 public function laggedSlaveUsed() {
1477 return $this->laggedReplicaUsed();
1481 * @note This method may trigger a DB connection if not yet done
1482 * @param string|bool $wiki Wiki ID, or false for the current wiki
1483 * @param DatabaseBase|null DB master connection; used to avoid loops [optional]
1484 * @return string|bool Reason the master is read-only or false if it is not
1487 public function getReadOnlyReason( $wiki = false, DatabaseBase
$conn = null ) {
1488 if ( $this->readOnlyReason
!== false ) {
1489 return $this->readOnlyReason
;
1490 } elseif ( $this->getLaggedReplicaMode( $wiki ) ) {
1491 if ( $this->allReplicasDownMode
) {
1492 return 'The database has been automatically locked ' .
1493 'until the replica database servers become available';
1495 return 'The database has been automatically locked ' .
1496 'while the replica database servers catch up to the master.';
1498 } elseif ( $this->masterRunningReadOnly( $wiki, $conn ) ) {
1499 return 'The database master is running in read-only mode.';
1506 * @param string $wiki Wiki ID, or false for the current wiki
1507 * @param DatabaseBase|null DB master connectionl used to avoid loops [optional]
1510 private function masterRunningReadOnly( $wiki, DatabaseBase
$conn = null ) {
1511 $cache = $this->wanCache
;
1512 $masterServer = $this->getServerName( $this->getWriterIndex() );
1514 return (bool)$cache->getWithSetCallback(
1515 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1516 self
::TTL_CACHE_READONLY
,
1517 function () use ( $wiki, $conn ) {
1518 $this->trxProfiler
->setSilenced( true );
1520 $dbw = $conn ?
: $this->getConnection( DB_MASTER
, [], $wiki );
1521 $readOnly = (int)$dbw->serverIsReadOnly();
1522 } catch ( DBError
$e ) {
1525 $this->trxProfiler
->setSilenced( false );
1528 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1533 * Disables/enables lag checks
1534 * @param null|bool $mode
1537 public function allowLagged( $mode = null ) {
1538 if ( $mode === null ) {
1539 return $this->mAllowLagged
;
1541 $this->mAllowLagged
= $mode;
1543 return $this->mAllowLagged
;
1549 public function pingAll() {
1551 $this->forEachOpenConnection( function ( DatabaseBase
$conn ) use ( &$success ) {
1552 if ( !$conn->ping() ) {
1561 * Call a function with each open connection object
1562 * @param callable $callback
1563 * @param array $params
1565 public function forEachOpenConnection( $callback, array $params = [] ) {
1566 foreach ( $this->mConns
as $connsByServer ) {
1567 foreach ( $connsByServer as $serverConns ) {
1568 foreach ( $serverConns as $conn ) {
1569 $mergedParams = array_merge( [ $conn ], $params );
1570 call_user_func_array( $callback, $mergedParams );
1577 * Call a function with each open connection object to a master
1578 * @param callable $callback
1579 * @param array $params
1582 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1583 $masterIndex = $this->getWriterIndex();
1584 foreach ( $this->mConns
as $connsByServer ) {
1585 if ( isset( $connsByServer[$masterIndex] ) ) {
1586 /** @var DatabaseBase $conn */
1587 foreach ( $connsByServer[$masterIndex] as $conn ) {
1588 $mergedParams = array_merge( [ $conn ], $params );
1589 call_user_func_array( $callback, $mergedParams );
1596 * Call a function with each open replica DB connection object
1597 * @param callable $callback
1598 * @param array $params
1601 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1602 foreach ( $this->mConns
as $connsByServer ) {
1603 foreach ( $connsByServer as $i => $serverConns ) {
1604 if ( $i === $this->getWriterIndex() ) {
1605 continue; // skip master
1607 foreach ( $serverConns as $conn ) {
1608 $mergedParams = array_merge( [ $conn ], $params );
1609 call_user_func_array( $callback, $mergedParams );
1616 * Get the hostname and lag time of the most-lagged replica DB
1618 * This is useful for maintenance scripts that need to throttle their updates.
1619 * May attempt to open connections to replica DBs on the default DB. If there is
1620 * no lag, the maximum lag will be reported as -1.
1622 * @param bool|string $wiki Wiki ID, or false for the default database
1623 * @return array ( host, max lag, index of max lagged host )
1625 public function getMaxLag( $wiki = false ) {
1630 if ( $this->getServerCount() <= 1 ) {
1631 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1634 $lagTimes = $this->getLagTimes( $wiki );
1635 foreach ( $lagTimes as $i => $lag ) {
1636 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1638 $host = $this->mServers
[$i]['host'];
1643 return [ $host, $maxLag, $maxIndex ];
1647 * Get an estimate of replication lag (in seconds) for each server
1649 * Results are cached for a short time in memcached/process cache
1651 * Values may be "false" if replication is too broken to estimate
1653 * @param string|bool $wiki
1654 * @return int[] Map of (server index => float|int|bool)
1656 public function getLagTimes( $wiki = false ) {
1657 if ( $this->getServerCount() <= 1 ) {
1658 return [ 0 => 0 ]; // no replication = no lag
1661 # Send the request to the load monitor
1662 return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
1666 * Get the lag in seconds for a given connection, or zero if this load
1667 * balancer does not have replication enabled.
1669 * This should be used in preference to Database::getLag() in cases where
1670 * replication may not be in use, since there is no way to determine if
1671 * replication is in use at the connection level without running
1672 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1673 * function instead of Database::getLag() avoids a fatal error in this
1674 * case on many installations.
1676 * @param IDatabase $conn
1677 * @return int|bool Returns false on error
1679 public function safeGetLag( IDatabase
$conn ) {
1680 if ( $this->getServerCount() == 1 ) {
1683 return $conn->getLag();
1688 * Wait for a replica DB to reach a specified master position
1690 * This will connect to the master to get an accurate position if $pos is not given
1692 * @param IDatabase $conn Replica DB
1693 * @param DBMasterPos|bool $pos Master position; default: current position
1694 * @param integer $timeout Timeout in seconds
1695 * @return bool Success
1698 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1699 if ( $this->getServerCount() == 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1700 return true; // server is not a replica DB
1703 $pos = $pos ?
: $this->getConnection( DB_MASTER
)->getMasterPos();
1704 if ( !( $pos instanceof DBMasterPos
) ) {
1705 return false; // something is misconfigured
1708 $result = $conn->masterPosWait( $pos, $timeout );
1709 if ( $result == -1 ||
is_null( $result ) ) {
1710 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1711 wfDebugLog( 'replication', "$msg\n" );
1712 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1715 wfDebugLog( 'replication', __METHOD__
. ": Done\n" );
1723 * Clear the cache for slag lag delay times
1725 * This is only used for testing
1727 public function clearLagTimeCache() {
1728 $this->getLoadMonitor()->clearCaches();
1732 * Set a callback via DatabaseBase::setTransactionListener() on
1733 * all current and future master connections of this load balancer
1735 * @param string $name Callback name
1736 * @param callable|null $callback
1739 public function setTransactionListener( $name, callable
$callback = null ) {
1741 $this->trxRecurringCallbacks
[$name] = $callback;
1743 unset( $this->trxRecurringCallbacks
[$name] );
1745 $this->forEachOpenMasterConnection(
1746 function ( DatabaseBase
$conn ) use ( $name, $callback ) {
1747 $conn->setTransactionListener( $name, $callback );