Remove global state from DatabaseBase::__construct()
[mediawiki.git] / includes / libs / rdbms / loadbalancer / LoadBalancer.php
blob824279dc8b2604ab99db56ca39769f47299134d0
1 <?php
2 /**
3 * Database load balancing manager
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Database
23 use Psr\Log\LoggerInterface;
25 /**
26 * Database load balancing, tracking, and transaction management object
28 * @ingroup Database
30 class LoadBalancer implements ILoadBalancer {
31 /** @var array[] Map of (server index => server config array) */
32 private $mServers;
33 /** @var array[] Map of (local/foreignUsed/foreignFree => server index => IDatabase array) */
34 private $mConns;
35 /** @var array Map of (server index => weight) */
36 private $mLoads;
37 /** @var array[] Map of (group => server index => weight) */
38 private $mGroupLoads;
39 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
40 private $mAllowLagged;
41 /** @var integer Seconds to spend waiting on replica DB lag to resolve */
42 private $mWaitTimeout;
43 /** @var string The LoadMonitor subclass name */
44 private $mLoadMonitorClass;
46 /** @var LoadMonitor */
47 private $mLoadMonitor;
48 /** @var BagOStuff */
49 private $srvCache;
50 /** @var BagOStuff */
51 private $memCache;
52 /** @var WANObjectCache */
53 private $wanCache;
54 /** @var TransactionProfiler */
55 protected $trxProfiler;
56 /** @var LoggerInterface */
57 protected $replLogger;
58 /** @var LoggerInterface */
59 protected $connLogger;
60 /** @var LoggerInterface */
61 protected $queryLogger;
62 /** @var LoggerInterface */
63 protected $perfLogger;
65 /** @var bool|IDatabase Database connection that caused a problem */
66 private $mErrorConnection;
67 /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
68 private $mReadIndex;
69 /** @var bool|DBMasterPos False if not set */
70 private $mWaitForPos;
71 /** @var bool Whether the generic reader fell back to a lagged replica DB */
72 private $laggedReplicaMode = false;
73 /** @var bool Whether the generic reader fell back to a lagged replica DB */
74 private $allReplicasDownMode = false;
75 /** @var string The last DB selection or connection error */
76 private $mLastError = 'Unknown error';
77 /** @var string|bool Reason the LB is read-only or false if not */
78 private $readOnlyReason = false;
79 /** @var integer Total connections opened */
80 private $connsOpened = 0;
81 /** @var string|bool String if a requested DBO_TRX transaction round is active */
82 private $trxRoundId = false;
83 /** @var array[] Map of (name => callable) */
84 private $trxRecurringCallbacks = [];
85 /** @var string Local Domain ID and default for selectDB() calls */
86 private $localDomain;
87 /** @var string Current server name */
88 private $host;
90 /** @var callable Exception logger */
91 private $errorLogger;
93 /** @var boolean */
94 private $disabled = false;
96 /** @var integer Warn when this many connection are held */
97 const CONN_HELD_WARN_THRESHOLD = 10;
98 /** @var integer Default 'max lag' when unspecified */
99 const MAX_LAG_DEFAULT = 10;
100 /** @var integer Max time to wait for a replica DB to catch up (e.g. ChronologyProtector) */
101 const POS_WAIT_TIMEOUT = 10;
102 /** @var integer Seconds to cache master server read-only status */
103 const TTL_CACHE_READONLY = 5;
105 public function __construct( array $params ) {
106 if ( !isset( $params['servers'] ) ) {
107 throw new InvalidArgumentException( __CLASS__ . ': missing servers parameter' );
109 $this->mServers = $params['servers'];
110 $this->mWaitTimeout = isset( $params['waitTimeout'] )
111 ? $params['waitTimeout']
112 : self::POS_WAIT_TIMEOUT;
113 $this->localDomain = isset( $params['localDomain'] ) ? $params['localDomain'] : '';
115 $this->mReadIndex = -1;
116 $this->mConns = [
117 'local' => [],
118 'foreignUsed' => [],
119 'foreignFree' => [] ];
120 $this->mLoads = [];
121 $this->mWaitForPos = false;
122 $this->mErrorConnection = false;
123 $this->mAllowLagged = false;
125 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
126 $this->readOnlyReason = $params['readOnlyReason'];
129 if ( isset( $params['loadMonitor'] ) ) {
130 $this->mLoadMonitorClass = $params['loadMonitor'];
131 } else {
132 $master = reset( $params['servers'] );
133 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
134 $this->mLoadMonitorClass = 'LoadMonitorMySQL';
135 } else {
136 $this->mLoadMonitorClass = 'LoadMonitorNull';
140 foreach ( $params['servers'] as $i => $server ) {
141 $this->mLoads[$i] = $server['load'];
142 if ( isset( $server['groupLoads'] ) ) {
143 foreach ( $server['groupLoads'] as $group => $ratio ) {
144 if ( !isset( $this->mGroupLoads[$group] ) ) {
145 $this->mGroupLoads[$group] = [];
147 $this->mGroupLoads[$group][$i] = $ratio;
152 if ( isset( $params['srvCache'] ) ) {
153 $this->srvCache = $params['srvCache'];
154 } else {
155 $this->srvCache = new EmptyBagOStuff();
157 if ( isset( $params['memCache'] ) ) {
158 $this->memCache = $params['memCache'];
159 } else {
160 $this->memCache = new EmptyBagOStuff();
162 if ( isset( $params['wanCache'] ) ) {
163 $this->wanCache = $params['wanCache'];
164 } else {
165 $this->wanCache = WANObjectCache::newEmpty();
167 if ( isset( $params['trxProfiler'] ) ) {
168 $this->trxProfiler = $params['trxProfiler'];
169 } else {
170 $this->trxProfiler = new TransactionProfiler();
173 $this->errorLogger = isset( $params['errorLogger'] )
174 ? $params['errorLogger']
175 : function ( Exception $e ) {
176 trigger_error( E_WARNING, $e->getMessage() );
179 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
180 $this->$key = isset( $params[$key] ) ? $params[$key] : new \Psr\Log\NullLogger();
183 $this->host = isset( $params['hostname'] )
184 ? $params['hostname']
185 : ( gethostname() ?: 'unknown' );
189 * Get a LoadMonitor instance
191 * @return LoadMonitor
193 private function getLoadMonitor() {
194 if ( !isset( $this->mLoadMonitor ) ) {
195 $class = $this->mLoadMonitorClass;
196 $this->mLoadMonitor = new $class( $this, $this->srvCache, $this->memCache );
197 $this->mLoadMonitor->setLogger( $this->replLogger );
200 return $this->mLoadMonitor;
204 * @param array $loads
205 * @param bool|string $domain Domain to get non-lagged for
206 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
207 * @return bool|int|string
209 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF ) {
210 $lags = $this->getLagTimes( $domain );
212 # Unset excessively lagged servers
213 foreach ( $lags as $i => $lag ) {
214 if ( $i != 0 ) {
215 # How much lag this server nominally is allowed to have
216 $maxServerLag = isset( $this->mServers[$i]['max lag'] )
217 ? $this->mServers[$i]['max lag']
218 : self::MAX_LAG_DEFAULT; // default
219 # Constrain that futher by $maxLag argument
220 $maxServerLag = min( $maxServerLag, $maxLag );
222 $host = $this->getServerName( $i );
223 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
224 $this->replLogger->error( "Server $host (#$i) is not replicating?" );
225 unset( $loads[$i] );
226 } elseif ( $lag > $maxServerLag ) {
227 $this->replLogger->warning( "Server $host (#$i) has >= $lag seconds of lag" );
228 unset( $loads[$i] );
233 # Find out if all the replica DBs with non-zero load are lagged
234 $sum = 0;
235 foreach ( $loads as $load ) {
236 $sum += $load;
238 if ( $sum == 0 ) {
239 # No appropriate DB servers except maybe the master and some replica DBs with zero load
240 # Do NOT use the master
241 # Instead, this function will return false, triggering read-only mode,
242 # and a lagged replica DB will be used instead.
243 return false;
246 if ( count( $loads ) == 0 ) {
247 return false;
250 # Return a random representative of the remainder
251 return ArrayUtils::pickRandom( $loads );
254 public function getReaderIndex( $group = false, $domain = false ) {
255 if ( count( $this->mServers ) == 1 ) {
256 # Skip the load balancing if there's only one server
257 return $this->getWriterIndex();
258 } elseif ( $group === false && $this->mReadIndex >= 0 ) {
259 # Shortcut if generic reader exists already
260 return $this->mReadIndex;
263 # Find the relevant load array
264 if ( $group !== false ) {
265 if ( isset( $this->mGroupLoads[$group] ) ) {
266 $nonErrorLoads = $this->mGroupLoads[$group];
267 } else {
268 # No loads for this group, return false and the caller can use some other group
269 $this->connLogger->info( __METHOD__ . ": no loads for group $group" );
271 return false;
273 } else {
274 $nonErrorLoads = $this->mLoads;
277 if ( !count( $nonErrorLoads ) ) {
278 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
281 # Scale the configured load ratios according to the dynamic load if supported
282 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $domain );
284 $laggedReplicaMode = false;
286 # No server found yet
287 $i = false;
288 # First try quickly looking through the available servers for a server that
289 # meets our criteria
290 $currentLoads = $nonErrorLoads;
291 while ( count( $currentLoads ) ) {
292 if ( $this->mAllowLagged || $laggedReplicaMode ) {
293 $i = ArrayUtils::pickRandom( $currentLoads );
294 } else {
295 $i = false;
296 if ( $this->mWaitForPos && $this->mWaitForPos->asOfTime() ) {
297 # ChronologyProtecter causes mWaitForPos to be set via sessions.
298 # This triggers doWait() after connect, so it's especially good to
299 # avoid lagged servers so as to avoid just blocking in that method.
300 $ago = microtime( true ) - $this->mWaitForPos->asOfTime();
301 # Aim for <= 1 second of waiting (being too picky can backfire)
302 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago + 1 );
304 if ( $i === false ) {
305 # Any server with less lag than it's 'max lag' param is preferable
306 $i = $this->getRandomNonLagged( $currentLoads, $domain );
308 if ( $i === false && count( $currentLoads ) != 0 ) {
309 # All replica DBs lagged. Switch to read-only mode
310 $this->replLogger->error( "All replica DBs lagged. Switch to read-only mode" );
311 $i = ArrayUtils::pickRandom( $currentLoads );
312 $laggedReplicaMode = true;
316 if ( $i === false ) {
317 # pickRandom() returned false
318 # This is permanent and means the configuration or the load monitor
319 # wants us to return false.
320 $this->connLogger->debug( __METHOD__ . ": pickRandom() returned false" );
322 return false;
325 $serverName = $this->getServerName( $i );
326 $this->connLogger->debug( __METHOD__ . ": Using reader #$i: $serverName..." );
328 $conn = $this->openConnection( $i, $domain );
329 if ( !$conn ) {
330 $this->connLogger->warning( __METHOD__ . ": Failed connecting to $i/$domain" );
331 unset( $nonErrorLoads[$i] );
332 unset( $currentLoads[$i] );
333 $i = false;
334 continue;
337 // Decrement reference counter, we are finished with this connection.
338 // It will be incremented for the caller later.
339 if ( $domain !== false ) {
340 $this->reuseConnection( $conn );
343 # Return this server
344 break;
347 # If all servers were down, quit now
348 if ( !count( $nonErrorLoads ) ) {
349 $this->connLogger->error( "All servers down" );
352 if ( $i !== false ) {
353 # Replica DB connection successful.
354 # Wait for the session master pos for a short time.
355 if ( $this->mWaitForPos && $i > 0 ) {
356 $this->doWait( $i );
358 if ( $this->mReadIndex <= 0 && $this->mLoads[$i] > 0 && $group === false ) {
359 $this->mReadIndex = $i;
360 # Record if the generic reader index is in "lagged replica DB" mode
361 if ( $laggedReplicaMode ) {
362 $this->laggedReplicaMode = true;
365 $serverName = $this->getServerName( $i );
366 $this->connLogger->debug(
367 __METHOD__ . ": using server $serverName for group '$group'" );
370 return $i;
373 public function waitFor( $pos ) {
374 $this->mWaitForPos = $pos;
375 $i = $this->mReadIndex;
377 if ( $i > 0 ) {
378 if ( !$this->doWait( $i ) ) {
379 $this->laggedReplicaMode = true;
385 * Set the master wait position and wait for a "generic" replica DB to catch up to it
387 * This can be used a faster proxy for waitForAll()
389 * @param DBMasterPos $pos
390 * @param int $timeout Max seconds to wait; default is mWaitTimeout
391 * @return bool Success (able to connect and no timeouts reached)
392 * @since 1.26
394 public function waitForOne( $pos, $timeout = null ) {
395 $this->mWaitForPos = $pos;
397 $i = $this->mReadIndex;
398 if ( $i <= 0 ) {
399 // Pick a generic replica DB if there isn't one yet
400 $readLoads = $this->mLoads;
401 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
402 $readLoads = array_filter( $readLoads ); // with non-zero load
403 $i = ArrayUtils::pickRandom( $readLoads );
406 if ( $i > 0 ) {
407 $ok = $this->doWait( $i, true, $timeout );
408 } else {
409 $ok = true; // no applicable loads
412 return $ok;
415 public function waitForAll( $pos, $timeout = null ) {
416 $this->mWaitForPos = $pos;
417 $serverCount = count( $this->mServers );
419 $ok = true;
420 for ( $i = 1; $i < $serverCount; $i++ ) {
421 if ( $this->mLoads[$i] > 0 ) {
422 $ok = $this->doWait( $i, true, $timeout ) && $ok;
426 return $ok;
429 public function getAnyOpenConnection( $i ) {
430 foreach ( $this->mConns as $connsByServer ) {
431 if ( !empty( $connsByServer[$i] ) ) {
432 return reset( $connsByServer[$i] );
436 return false;
440 * Wait for a given replica DB to catch up to the master pos stored in $this
441 * @param int $index Server index
442 * @param bool $open Check the server even if a new connection has to be made
443 * @param int $timeout Max seconds to wait; default is mWaitTimeout
444 * @return bool
446 protected function doWait( $index, $open = false, $timeout = null ) {
447 $close = false; // close the connection afterwards
449 // Check if we already know that the DB has reached this point
450 $server = $this->getServerName( $index );
451 $key = $this->srvCache->makeGlobalKey( __CLASS__, 'last-known-pos', $server );
452 /** @var DBMasterPos $knownReachedPos */
453 $knownReachedPos = $this->srvCache->get( $key );
454 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos ) ) {
455 $this->replLogger->debug( __METHOD__ .
456 ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
457 return true;
460 // Find a connection to wait on, creating one if needed and allowed
461 $conn = $this->getAnyOpenConnection( $index );
462 if ( !$conn ) {
463 if ( !$open ) {
464 $this->replLogger->debug( __METHOD__ . ": no connection open for $server" );
466 return false;
467 } else {
468 $conn = $this->openConnection( $index, '' );
469 if ( !$conn ) {
470 $this->replLogger->warning( __METHOD__ . ": failed to connect to $server" );
472 return false;
474 // Avoid connection spam in waitForAll() when connections
475 // are made just for the sake of doing this lag check.
476 $close = true;
480 $this->replLogger->info( __METHOD__ . ": Waiting for replica DB $server to catch up..." );
481 $timeout = $timeout ?: $this->mWaitTimeout;
482 $result = $conn->masterPosWait( $this->mWaitForPos, $timeout );
484 if ( $result == -1 || is_null( $result ) ) {
485 // Timed out waiting for replica DB, use master instead
486 $msg = __METHOD__ . ": Timed out waiting on $server pos {$this->mWaitForPos}";
487 $this->replLogger->warning( "$msg" );
488 $ok = false;
489 } else {
490 $this->replLogger->info( __METHOD__ . ": Done" );
491 $ok = true;
492 // Remember that the DB reached this point
493 $this->srvCache->set( $key, $this->mWaitForPos, BagOStuff::TTL_DAY );
496 if ( $close ) {
497 $this->closeConnection( $conn );
500 return $ok;
503 public function getConnection( $i, $groups = [], $domain = false ) {
504 if ( $i === null || $i === false ) {
505 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__ .
506 ' with invalid server index' );
509 if ( $domain === $this->localDomain ) {
510 $domain = false;
513 $groups = ( $groups === false || $groups === [] )
514 ? [ false ] // check one "group": the generic pool
515 : (array)$groups;
517 $masterOnly = ( $i == DB_MASTER || $i == $this->getWriterIndex() );
518 $oldConnsOpened = $this->connsOpened; // connections open now
520 if ( $i == DB_MASTER ) {
521 $i = $this->getWriterIndex();
522 } else {
523 # Try to find an available server in any the query groups (in order)
524 foreach ( $groups as $group ) {
525 $groupIndex = $this->getReaderIndex( $group, $domain );
526 if ( $groupIndex !== false ) {
527 $i = $groupIndex;
528 break;
533 # Operation-based index
534 if ( $i == DB_REPLICA ) {
535 $this->mLastError = 'Unknown error'; // reset error string
536 # Try the general server pool if $groups are unavailable.
537 $i = in_array( false, $groups, true )
538 ? false // don't bother with this if that is what was tried above
539 : $this->getReaderIndex( false, $domain );
540 # Couldn't find a working server in getReaderIndex()?
541 if ( $i === false ) {
542 $this->mLastError = 'No working replica DB server: ' . $this->mLastError;
544 return $this->reportConnectionError();
548 # Now we have an explicit index into the servers array
549 $conn = $this->openConnection( $i, $domain );
550 if ( !$conn ) {
551 return $this->reportConnectionError();
554 # Profile any new connections that happen
555 if ( $this->connsOpened > $oldConnsOpened ) {
556 $host = $conn->getServer();
557 $dbname = $conn->getDBname();
558 $this->trxProfiler->recordConnection( $host, $dbname, $masterOnly );
561 if ( $masterOnly ) {
562 # Make master-requested DB handles inherit any read-only mode setting
563 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
566 return $conn;
569 public function reuseConnection( $conn ) {
570 $serverIndex = $conn->getLBInfo( 'serverIndex' );
571 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
572 if ( $serverIndex === null || $refCount === null ) {
574 * This can happen in code like:
575 * foreach ( $dbs as $db ) {
576 * $conn = $lb->getConnection( DB_REPLICA, [], $db );
577 * ...
578 * $lb->reuseConnection( $conn );
580 * When a connection to the local DB is opened in this way, reuseConnection()
581 * should be ignored
583 return;
586 $dbName = $conn->getDBname();
587 $prefix = $conn->tablePrefix();
588 if ( strval( $prefix ) !== '' ) {
589 $domain = "$dbName-$prefix";
590 } else {
591 $domain = $dbName;
593 if ( $this->mConns['foreignUsed'][$serverIndex][$domain] !== $conn ) {
594 throw new InvalidArgumentException( __METHOD__ . ": connection not found, has " .
595 "the connection been freed already?" );
597 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
598 if ( $refCount <= 0 ) {
599 $this->mConns['foreignFree'][$serverIndex][$domain] = $conn;
600 unset( $this->mConns['foreignUsed'][$serverIndex][$domain] );
601 $this->connLogger->debug( __METHOD__ . ": freed connection $serverIndex/$domain" );
602 } else {
603 $this->connLogger->debug( __METHOD__ .
604 ": reference count for $serverIndex/$domain reduced to $refCount" );
609 * Get a database connection handle reference
611 * The handle's methods wrap simply wrap those of a IDatabase handle
613 * @see LoadBalancer::getConnection() for parameter information
615 * @param int $db
616 * @param array|string|bool $groups Query group(s), or false for the generic reader
617 * @param string|bool $domain Domain ID, or false for the current domain
618 * @return DBConnRef
619 * @since 1.22
621 public function getConnectionRef( $db, $groups = [], $domain = false ) {
622 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
626 * Get a database connection handle reference without connecting yet
628 * The handle's methods wrap simply wrap those of a IDatabase handle
630 * @see LoadBalancer::getConnection() for parameter information
632 * @param int $db
633 * @param array|string|bool $groups Query group(s), or false for the generic reader
634 * @param string|bool $domain Domain ID, or false for the current domain
635 * @return DBConnRef
636 * @since 1.22
638 public function getLazyConnectionRef( $db, $groups = [], $domain = false ) {
639 $domain = ( $domain !== false ) ? $domain : $this->localDomain;
641 return new DBConnRef( $this, [ $db, $groups, $domain ] );
644 public function openConnection( $i, $domain = false ) {
645 if ( $domain !== false ) {
646 $conn = $this->openForeignConnection( $i, $domain );
647 } elseif ( isset( $this->mConns['local'][$i][0] ) ) {
648 $conn = $this->mConns['local'][$i][0];
649 } else {
650 $server = $this->mServers[$i];
651 $server['serverIndex'] = $i;
652 $conn = $this->reallyOpenConnection( $server, false );
653 $serverName = $this->getServerName( $i );
654 if ( $conn->isOpen() ) {
655 $this->connLogger->debug( "Connected to database $i at '$serverName'." );
656 $this->mConns['local'][$i][0] = $conn;
657 } else {
658 $this->connLogger->warning( "Failed to connect to database $i at '$serverName'." );
659 $this->mErrorConnection = $conn;
660 $conn = false;
664 if ( $conn && !$conn->isOpen() ) {
665 // Connection was made but later unrecoverably lost for some reason.
666 // Do not return a handle that will just throw exceptions on use,
667 // but let the calling code (e.g. getReaderIndex) try another server.
668 // See DatabaseMyslBase::ping() for how this can happen.
669 $this->mErrorConnection = $conn;
670 $conn = false;
673 return $conn;
677 * Open a connection to a foreign DB, or return one if it is already open.
679 * Increments a reference count on the returned connection which locks the
680 * connection to the requested domain. This reference count can be
681 * decremented by calling reuseConnection().
683 * If a connection is open to the appropriate server already, but with the wrong
684 * database, it will be switched to the right database and returned, as long as
685 * it has been freed first with reuseConnection().
687 * On error, returns false, and the connection which caused the
688 * error will be available via $this->mErrorConnection.
690 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
692 * @param int $i Server index
693 * @param string $domain Domain ID to open
694 * @return IDatabase
696 private function openForeignConnection( $i, $domain ) {
697 list( $dbName, $prefix ) = explode( '-', $domain, 2 ) + [ '', '' ];
699 if ( isset( $this->mConns['foreignUsed'][$i][$domain] ) ) {
700 // Reuse an already-used connection
701 $conn = $this->mConns['foreignUsed'][$i][$domain];
702 $this->connLogger->debug( __METHOD__ . ": reusing connection $i/$domain" );
703 } elseif ( isset( $this->mConns['foreignFree'][$i][$domain] ) ) {
704 // Reuse a free connection for the same domain
705 $conn = $this->mConns['foreignFree'][$i][$domain];
706 unset( $this->mConns['foreignFree'][$i][$domain] );
707 $this->mConns['foreignUsed'][$i][$domain] = $conn;
708 $this->connLogger->debug( __METHOD__ . ": reusing free connection $i/$domain" );
709 } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
710 // Reuse a connection from another domain
711 $conn = reset( $this->mConns['foreignFree'][$i] );
712 $oldDomain = key( $this->mConns['foreignFree'][$i] );
714 // The empty string as a DB name means "don't care".
715 // DatabaseMysqlBase::open() already handle this on connection.
716 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
717 $this->mLastError = "Error selecting database $dbName on server " .
718 $conn->getServer() . " from client host {$this->host}";
719 $this->mErrorConnection = $conn;
720 $conn = false;
721 } else {
722 $conn->tablePrefix( $prefix );
723 unset( $this->mConns['foreignFree'][$i][$oldDomain] );
724 $this->mConns['foreignUsed'][$i][$domain] = $conn;
725 $this->connLogger->debug( __METHOD__ .
726 ": reusing free connection from $oldDomain for $domain" );
728 } else {
729 // Open a new connection
730 $server = $this->mServers[$i];
731 $server['serverIndex'] = $i;
732 $server['foreignPoolRefCount'] = 0;
733 $server['foreign'] = true;
734 $conn = $this->reallyOpenConnection( $server, $dbName );
735 if ( !$conn->isOpen() ) {
736 $this->connLogger->warning( __METHOD__ . ": connection error for $i/$domain" );
737 $this->mErrorConnection = $conn;
738 $conn = false;
739 } else {
740 $conn->tablePrefix( $prefix );
741 $this->mConns['foreignUsed'][$i][$domain] = $conn;
742 $this->connLogger->debug( __METHOD__ . ": opened new connection for $i/$domain" );
746 // Increment reference count
747 if ( $conn ) {
748 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
749 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
752 return $conn;
756 * Test if the specified index represents an open connection
758 * @param int $index Server index
759 * @access private
760 * @return bool
762 private function isOpen( $index ) {
763 if ( !is_integer( $index ) ) {
764 return false;
767 return (bool)$this->getAnyOpenConnection( $index );
771 * Really opens a connection. Uncached.
772 * Returns a Database object whether or not the connection was successful.
773 * @access private
775 * @param array $server
776 * @param bool $dbNameOverride
777 * @return IDatabase
778 * @throws DBAccessError
779 * @throws InvalidArgumentException
781 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
782 if ( $this->disabled ) {
783 throw new DBAccessError();
786 if ( !is_array( $server ) ) {
787 throw new InvalidArgumentException(
788 'You must update your load-balancing configuration. ' .
789 'See DefaultSettings.php entry for $wgDBservers.' );
792 if ( $dbNameOverride !== false ) {
793 $server['dbname'] = $dbNameOverride;
796 // Let the handle know what the cluster master is (e.g. "db1052")
797 $masterName = $this->getServerName( $this->getWriterIndex() );
798 $server['clusterMasterHost'] = $masterName;
800 // Log when many connection are made on requests
801 if ( ++$this->connsOpened >= self::CONN_HELD_WARN_THRESHOLD ) {
802 $this->perfLogger->warning( __METHOD__ . ": " .
803 "{$this->connsOpened}+ connections made (master=$masterName)" );
806 $server['srvCache'] = $this->srvCache;
807 // Set loggers
808 $server['connLogger'] = $this->connLogger;
809 $server['queryLogger'] = $this->queryLogger;
810 $server['trxProfiler'] = $this->trxProfiler;
812 // Create a live connection object
813 try {
814 $db = DatabaseBase::factory( $server['type'], $server );
815 } catch ( DBConnectionError $e ) {
816 // FIXME: This is probably the ugliest thing I have ever done to
817 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
818 $db = $e->db;
821 $db->setLBInfo( $server );
822 $db->setLazyMasterHandle(
823 $this->getLazyConnectionRef( DB_MASTER, [], $db->getWikiID() )
826 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
827 if ( $this->trxRoundId !== false ) {
828 $this->applyTransactionRoundFlags( $db );
830 foreach ( $this->trxRecurringCallbacks as $name => $callback ) {
831 $db->setTransactionListener( $name, $callback );
835 return $db;
839 * @throws DBConnectionError
840 * @return bool
842 private function reportConnectionError() {
843 $conn = $this->mErrorConnection; // The connection which caused the error
844 $context = [
845 'method' => __METHOD__,
846 'last_error' => $this->mLastError,
849 if ( !is_object( $conn ) ) {
850 // No last connection, probably due to all servers being too busy
851 $this->connLogger->error(
852 "LB failure with no last connection. Connection error: {last_error}",
853 $context
856 // If all servers were busy, mLastError will contain something sensible
857 throw new DBConnectionError( null, $this->mLastError );
858 } else {
859 $context['db_server'] = $conn->getProperty( 'mServer' );
860 $this->connLogger->warning(
861 "Connection error: {last_error} ({db_server})",
862 $context
865 // throws DBConnectionError
866 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
869 return false; /* not reached */
872 public function getWriterIndex() {
873 return 0;
876 public function haveIndex( $i ) {
877 return array_key_exists( $i, $this->mServers );
880 public function isNonZeroLoad( $i ) {
881 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
884 public function getServerCount() {
885 return count( $this->mServers );
888 public function getServerName( $i ) {
889 if ( isset( $this->mServers[$i]['hostName'] ) ) {
890 $name = $this->mServers[$i]['hostName'];
891 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
892 $name = $this->mServers[$i]['host'];
893 } else {
894 $name = '';
897 return ( $name != '' ) ? $name : 'localhost';
900 public function getServerInfo( $i ) {
901 if ( isset( $this->mServers[$i] ) ) {
902 return $this->mServers[$i];
903 } else {
904 return false;
908 public function setServerInfo( $i, array $serverInfo ) {
909 $this->mServers[$i] = $serverInfo;
912 public function getMasterPos() {
913 # If this entire request was served from a replica DB without opening a connection to the
914 # master (however unlikely that may be), then we can fetch the position from the replica DB.
915 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
916 if ( !$masterConn ) {
917 $serverCount = count( $this->mServers );
918 for ( $i = 1; $i < $serverCount; $i++ ) {
919 $conn = $this->getAnyOpenConnection( $i );
920 if ( $conn ) {
921 return $conn->getSlavePos();
924 } else {
925 return $masterConn->getMasterPos();
928 return false;
932 * Disable this load balancer. All connections are closed, and any attempt to
933 * open a new connection will result in a DBAccessError.
935 * @since 1.27
937 public function disable() {
938 $this->closeAll();
939 $this->disabled = true;
942 public function closeAll() {
943 $this->forEachOpenConnection( function ( IDatabase $conn ) {
944 $conn->close();
945 } );
947 $this->mConns = [
948 'local' => [],
949 'foreignFree' => [],
950 'foreignUsed' => [],
952 $this->connsOpened = 0;
955 public function closeConnection( IDatabase $conn ) {
956 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
957 foreach ( $this->mConns as $type => $connsByServer ) {
958 if ( !isset( $connsByServer[$serverIndex] ) ) {
959 continue;
962 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
963 if ( $conn === $trackedConn ) {
964 unset( $this->mConns[$type][$serverIndex][$i] );
965 --$this->connsOpened;
966 break 2;
971 $conn->close();
974 public function commitAll( $fname = __METHOD__ ) {
975 $failures = [];
977 $restore = ( $this->trxRoundId !== false );
978 $this->trxRoundId = false;
979 $this->forEachOpenConnection(
980 function ( IDatabase $conn ) use ( $fname, $restore, &$failures ) {
981 try {
982 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
983 } catch ( DBError $e ) {
984 call_user_func( $this->errorLogger, $e );
985 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
987 if ( $restore && $conn->getLBInfo( 'master' ) ) {
988 $this->undoTransactionRoundFlags( $conn );
993 if ( $failures ) {
994 throw new DBExpectedError(
995 null,
996 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1002 * Perform all pre-commit callbacks that remain part of the atomic transactions
1003 * and disable any post-commit callbacks until runMasterPostTrxCallbacks()
1004 * @since 1.28
1006 public function finalizeMasterChanges() {
1007 $this->forEachOpenMasterConnection( function ( DatabaseBase $conn ) {
1008 // Any error should cause all DB transactions to be rolled back together
1009 $conn->setTrxEndCallbackSuppression( false );
1010 $conn->runOnTransactionPreCommitCallbacks();
1011 // Defer post-commit callbacks until COMMIT finishes for all DBs
1012 $conn->setTrxEndCallbackSuppression( true );
1013 } );
1017 * Perform all pre-commit checks for things like replication safety
1018 * @param array $options Includes:
1019 * - maxWriteDuration : max write query duration time in seconds
1020 * @throws DBTransactionError
1021 * @since 1.28
1023 public function approveMasterChanges( array $options ) {
1024 $limit = isset( $options['maxWriteDuration'] ) ? $options['maxWriteDuration'] : 0;
1025 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $limit ) {
1026 // If atomic sections or explicit transactions are still open, some caller must have
1027 // caught an exception but failed to properly rollback any changes. Detect that and
1028 // throw and error (causing rollback).
1029 if ( $conn->explicitTrxActive() ) {
1030 throw new DBTransactionError(
1031 $conn,
1032 "Explicit transaction still active. A caller may have caught an error."
1035 // Assert that the time to replicate the transaction will be sane.
1036 // If this fails, then all DB transactions will be rollback back together.
1037 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY );
1038 if ( $limit > 0 && $time > $limit ) {
1039 throw new DBTransactionSizeError(
1040 $conn,
1041 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1042 [ $time, $limit ]
1045 // If a connection sits idle while slow queries execute on another, that connection
1046 // may end up dropped before the commit round is reached. Ping servers to detect this.
1047 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1048 throw new DBTransactionError(
1049 $conn,
1050 "A connection to the {$conn->getDBname()} database was lost before commit."
1053 } );
1057 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
1059 * The DBO_TRX setting will be reverted to the default in each of these methods:
1060 * - commitMasterChanges()
1061 * - rollbackMasterChanges()
1062 * - commitAll()
1063 * This allows for custom transaction rounds from any outer transaction scope.
1065 * @param string $fname
1066 * @throws DBExpectedError
1067 * @since 1.28
1069 public function beginMasterChanges( $fname = __METHOD__ ) {
1070 if ( $this->trxRoundId !== false ) {
1071 throw new DBTransactionError(
1072 null,
1073 "$fname: Transaction round '{$this->trxRoundId}' already started."
1076 $this->trxRoundId = $fname;
1078 $failures = [];
1079 $this->forEachOpenMasterConnection(
1080 function ( DatabaseBase $conn ) use ( $fname, &$failures ) {
1081 $conn->setTrxEndCallbackSuppression( true );
1082 try {
1083 $conn->flushSnapshot( $fname );
1084 } catch ( DBError $e ) {
1085 call_user_func( $this->errorLogger, $e );
1086 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1088 $conn->setTrxEndCallbackSuppression( false );
1089 $this->applyTransactionRoundFlags( $conn );
1093 if ( $failures ) {
1094 throw new DBExpectedError(
1095 null,
1096 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1101 public function commitMasterChanges( $fname = __METHOD__ ) {
1102 $failures = [];
1104 $restore = ( $this->trxRoundId !== false );
1105 $this->trxRoundId = false;
1106 $this->forEachOpenMasterConnection(
1107 function ( IDatabase $conn ) use ( $fname, $restore, &$failures ) {
1108 try {
1109 if ( $conn->writesOrCallbacksPending() ) {
1110 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1111 } elseif ( $restore ) {
1112 $conn->flushSnapshot( $fname );
1114 } catch ( DBError $e ) {
1115 call_user_func( $this->errorLogger, $e );
1116 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1118 if ( $restore ) {
1119 $this->undoTransactionRoundFlags( $conn );
1124 if ( $failures ) {
1125 throw new DBExpectedError(
1126 null,
1127 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1133 * Issue all pending post-COMMIT/ROLLBACK callbacks
1134 * @param integer $type IDatabase::TRIGGER_* constant
1135 * @return Exception|null The first exception or null if there were none
1136 * @since 1.28
1138 public function runMasterPostTrxCallbacks( $type ) {
1139 $e = null; // first exception
1140 $this->forEachOpenMasterConnection( function ( DatabaseBase $conn ) use ( $type, &$e ) {
1141 $conn->setTrxEndCallbackSuppression( false );
1142 if ( $conn->writesOrCallbacksPending() ) {
1143 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1144 // (which finished its callbacks already). Warn and recover in this case. Let the
1145 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1146 $this->queryLogger->error( __METHOD__ . ": found writes/callbacks pending." );
1147 return;
1148 } elseif ( $conn->trxLevel() ) {
1149 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1150 // thus leaving an implicit read-only transaction open at this point. It
1151 // also happens if onTransactionIdle() callbacks leave implicit transactions
1152 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1153 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1154 return;
1156 try {
1157 $conn->runOnTransactionIdleCallbacks( $type );
1158 } catch ( Exception $ex ) {
1159 $e = $e ?: $ex;
1161 try {
1162 $conn->runTransactionListenerCallbacks( $type );
1163 } catch ( Exception $ex ) {
1164 $e = $e ?: $ex;
1166 } );
1168 return $e;
1172 * Issue ROLLBACK only on master, only if queries were done on connection
1173 * @param string $fname Caller name
1174 * @throws DBExpectedError
1175 * @since 1.23
1177 public function rollbackMasterChanges( $fname = __METHOD__ ) {
1178 $restore = ( $this->trxRoundId !== false );
1179 $this->trxRoundId = false;
1180 $this->forEachOpenMasterConnection(
1181 function ( IDatabase $conn ) use ( $fname, $restore ) {
1182 if ( $conn->writesOrCallbacksPending() ) {
1183 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS );
1185 if ( $restore ) {
1186 $this->undoTransactionRoundFlags( $conn );
1193 * Suppress all pending post-COMMIT/ROLLBACK callbacks
1194 * @return Exception|null The first exception or null if there were none
1195 * @since 1.28
1197 public function suppressTransactionEndCallbacks() {
1198 $this->forEachOpenMasterConnection( function ( DatabaseBase $conn ) {
1199 $conn->setTrxEndCallbackSuppression( true );
1200 } );
1204 * @param IDatabase $conn
1206 private function applyTransactionRoundFlags( IDatabase $conn ) {
1207 if ( $conn->getFlag( DBO_DEFAULT ) ) {
1208 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1209 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1210 $conn->setFlag( DBO_TRX, $conn::REMEMBER_PRIOR );
1211 // If config has explicitly requested DBO_TRX be either on or off by not
1212 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1213 // for things like blob stores (ExternalStore) which want auto-commit mode.
1218 * @param IDatabase $conn
1220 private function undoTransactionRoundFlags( IDatabase $conn ) {
1221 if ( $conn->getFlag( DBO_DEFAULT ) ) {
1222 $conn->restoreFlags( $conn::RESTORE_PRIOR );
1227 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
1229 * @param string $fname Caller name
1230 * @since 1.28
1232 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
1233 $this->forEachOpenReplicaConnection( function ( IDatabase $conn ) {
1234 $conn->flushSnapshot( __METHOD__ );
1235 } );
1239 * @return bool Whether a master connection is already open
1240 * @since 1.24
1242 public function hasMasterConnection() {
1243 return $this->isOpen( $this->getWriterIndex() );
1247 * Determine if there are pending changes in a transaction by this thread
1248 * @since 1.23
1249 * @return bool
1251 public function hasMasterChanges() {
1252 $pending = 0;
1253 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$pending ) {
1254 $pending |= $conn->writesOrCallbacksPending();
1255 } );
1257 return (bool)$pending;
1261 * Get the timestamp of the latest write query done by this thread
1262 * @since 1.25
1263 * @return float|bool UNIX timestamp or false
1265 public function lastMasterChangeTimestamp() {
1266 $lastTime = false;
1267 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$lastTime ) {
1268 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1269 } );
1271 return $lastTime;
1275 * Check if this load balancer object had any recent or still
1276 * pending writes issued against it by this PHP thread
1278 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
1279 * @return bool
1280 * @since 1.25
1282 public function hasOrMadeRecentMasterChanges( $age = null ) {
1283 $age = ( $age === null ) ? $this->mWaitTimeout : $age;
1285 return ( $this->hasMasterChanges()
1286 || $this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1290 * Get the list of callers that have pending master changes
1292 * @return string[] List of method names
1293 * @since 1.27
1295 public function pendingMasterChangeCallers() {
1296 $fnames = [];
1297 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$fnames ) {
1298 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1299 } );
1301 return $fnames;
1304 public function getLaggedReplicaMode( $domain = false ) {
1305 // No-op if there is only one DB (also avoids recursion)
1306 if ( !$this->laggedReplicaMode && $this->getServerCount() > 1 ) {
1307 try {
1308 // See if laggedReplicaMode gets set
1309 $conn = $this->getConnection( DB_REPLICA, false, $domain );
1310 $this->reuseConnection( $conn );
1311 } catch ( DBConnectionError $e ) {
1312 // Avoid expensive re-connect attempts and failures
1313 $this->allReplicasDownMode = true;
1314 $this->laggedReplicaMode = true;
1318 return $this->laggedReplicaMode;
1322 * @param bool $domain
1323 * @return bool
1324 * @deprecated 1.28; use getLaggedReplicaMode()
1326 public function getLaggedSlaveMode( $domain = false ) {
1327 return $this->getLaggedReplicaMode( $domain );
1331 * @note This method will never cause a new DB connection
1332 * @return bool Whether any generic connection used for reads was highly "lagged"
1333 * @since 1.28
1335 public function laggedReplicaUsed() {
1336 return $this->laggedReplicaMode;
1340 * @return bool
1341 * @since 1.27
1342 * @deprecated Since 1.28; use laggedReplicaUsed()
1344 public function laggedSlaveUsed() {
1345 return $this->laggedReplicaUsed();
1349 * @note This method may trigger a DB connection if not yet done
1350 * @param string|bool $domain Domain ID, or false for the current domain
1351 * @param IDatabase|null DB master connection; used to avoid loops [optional]
1352 * @return string|bool Reason the master is read-only or false if it is not
1353 * @since 1.27
1355 public function getReadOnlyReason( $domain = false, IDatabase $conn = null ) {
1356 if ( $this->readOnlyReason !== false ) {
1357 return $this->readOnlyReason;
1358 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1359 if ( $this->allReplicasDownMode ) {
1360 return 'The database has been automatically locked ' .
1361 'until the replica database servers become available';
1362 } else {
1363 return 'The database has been automatically locked ' .
1364 'while the replica database servers catch up to the master.';
1366 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1367 return 'The database master is running in read-only mode.';
1370 return false;
1374 * @param string $domain Domain ID, or false for the current domain
1375 * @param IDatabase|null DB master connectionl used to avoid loops [optional]
1376 * @return bool
1378 private function masterRunningReadOnly( $domain, IDatabase $conn = null ) {
1379 $cache = $this->wanCache;
1380 $masterServer = $this->getServerName( $this->getWriterIndex() );
1382 return (bool)$cache->getWithSetCallback(
1383 $cache->makeGlobalKey( __CLASS__, 'server-read-only', $masterServer ),
1384 self::TTL_CACHE_READONLY,
1385 function () use ( $domain, $conn ) {
1386 $this->trxProfiler->setSilenced( true );
1387 try {
1388 $dbw = $conn ?: $this->getConnection( DB_MASTER, [], $domain );
1389 $readOnly = (int)$dbw->serverIsReadOnly();
1390 } catch ( DBError $e ) {
1391 $readOnly = 0;
1393 $this->trxProfiler->setSilenced( false );
1394 return $readOnly;
1396 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'busyValue' => 0 ]
1400 public function allowLagged( $mode = null ) {
1401 if ( $mode === null ) {
1402 return $this->mAllowLagged;
1404 $this->mAllowLagged = $mode;
1406 return $this->mAllowLagged;
1409 public function pingAll() {
1410 $success = true;
1411 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$success ) {
1412 if ( !$conn->ping() ) {
1413 $success = false;
1415 } );
1417 return $success;
1420 public function forEachOpenConnection( $callback, array $params = [] ) {
1421 foreach ( $this->mConns as $connsByServer ) {
1422 foreach ( $connsByServer as $serverConns ) {
1423 foreach ( $serverConns as $conn ) {
1424 $mergedParams = array_merge( [ $conn ], $params );
1425 call_user_func_array( $callback, $mergedParams );
1432 * Call a function with each open connection object to a master
1433 * @param callable $callback
1434 * @param array $params
1435 * @since 1.28
1437 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1438 $masterIndex = $this->getWriterIndex();
1439 foreach ( $this->mConns as $connsByServer ) {
1440 if ( isset( $connsByServer[$masterIndex] ) ) {
1441 /** @var IDatabase $conn */
1442 foreach ( $connsByServer[$masterIndex] as $conn ) {
1443 $mergedParams = array_merge( [ $conn ], $params );
1444 call_user_func_array( $callback, $mergedParams );
1451 * Call a function with each open replica DB connection object
1452 * @param callable $callback
1453 * @param array $params
1454 * @since 1.28
1456 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1457 foreach ( $this->mConns as $connsByServer ) {
1458 foreach ( $connsByServer as $i => $serverConns ) {
1459 if ( $i === $this->getWriterIndex() ) {
1460 continue; // skip master
1462 foreach ( $serverConns as $conn ) {
1463 $mergedParams = array_merge( [ $conn ], $params );
1464 call_user_func_array( $callback, $mergedParams );
1470 public function getMaxLag( $domain = false ) {
1471 $maxLag = -1;
1472 $host = '';
1473 $maxIndex = 0;
1475 if ( $this->getServerCount() <= 1 ) {
1476 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1479 $lagTimes = $this->getLagTimes( $domain );
1480 foreach ( $lagTimes as $i => $lag ) {
1481 if ( $this->mLoads[$i] > 0 && $lag > $maxLag ) {
1482 $maxLag = $lag;
1483 $host = $this->mServers[$i]['host'];
1484 $maxIndex = $i;
1488 return [ $host, $maxLag, $maxIndex ];
1491 public function getLagTimes( $domain = false ) {
1492 if ( $this->getServerCount() <= 1 ) {
1493 return [ 0 => 0 ]; // no replication = no lag
1496 # Send the request to the load monitor
1497 return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $domain );
1500 public function safeGetLag( IDatabase $conn ) {
1501 if ( $this->getServerCount() == 1 ) {
1502 return 0;
1503 } else {
1504 return $conn->getLag();
1509 * Wait for a replica DB to reach a specified master position
1511 * This will connect to the master to get an accurate position if $pos is not given
1513 * @param IDatabase $conn Replica DB
1514 * @param DBMasterPos|bool $pos Master position; default: current position
1515 * @param integer $timeout Timeout in seconds
1516 * @return bool Success
1517 * @since 1.27
1519 public function safeWaitForMasterPos( IDatabase $conn, $pos = false, $timeout = 10 ) {
1520 if ( $this->getServerCount() == 1 || !$conn->getLBInfo( 'replica' ) ) {
1521 return true; // server is not a replica DB
1524 $pos = $pos ?: $this->getConnection( DB_MASTER )->getMasterPos();
1525 if ( !( $pos instanceof DBMasterPos ) ) {
1526 return false; // something is misconfigured
1529 $result = $conn->masterPosWait( $pos, $timeout );
1530 if ( $result == -1 || is_null( $result ) ) {
1531 $msg = __METHOD__ . ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1532 $this->replLogger->warning( "$msg" );
1533 $ok = false;
1534 } else {
1535 $this->replLogger->info( __METHOD__ . ": Done" );
1536 $ok = true;
1539 return $ok;
1543 * Clear the cache for slag lag delay times
1545 * This is only used for testing
1546 * @since 1.26
1548 public function clearLagTimeCache() {
1549 $this->getLoadMonitor()->clearCaches();
1553 * Set a callback via IDatabase::setTransactionListener() on
1554 * all current and future master connections of this load balancer
1556 * @param string $name Callback name
1557 * @param callable|null $callback
1558 * @since 1.28
1560 public function setTransactionListener( $name, callable $callback = null ) {
1561 if ( $callback ) {
1562 $this->trxRecurringCallbacks[$name] = $callback;
1563 } else {
1564 unset( $this->trxRecurringCallbacks[$name] );
1566 $this->forEachOpenMasterConnection(
1567 function ( IDatabase $conn ) use ( $name, $callback ) {
1568 $conn->setTransactionListener( $name, $callback );
1574 * Set a new table prefix for the existing local domain ID for testing
1576 * @param string $prefix
1577 * @since 1.28
1579 public function setDomainPrefix( $prefix ) {
1580 list( $dbName, ) = explode( '-', $this->localDomain, 2 );
1582 $this->localDomain = "{$dbName}-{$prefix}";