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
22 namespace Wikimedia\Rdbms
;
24 use Psr\Log\LoggerInterface
;
25 use Psr\Log\NullLogger
;
26 use Wikimedia\ScopedCallback
;
31 use UnexpectedValueException
;
32 use InvalidArgumentException
;
37 * Database connection, tracking, load balancing, and transaction manager for a cluster
41 class LoadBalancer
implements ILoadBalancer
{
42 /** @var ILoadMonitor */
44 /** @var callable|null Callback to run before the first connection attempt */
45 private $chronologyCallback;
48 /** @var WANObjectCache */
50 /** @var mixed Class name or object With profileIn/profileOut methods */
52 /** @var TransactionProfiler */
54 /** @var LoggerInterface */
56 /** @var LoggerInterface */
58 /** @var LoggerInterface */
60 /** @var LoggerInterface */
62 /** @var callable Exception logger */
64 /** @var callable Deprecation logger */
65 private $deprecationLogger;
67 /** @var DatabaseDomain Local DB domain ID and default for selectDB() calls */
70 /** @var Database[][][] Map of (connection category => server index => IDatabase[]) */
73 /** @var array[] Map of (server index => server config array) */
75 /** @var float[] Map of (server index => weight) */
76 private $genericLoads;
77 /** @var array[] Map of (group => server index => weight) */
79 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
81 /** @var int Seconds to spend waiting on replica DB lag to resolve */
83 /** @var array The LoadMonitor configuration */
84 private $loadMonitorConfig;
85 /** @var string Alternate local DB domain instead of DatabaseDomain::getId() */
86 private $localDomainIdAlias;
90 /** @var string Current server name */
92 /** @var bool Whether this PHP instance is for a CLI script */
94 /** @var string Agent name for query profiling */
97 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
98 private $tableAliases = [];
99 /** @var string[] Map of (index alias => index) */
100 private $indexAliases = [];
101 /** @var array[] Map of (name => callable) */
102 private $trxRecurringCallbacks = [];
104 /** @var Database DB connection object that caused a problem */
105 private $errorConnection;
106 /** @var int The generic (not query grouped) replica DB index */
107 private $genericReadIndex = -1;
108 /** @var int[] The group replica DB indexes keyed by group */
109 private $readIndexByGroup = [];
110 /** @var bool|DBMasterPos Replication sync position or false if not set */
112 /** @var bool Whether the generic reader fell back to a lagged replica DB */
113 private $laggedReplicaMode = false;
114 /** @var bool Whether the generic reader fell back to a lagged replica DB */
115 private $allReplicasDownMode = false;
116 /** @var string The last DB selection or connection error */
117 private $lastError = 'Unknown error';
118 /** @var string|bool Reason the LB is read-only or false if not */
119 private $readOnlyReason = false;
120 /** @var int Total number of new connections ever made with this instance */
121 private $connectionCounter = 0;
123 private $disabled = false;
124 /** @var bool Whether any connection has been attempted yet */
125 private $connectionAttempted = false;
127 /** @var int|null An integer ID of the managing LBFactory instance or null */
129 /** @var string|bool String if a requested DBO_TRX transaction round is active */
130 private $trxRoundId = false;
131 /** @var string Stage of the current transaction round in the transaction round life-cycle */
132 private $trxRoundStage = self
::ROUND_CURSORY
;
134 /** @var string|null */
135 private $defaultGroup = null;
137 /** @var int Warn when this many connection are held */
138 const CONN_HELD_WARN_THRESHOLD
= 10;
140 /** @var int Default 'maxLag' when unspecified */
141 const MAX_LAG_DEFAULT
= 6;
142 /** @var int Default 'waitTimeout' when unspecified */
143 const MAX_WAIT_DEFAULT
= 10;
144 /** @var int Seconds to cache master server read-only status */
145 const TTL_CACHE_READONLY
= 5;
147 const KEY_LOCAL
= 'local';
148 const KEY_FOREIGN_FREE
= 'foreignFree';
149 const KEY_FOREIGN_INUSE
= 'foreignInUse';
151 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
152 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
153 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
155 /** @var string Transaction round, explicit or implicit, has not finished writing */
156 const ROUND_CURSORY
= 'cursory';
157 /** @var string Transaction round writes are complete and ready for pre-commit checks */
158 const ROUND_FINALIZED
= 'finalized';
159 /** @var string Transaction round passed final pre-commit checks */
160 const ROUND_APPROVED
= 'approved';
161 /** @var string Transaction round was committed and post-commit callbacks must be run */
162 const ROUND_COMMIT_CALLBACKS
= 'commit-callbacks';
163 /** @var string Transaction round was rolled back and post-rollback callbacks must be run */
164 const ROUND_ROLLBACK_CALLBACKS
= 'rollback-callbacks';
165 /** @var string Transaction round encountered an error */
166 const ROUND_ERROR
= 'error';
168 public function __construct( array $params ) {
169 if ( !isset( $params['servers'] ) ||
!count( $params['servers'] ) ) {
170 throw new InvalidArgumentException( 'Missing or empty "servers" parameter' );
175 $this->genericLoads
= [];
176 foreach ( $params['servers'] as $i => $server ) {
177 if ( ++
$listKey !== $i ) {
178 throw new UnexpectedValueException( 'List expected for "servers" parameter' );
181 $server['master'] = true;
183 $server['replica'] = true;
185 $this->servers
[$i] = $server;
187 $this->genericLoads
[$i] = $server['load'];
188 if ( isset( $server['groupLoads'] ) ) {
189 foreach ( $server['groupLoads'] as $group => $ratio ) {
190 $this->groupLoads
[$group][$i] = $ratio;
195 $localDomain = isset( $params['localDomain'] )
196 ? DatabaseDomain
::newFromId( $params['localDomain'] )
197 : DatabaseDomain
::newUnspecified();
198 $this->setLocalDomain( $localDomain );
200 $this->waitTimeout
= $params['waitTimeout'] ?? self
::MAX_WAIT_DEFAULT
;
202 $this->conns
= self
::newTrackedConnectionsArray();
203 $this->waitForPos
= false;
204 $this->allowLagged
= false;
206 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
207 $this->readOnlyReason
= $params['readOnlyReason'];
210 $this->maxLag
= $params['maxLag'] ?? self
::MAX_LAG_DEFAULT
;
212 $this->loadMonitorConfig
= $params['loadMonitor'] ??
[ 'class' => 'LoadMonitorNull' ];
213 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
215 $this->srvCache
= $params['srvCache'] ??
new EmptyBagOStuff();
216 $this->wanCache
= $params['wanCache'] ?? WANObjectCache
::newEmpty();
217 $this->profiler
= $params['profiler'] ??
null;
218 $this->trxProfiler
= $params['trxProfiler'] ??
new TransactionProfiler();
220 $this->errorLogger
= $params['errorLogger'] ??
function ( Exception
$e ) {
221 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
223 $this->deprecationLogger
= $params['deprecationLogger'] ??
function ( $msg ) {
224 trigger_error( $msg, E_USER_DEPRECATED
);
227 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
228 $this->$key = $params[$key] ??
new NullLogger();
231 $this->hostname
= $params['hostname'] ??
( gethostname() ?
: 'unknown' );
232 $this->cliMode
= $params['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
233 $this->agent
= $params['agent'] ??
'';
235 if ( isset( $params['chronologyCallback'] ) ) {
236 $this->chronologyCallback
= $params['chronologyCallback'];
239 if ( isset( $params['roundStage'] ) ) {
240 if ( $params['roundStage'] === self
::STAGE_POSTCOMMIT_CALLBACKS
) {
241 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
242 } elseif ( $params['roundStage'] === self
::STAGE_POSTROLLBACK_CALLBACKS
) {
243 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
247 $this->defaultGroup
= $params['defaultGroup'] ??
null;
248 $this->ownerId
= $params['ownerId'] ??
null;
251 private static function newTrackedConnectionsArray() {
253 // Connection were transaction rounds may be applied
254 self
::KEY_LOCAL
=> [],
255 self
::KEY_FOREIGN_INUSE
=> [],
256 self
::KEY_FOREIGN_FREE
=> [],
257 // Auto-committing counterpart connections that ignore transaction rounds
258 self
::KEY_LOCAL_NOROUND
=> [],
259 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
260 self
::KEY_FOREIGN_FREE_NOROUND
=> []
264 public function getLocalDomainID() {
265 return $this->localDomain
->getId();
268 public function resolveDomainID( $domain ) {
269 if ( $domain === $this->localDomainIdAlias ||
$domain === false ) {
270 // Local connection requested via some backwards-compatibility domain alias
271 return $this->getLocalDomainID();
274 return (string)$domain;
281 private function sanitizeConnectionFlags( $flags ) {
282 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) === self
::CONN_TRX_AUTOCOMMIT
) {
283 // Assuming all servers are of the same type (or similar), which is overwhelmingly
284 // the case, use the master server information to get the attributes. The information
285 // for $i cannot be used since it might be DB_REPLICA, which might require connection
286 // attempts in order to be resolved into a real server index.
287 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
288 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
289 // Callers sometimes want to (a) escape REPEATABLE-READ stateness without locking
290 // rows (e.g. FOR UPDATE) or (b) make small commits during a larger transactions
291 // to reduce lock contention. None of these apply for sqlite and using separate
292 // connections just causes self-deadlocks.
293 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
294 $this->connLogger
->info( __METHOD__
.
295 ': ignoring CONN_TRX_AUTOCOMMIT to avoid deadlocks.' );
303 * @param IDatabase $conn
305 * @throws DBUnexpectedError
307 private function enforceConnectionFlags( IDatabase
$conn, $flags ) {
308 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
) {
309 if ( $conn->trxLevel() ) { // sanity
310 throw new DBUnexpectedError(
312 'Handle requested with CONN_TRX_AUTOCOMMIT yet it has a transaction'
316 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
321 * Get a LoadMonitor instance
323 * @return ILoadMonitor
325 private function getLoadMonitor() {
326 if ( !isset( $this->loadMonitor
) ) {
328 'LoadMonitor' => LoadMonitor
::class,
329 'LoadMonitorNull' => LoadMonitorNull
::class,
330 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
333 $class = $this->loadMonitorConfig
['class'];
334 if ( isset( $compat[$class] ) ) {
335 $class = $compat[$class];
338 $this->loadMonitor
= new $class(
339 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
340 $this->loadMonitor
->setLogger( $this->replLogger
);
343 return $this->loadMonitor
;
347 * @param array $loads
348 * @param bool|string $domain Domain to get non-lagged for
349 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
350 * @return bool|int|string
352 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
353 $lags = $this->getLagTimes( $domain );
355 # Unset excessively lagged servers
356 foreach ( $lags as $i => $lag ) {
357 if ( $i !== $this->getWriterIndex() ) {
358 # How much lag this server nominally is allowed to have
359 $maxServerLag = $this->servers
[$i]['max lag'] ??
$this->maxLag
; // default
360 # Constrain that futher by $maxLag argument
361 $maxServerLag = min( $maxServerLag, $maxLag );
363 $host = $this->getServerName( $i );
364 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
365 $this->replLogger
->debug(
367 ": server {host} is not replicating?", [ 'host' => $host ] );
369 } elseif ( $lag > $maxServerLag ) {
370 $this->replLogger
->debug(
372 ": server {host} has {lag} seconds of lag (>= {maxlag})",
373 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
380 # Find out if all the replica DBs with non-zero load are lagged
382 foreach ( $loads as $load ) {
386 # No appropriate DB servers except maybe the master and some replica DBs with zero load
387 # Do NOT use the master
388 # Instead, this function will return false, triggering read-only mode,
389 # and a lagged replica DB will be used instead.
393 if ( count( $loads ) == 0 ) {
397 # Return a random representative of the remainder
398 return ArrayUtils
::pickRandom( $loads );
403 * @param array $groups
404 * @param string|bool $domain
405 * @return int The index of a specific server (replica DBs are checked for connectivity)
407 private function getConnectionIndex( $i, $groups, $domain ) {
408 // Check one "group" per default: the generic pool
409 $defaultGroups = $this->defaultGroup ?
[ $this->defaultGroup
] : [ false ];
411 $groups = ( $groups === false ||
$groups === [] )
415 if ( $i === self
::DB_MASTER
) {
416 $i = $this->getWriterIndex();
417 } elseif ( $i === self
::DB_REPLICA
) {
418 # Try to find an available server in any the query groups (in order)
419 foreach ( $groups as $group ) {
420 $groupIndex = $this->getReaderIndex( $group, $domain );
421 if ( $groupIndex !== false ) {
428 # Operation-based index
429 if ( $i === self
::DB_REPLICA
) {
430 $this->lastError
= 'Unknown error'; // reset error string
431 # Try the general server pool if $groups are unavailable.
432 $i = ( $groups === [ false ] )
433 ?
false // don't bother with this if that is what was tried above
434 : $this->getReaderIndex( false, $domain );
435 # Couldn't find a working server in getReaderIndex()?
436 if ( $i === false ) {
437 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
438 // Throw an exception
439 $this->reportConnectionError();
440 return null; // unreachable due to exception
447 public function getReaderIndex( $group = false, $domain = false ) {
448 if ( $this->getServerCount() == 1 ) {
449 // Skip the load balancing if there's only one server
450 return $this->getWriterIndex();
453 $index = $this->getExistingReaderIndex( $group );
455 // A reader index was already selected and "waitForPos" was handled
459 if ( $group !== false ) {
460 // Use the server weight array for this load group
461 if ( isset( $this->groupLoads
[$group] ) ) {
462 $loads = $this->groupLoads
[$group];
464 // No loads for this group, return false and the caller can use some other group
465 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
470 // Use the generic load group
471 $loads = $this->genericLoads
;
474 // Scale the configured load ratios according to each server's load and state
475 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
477 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
478 $this->lazyLoadReplicationPositions(); // optimizes server candidate selection
479 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
480 if ( $i === false ) {
481 // DB connection unsuccessful
485 // If data seen by queries is expected to reflect the transactions committed as of
486 // or after a given replication position then wait for the DB to apply those changes
487 if ( $this->waitForPos
&& $i !== $this->getWriterIndex() && !$this->doWait( $i ) ) {
488 // Data will be outdated compared to what was expected
489 $laggedReplicaMode = true;
492 // Cache the reader index for future DB_REPLICA handles
493 $this->setExistingReaderIndex( $group, $i );
494 // Record whether the generic reader index is in "lagged replica DB" mode
495 if ( $group === false && $laggedReplicaMode ) {
496 $this->laggedReplicaMode
= true;
499 $serverName = $this->getServerName( $i );
500 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
506 * Get the server index chosen by the load balancer for use with the given query group
508 * @param string|bool $group Query group; use false for the generic group
509 * @return int Server index or -1 if none was chosen
511 protected function getExistingReaderIndex( $group ) {
512 if ( $group === false ) {
513 $index = $this->genericReadIndex
;
515 $index = $this->readIndexByGroup
[$group] ??
-1;
522 * Set the server index chosen by the load balancer for use with the given query group
524 * @param string|bool $group Query group; use false for the generic group
525 * @param int $index The index of a specific server
527 private function setExistingReaderIndex( $group, $index ) {
529 throw new UnexpectedValueException( "Cannot set a negative read server index" );
532 if ( $group === false ) {
533 $this->genericReadIndex
= $index;
535 $this->readIndexByGroup
[$group] = $index;
540 * @param array $loads List of server weights
541 * @param string|bool $domain
542 * @return array (reader index, lagged replica mode) or false on failure
544 private function pickReaderIndex( array $loads, $domain = false ) {
545 if ( $loads === [] ) {
546 throw new InvalidArgumentException( "Server configuration array is empty" );
549 /** @var int|bool $i Index of selected server */
551 /** @var bool $laggedReplicaMode Whether server is considered lagged */
552 $laggedReplicaMode = false;
554 // Quickly look through the available servers for a server that meets criteria...
555 $currentLoads = $loads;
556 while ( count( $currentLoads ) ) {
557 if ( $this->allowLagged ||
$laggedReplicaMode ) {
558 $i = ArrayUtils
::pickRandom( $currentLoads );
561 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
562 $this->replLogger
->debug( __METHOD__
. ": replication positions detected" );
563 // "chronologyCallback" sets "waitForPos" for session consistency.
564 // This triggers doWait() after connect, so it's especially good to
565 // avoid lagged servers so as to avoid excessive delay in that method.
566 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
567 // Aim for <= 1 second of waiting (being too picky can backfire)
568 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
570 if ( $i === false ) {
571 // Any server with less lag than it's 'max lag' param is preferable
572 $i = $this->getRandomNonLagged( $currentLoads, $domain );
574 if ( $i === false && count( $currentLoads ) ) {
575 // All replica DBs lagged. Switch to read-only mode
576 $this->replLogger
->error(
577 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
578 $i = ArrayUtils
::pickRandom( $currentLoads );
579 $laggedReplicaMode = true;
583 if ( $i === false ) {
584 // pickRandom() returned false.
585 // This is permanent and means the configuration or the load monitor
586 // wants us to return false.
587 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
589 return [ false, false ];
592 $serverName = $this->getServerName( $i );
593 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
595 $conn = $this->getConnection( $i, [], $domain, self
::CONN_SILENCE_ERRORS
);
597 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
598 unset( $currentLoads[$i] ); // avoid this server next iteration
603 // Decrement reference counter, we are finished with this connection.
604 // It will be incremented for the caller later.
605 if ( $domain !== false ) {
606 $this->reuseConnection( $conn );
609 // Return this server
613 // If all servers were down, quit now
614 if ( $currentLoads === [] ) {
615 $this->connLogger
->error( __METHOD__
. ": all servers down" );
618 return [ $i, $laggedReplicaMode ];
621 public function waitFor( $pos ) {
622 $oldPos = $this->waitForPos
;
624 $this->waitForPos
= $pos;
625 // If a generic reader connection was already established, then wait now
626 if ( $this->genericReadIndex
> 0 && !$this->doWait( $this->genericReadIndex
) ) {
627 $this->laggedReplicaMode
= true;
629 // Otherwise, wait until a connection is established in getReaderIndex()
631 // Restore the older position if it was higher since this is used for lag-protection
632 $this->setWaitForPositionIfHigher( $oldPos );
636 public function waitForOne( $pos, $timeout = null ) {
637 $oldPos = $this->waitForPos
;
639 $this->waitForPos
= $pos;
641 $i = $this->genericReadIndex
;
643 // Pick a generic replica DB if there isn't one yet
644 $readLoads = $this->genericLoads
;
645 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
646 $readLoads = array_filter( $readLoads ); // with non-zero load
647 $i = ArrayUtils
::pickRandom( $readLoads );
651 $ok = $this->doWait( $i, true, $timeout );
653 $ok = true; // no applicable loads
656 # Restore the old position, as this is not used for lag-protection but for throttling
657 $this->waitForPos
= $oldPos;
663 public function waitForAll( $pos, $timeout = null ) {
664 $timeout = $timeout ?
: $this->waitTimeout
;
666 $oldPos = $this->waitForPos
;
668 $this->waitForPos
= $pos;
669 $serverCount = $this->getServerCount();
672 for ( $i = 1; $i < $serverCount; $i++
) {
673 if ( $this->genericLoads
[$i] > 0 ) {
674 $start = microtime( true );
675 $ok = $this->doWait( $i, true, $timeout ) && $ok;
676 $timeout -= intval( microtime( true ) - $start );
677 if ( $timeout <= 0 ) {
678 break; // timeout reached
683 # Restore the old position, as this is not used for lag-protection but for throttling
684 $this->waitForPos
= $oldPos;
691 * @param DBMasterPos|bool $pos
693 private function setWaitForPositionIfHigher( $pos ) {
698 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
699 $this->waitForPos
= $pos;
703 public function getAnyOpenConnection( $i, $flags = 0 ) {
704 $i = ( $i === self
::DB_MASTER
) ?
$this->getWriterIndex() : $i;
705 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
707 foreach ( $this->conns
as $connsByServer ) {
708 if ( $i === self
::DB_REPLICA
) {
709 $indexes = array_keys( $connsByServer );
711 $indexes = isset( $connsByServer[$i] ) ?
[ $i ] : [];
714 foreach ( $indexes as $index ) {
715 foreach ( $connsByServer[$index] as $conn ) {
716 if ( !$conn->isOpen() ) {
717 continue; // some sort of error occured?
719 if ( !$autocommit ||
$conn->getLBInfo( 'autoCommitOnly' ) ) {
730 * Wait for a given replica DB to catch up to the master pos stored in "waitForPos"
731 * @param int $index Server index
732 * @param bool $open Check the server even if a new connection has to be made
733 * @param int|null $timeout Max seconds to wait; default is "waitTimeout"
736 protected function doWait( $index, $open = false, $timeout = null ) {
737 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
739 // Check if we already know that the DB has reached this point
740 $server = $this->getServerName( $index );
741 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
742 /** @var DBMasterPos $knownReachedPos */
743 $knownReachedPos = $this->srvCache
->get( $key );
745 $knownReachedPos instanceof DBMasterPos
&&
746 $knownReachedPos->hasReached( $this->waitForPos
)
748 $this->replLogger
->debug(
750 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
751 [ 'dbserver' => $server ]
756 // Find a connection to wait on, creating one if needed and allowed
757 $close = false; // close the connection afterwards
758 $conn = $this->getAnyOpenConnection( $index );
761 $this->replLogger
->debug(
762 __METHOD__
. ': no connection open for {dbserver}',
763 [ 'dbserver' => $server ]
768 // Open a temporary new connection in order to wait for replication
769 $conn = $this->getConnection( $index, [], self
::DOMAIN_ANY
, self
::CONN_SILENCE_ERRORS
);
771 $this->replLogger
->warning(
772 __METHOD__
. ': failed to connect to {dbserver}',
773 [ 'dbserver' => $server ]
778 // Avoid connection spam in waitForAll() when connections
779 // are made just for the sake of doing this lag check.
783 $this->replLogger
->info(
785 ': waiting for replica DB {dbserver} to catch up...',
786 [ 'dbserver' => $server ]
789 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
791 if ( $result === null ) {
792 $this->replLogger
->warning(
793 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
796 'pos' => $this->waitForPos
,
797 'trace' => ( new RuntimeException() )->getTraceAsString()
801 } elseif ( $result == -1 ) {
802 $this->replLogger
->warning(
803 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
806 'pos' => $this->waitForPos
,
807 'trace' => ( new RuntimeException() )->getTraceAsString()
812 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
814 // Remember that the DB reached this point
815 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
819 $this->closeConnection( $conn );
825 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
826 if ( !is_int( $i ) ) {
827 throw new InvalidArgumentException( "Cannot connect without a server index" );
828 } elseif ( $groups && $i > 0 ) {
829 throw new InvalidArgumentException( "Got query groups with server index #$i" );
832 $domain = $this->resolveDomainID( $domain );
833 $flags = $this->sanitizeConnectionFlags( $flags );
834 $masterOnly = ( $i === self
::DB_MASTER ||
$i === $this->getWriterIndex() );
836 // Number of connections made before getting the server index and handle
837 $priorConnectionsMade = $this->connectionCounter
;
838 // Choose a server if $i is DB_MASTER/DB_REPLICA (might trigger new connections)
839 $serverIndex = $this->getConnectionIndex( $i, $groups, $domain );
840 // Get an open connection to that server (might trigger a new connection)
841 $conn = $this->localDomain
->equals( $domain )
842 ?
$this->getLocalConnection( $serverIndex, $flags )
843 : $this->getForeignConnection( $serverIndex, $domain, $flags );
844 // Throw an error or bail out if the connection attempt failed
845 if ( !( $conn instanceof IDatabase
) ) {
846 if ( ( $flags & self
::CONN_SILENCE_ERRORS
) != self
::CONN_SILENCE_ERRORS
) {
847 $this->reportConnectionError();
853 // Profile any new connections caused by this method
854 if ( $this->connectionCounter
> $priorConnectionsMade ) {
855 $host = $conn->getServer();
856 $dbname = $conn->getDBname();
857 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
860 if ( !$conn->isOpen() ) {
861 // Connection was made but later unrecoverably lost for some reason.
862 // Do not return a handle that will just throw exceptions on use,
863 // but let the calling code (e.g. getReaderIndex) try another server.
864 $this->errorConnection
= $conn;
868 $this->enforceConnectionFlags( $conn, $flags );
869 if ( $serverIndex === $this->getWriterIndex() ) {
870 // If the load balancer is read-only, perhaps due to replication lag, then master
871 // DB handles will reflect that. Note that Database::assertIsWritableMaster() takes
872 // care of replica DB handles whereas getReadOnlyReason() would cause infinite loops.
873 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
879 public function reuseConnection( IDatabase
$conn ) {
880 $serverIndex = $conn->getLBInfo( 'serverIndex' );
881 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
882 if ( $serverIndex === null ||
$refCount === null ) {
884 * This can happen in code like:
885 * foreach ( $dbs as $db ) {
886 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
888 * $lb->reuseConnection( $conn );
890 * When a connection to the local DB is opened in this way, reuseConnection()
894 } elseif ( $conn instanceof DBConnRef
) {
895 // DBConnRef already handles calling reuseConnection() and only passes the live
896 // Database instance to this method. Any caller passing in a DBConnRef is broken.
897 $this->connLogger
->error(
898 __METHOD__
. ": got DBConnRef instance.\n" .
899 ( new RuntimeException() )->getTraceAsString() );
904 if ( $this->disabled
) {
905 return; // DBConnRef handle probably survived longer than the LoadBalancer
908 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
909 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
910 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
912 $connFreeKey = self
::KEY_FOREIGN_FREE
;
913 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
916 $domain = $conn->getDomainID();
917 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
918 throw new InvalidArgumentException(
919 "Connection $serverIndex/$domain not found; it may have already been freed" );
920 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
921 throw new InvalidArgumentException(
922 "Connection $serverIndex/$domain mismatched; it may have already been freed" );
925 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
926 if ( $refCount <= 0 ) {
927 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
928 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
929 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
930 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
932 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
934 $this->connLogger
->debug( __METHOD__
.
935 ": reference count for $serverIndex/$domain reduced to $refCount" );
939 public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
940 $domain = $this->resolveDomainID( $domain );
941 $role = $this->getRoleFromIndex( $i );
943 return new DBConnRef( $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
946 public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
947 $domain = $this->resolveDomainID( $domain );
948 $role = $this->getRoleFromIndex( $i );
950 return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role );
953 public function getMaintenanceConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
954 $domain = $this->resolveDomainID( $domain );
955 $role = $this->getRoleFromIndex( $i );
957 return new MaintainableDBConnRef(
958 $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
962 * @param int $i Server index or DB_MASTER/DB_REPLICA
963 * @return int One of DB_MASTER/DB_REPLICA
965 private function getRoleFromIndex( $i ) {
966 return ( $i === self
::DB_MASTER ||
$i === $this->getWriterIndex() )
973 * @param bool $domain
975 * @return Database|bool Live database handle or false on failure
976 * @deprecated Since 1.34 Use getConnection() instead
978 public function openConnection( $i, $domain = false, $flags = 0 ) {
979 return $this->getConnection( $i, [], $domain, $flags | self
::CONN_SILENCE_ERRORS
);
983 * Open a connection to a local DB, or return one if it is already open.
985 * On error, returns false, and the connection which caused the
986 * error will be available via $this->errorConnection.
988 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
990 * @param int $i Server index
991 * @param int $flags Class CONN_* constant bitfield
994 private function getLocalConnection( $i, $flags = 0 ) {
995 // Connection handles required to be in auto-commit mode use a separate connection
996 // pool since the main pool is effected by implicit and explicit transaction rounds
997 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
999 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
1000 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
1001 $conn = $this->conns
[$connKey][$i][0];
1003 // Open a new connection
1004 $server = $this->getServerInfoStrict( $i );
1005 $server['serverIndex'] = $i;
1006 $server['autoCommitOnly'] = $autoCommit;
1007 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
1008 $host = $this->getServerName( $i );
1009 if ( $conn->isOpen() ) {
1010 $this->connLogger
->debug(
1011 __METHOD__
. ": connected to database $i at '$host'." );
1012 $this->conns
[$connKey][$i][0] = $conn;
1014 $this->connLogger
->warning(
1015 __METHOD__
. ": failed to connect to database $i at '$host'." );
1016 $this->errorConnection
= $conn;
1021 // Final sanity check to make sure the right domain is selected
1023 $conn instanceof IDatabase
&&
1024 !$this->localDomain
->isCompatible( $conn->getDomainID() )
1026 throw new UnexpectedValueException(
1027 "Got connection to '{$conn->getDomainID()}', " .
1028 "but expected local domain ('{$this->localDomain}')" );
1035 * Open a connection to a foreign DB, or return one if it is already open.
1037 * Increments a reference count on the returned connection which locks the
1038 * connection to the requested domain. This reference count can be
1039 * decremented by calling reuseConnection().
1041 * If a connection is open to the appropriate server already, but with the wrong
1042 * database, it will be switched to the right database and returned, as long as
1043 * it has been freed first with reuseConnection().
1045 * On error, returns false, and the connection which caused the
1046 * error will be available via $this->errorConnection.
1048 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
1050 * @param int $i Server index
1051 * @param string $domain Domain ID to open
1052 * @param int $flags Class CONN_* constant bitfield
1053 * @return Database|bool Returns false on connection error
1054 * @throws DBError When database selection fails
1056 private function getForeignConnection( $i, $domain, $flags = 0 ) {
1057 $domainInstance = DatabaseDomain
::newFromId( $domain );
1058 // Connection handles required to be in auto-commit mode use a separate connection
1059 // pool since the main pool is effected by implicit and explicit transaction rounds
1060 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
1062 if ( $autoCommit ) {
1063 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
1064 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
1066 $connFreeKey = self
::KEY_FOREIGN_FREE
;
1067 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
1070 /** @var Database $conn */
1073 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
1074 // Reuse an in-use connection for the same domain
1075 $conn = $this->conns
[$connInUseKey][$i][$domain];
1076 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
1077 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
1078 // Reuse a free connection for the same domain
1079 $conn = $this->conns
[$connFreeKey][$i][$domain];
1080 unset( $this->conns
[$connFreeKey][$i][$domain] );
1081 $this->conns
[$connInUseKey][$i][$domain] = $conn;
1082 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
1083 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
1084 // Reuse a free connection from another domain if possible
1085 foreach ( $this->conns
[$connFreeKey][$i] as $oldDomain => $conn ) {
1086 if ( $domainInstance->getDatabase() !== null ) {
1087 // Check if changing the database will require a new connection.
1088 // In that case, leave the connection handle alone and keep looking.
1089 // This prevents connections from being closed mid-transaction and can
1090 // also avoid overhead if the same database will later be requested.
1092 $conn->databasesAreIndependent() &&
1093 $conn->getDBname() !== $domainInstance->getDatabase()
1097 // Select the new database, schema, and prefix
1098 $conn->selectDomain( $domainInstance );
1100 // Stay on the current database, but update the schema/prefix
1101 $conn->dbSchema( $domainInstance->getSchema() );
1102 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1104 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
1105 // Note that if $domain is an empty string, getDomainID() might not match it
1106 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1107 $this->connLogger
->debug( __METHOD__
.
1108 ": reusing free connection from $oldDomain for $domain" );
1114 // Open a new connection
1115 $server = $this->getServerInfoStrict( $i );
1116 $server['serverIndex'] = $i;
1117 $server['foreignPoolRefCount'] = 0;
1118 $server['foreign'] = true;
1119 $server['autoCommitOnly'] = $autoCommit;
1120 $conn = $this->reallyOpenConnection( $server, $domainInstance );
1121 if ( !$conn->isOpen() ) {
1122 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
1123 $this->errorConnection
= $conn;
1126 // Note that if $domain is an empty string, getDomainID() might not match it
1127 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1128 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1132 if ( $conn instanceof IDatabase
) {
1133 // Final sanity check to make sure the right domain is selected
1134 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1135 throw new UnexpectedValueException(
1136 "Got connection to '{$conn->getDomainID()}', but expected '$domain'" );
1138 // Increment reference count
1139 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1140 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1146 public function getServerAttributes( $i ) {
1147 return Database
::attributesFromType(
1148 $this->getServerType( $i ),
1149 $this->servers
[$i]['driver'] ??
null
1154 * Test if the specified index represents an open connection
1156 * @param int $index Server index
1160 private function isOpen( $index ) {
1161 if ( !is_int( $index ) ) {
1165 return (bool)$this->getAnyOpenConnection( $index );
1169 * Open a new network connection to a server (uncached)
1171 * Returns a Database object whether or not the connection was successful.
1173 * @param array $server
1174 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
1176 * @throws DBAccessError
1177 * @throws InvalidArgumentException
1179 protected function reallyOpenConnection( array $server, DatabaseDomain
$domain ) {
1180 if ( $this->disabled
) {
1181 throw new DBAccessError();
1184 if ( $domain->getDatabase() === null ) {
1185 // The database domain does not specify a DB name and some database systems require a
1186 // valid DB specified on connection. The $server configuration array contains a default
1187 // DB name to use for connections in such cases.
1188 if ( $server['type'] === 'mysql' ) {
1189 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1190 // and the DB name in $server might not exist due to legacy reasons (the default
1191 // domain used to ignore the local LB domain, even when mismatched).
1192 $server['dbname'] = null;
1195 $server['dbname'] = $domain->getDatabase();
1198 if ( $domain->getSchema() !== null ) {
1199 $server['schema'] = $domain->getSchema();
1202 // It is always possible to connect with any prefix, even the empty string
1203 $server['tablePrefix'] = $domain->getTablePrefix();
1205 // Let the handle know what the cluster master is (e.g. "db1052")
1206 $masterName = $this->getServerName( $this->getWriterIndex() );
1207 $server['clusterMasterHost'] = $masterName;
1209 $server['srvCache'] = $this->srvCache
;
1210 // Set loggers and profilers
1211 $server['connLogger'] = $this->connLogger
;
1212 $server['queryLogger'] = $this->queryLogger
;
1213 $server['errorLogger'] = $this->errorLogger
;
1214 $server['deprecationLogger'] = $this->deprecationLogger
;
1215 $server['profiler'] = $this->profiler
;
1216 $server['trxProfiler'] = $this->trxProfiler
;
1217 // Use the same agent and PHP mode for all DB handles
1218 $server['cliMode'] = $this->cliMode
;
1219 $server['agent'] = $this->agent
;
1220 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1221 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1222 $server['flags'] = $server['flags'] ?? IDatabase
::DBO_DEFAULT
;
1224 // Create a live connection object
1226 $db = Database
::factory( $server['type'], $server );
1227 // Log when many connection are made on requests
1228 ++
$this->connectionCounter
;
1229 $currentConnCount = $this->getCurrentConnectionCount();
1230 if ( $currentConnCount >= self
::CONN_HELD_WARN_THRESHOLD
) {
1231 $this->perfLogger
->warning(
1232 __METHOD__
. ": {connections}+ connections made (master={masterdb})",
1233 [ 'connections' => $currentConnCount, 'masterdb' => $masterName ]
1236 } catch ( DBConnectionError
$e ) {
1237 // FIXME: This is probably the ugliest thing I have ever done to
1238 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1242 $db->setLBInfo( $server );
1243 $db->setLazyMasterHandle(
1244 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1246 $db->setTableAliases( $this->tableAliases
);
1247 $db->setIndexAliases( $this->indexAliases
);
1249 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1250 if ( $this->trxRoundId
!== false ) {
1251 $this->applyTransactionRoundFlags( $db );
1253 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1254 $db->setTransactionListener( $name, $callback );
1258 $this->lazyLoadReplicationPositions(); // session consistency
1264 * Make sure that any "waitForPos" positions are loaded and available to doWait()
1266 private function lazyLoadReplicationPositions() {
1267 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
1268 $this->connectionAttempted
= true;
1269 ( $this->chronologyCallback
)( $this ); // generally calls waitFor()
1270 $this->connLogger
->debug( __METHOD__
. ': executed chronology callback.' );
1275 * @throws DBConnectionError
1277 private function reportConnectionError() {
1278 $conn = $this->errorConnection
; // the connection which caused the error
1280 'method' => __METHOD__
,
1281 'last_error' => $this->lastError
,
1284 if ( $conn instanceof IDatabase
) {
1285 $context['db_server'] = $conn->getServer();
1286 $this->connLogger
->warning(
1287 __METHOD__
. ": connection error: {last_error} ({db_server})",
1291 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1293 // No last connection, probably due to all servers being too busy
1294 $this->connLogger
->error(
1296 ": LB failure with no last connection. Connection error: {last_error}",
1300 // If all servers were busy, "lastError" will contain something sensible
1301 throw new DBConnectionError( null, $this->lastError
);
1305 public function getWriterIndex() {
1309 public function haveIndex( $i ) {
1310 return array_key_exists( $i, $this->servers
);
1313 public function isNonZeroLoad( $i ) {
1314 return array_key_exists( $i, $this->servers
) && $this->genericLoads
[$i] != 0;
1317 public function getServerCount() {
1318 return count( $this->servers
);
1321 public function hasReplicaServers() {
1322 return ( $this->getServerCount() > 1 );
1325 public function hasStreamingReplicaServers() {
1326 foreach ( $this->servers
as $i => $server ) {
1327 if ( $i !== $this->getWriterIndex() && empty( $server['is static'] ) ) {
1335 public function getServerName( $i ) {
1336 $name = $this->servers
[$i]['hostName'] ??
( $this->servers
[$i]['host'] ??
'' );
1338 return ( $name != '' ) ?
$name : 'localhost';
1341 public function getServerInfo( $i ) {
1342 return $this->servers
[$i] ??
false;
1345 public function getServerType( $i ) {
1346 return $this->servers
[$i]['type'] ??
'unknown';
1349 public function getMasterPos() {
1350 # If this entire request was served from a replica DB without opening a connection to the
1351 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1352 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1353 if ( !$masterConn ) {
1354 $serverCount = $this->getServerCount();
1355 for ( $i = 1; $i < $serverCount; $i++
) {
1356 $conn = $this->getAnyOpenConnection( $i );
1358 return $conn->getReplicaPos();
1362 return $masterConn->getMasterPos();
1368 public function disable() {
1370 $this->disabled
= true;
1373 public function closeAll() {
1374 $fname = __METHOD__
;
1375 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( $fname ) {
1376 $host = $conn->getServer();
1377 $this->connLogger
->debug(
1378 $fname . ": closing connection to database '$host'." );
1382 $this->conns
= self
::newTrackedConnectionsArray();
1385 public function closeConnection( IDatabase
$conn ) {
1386 if ( $conn instanceof DBConnRef
) {
1387 // Avoid calling close() but still leaving the handle in the pool
1388 throw new RuntimeException( 'Cannot close DBConnRef instance; it must be shareable' );
1391 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1392 foreach ( $this->conns
as $type => $connsByServer ) {
1393 if ( !isset( $connsByServer[$serverIndex] ) ) {
1397 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1398 if ( $conn === $trackedConn ) {
1399 $host = $this->getServerName( $i );
1400 $this->connLogger
->debug(
1401 __METHOD__
. ": closing connection to database $i at '$host'." );
1402 unset( $this->conns
[$type][$serverIndex][$i] );
1411 public function commitAll( $fname = __METHOD__
, $owner = null ) {
1412 $this->commitMasterChanges( $fname, $owner );
1413 $this->flushMasterSnapshots( $fname );
1414 $this->flushReplicaSnapshots( $fname );
1417 public function finalizeMasterChanges( $fname = __METHOD__
, $owner = null ) {
1418 $this->assertOwnership( $fname, $owner );
1419 $this->assertTransactionRoundStage( [ self
::ROUND_CURSORY
, self
::ROUND_FINALIZED
] );
1421 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1422 // Loop until callbacks stop adding callbacks on other connections
1425 $count = 0; // callbacks execution attempts
1426 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$count ) {
1427 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1428 // Any error should cause all (peer) transactions to be rolled back together.
1429 $count +
= $conn->runOnTransactionPreCommitCallbacks();
1432 } while ( $count > 0 );
1433 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1434 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1435 $conn->setTrxEndCallbackSuppression( true );
1437 $this->trxRoundStage
= self
::ROUND_FINALIZED
;
1442 public function approveMasterChanges( array $options, $fname = __METHOD__
, $owner = null ) {
1443 $this->assertOwnership( $fname, $owner );
1444 $this->assertTransactionRoundStage( self
::ROUND_FINALIZED
);
1446 $limit = $options['maxWriteDuration'] ??
0;
1448 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1449 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1450 // If atomic sections or explicit transactions are still open, some caller must have
1451 // caught an exception but failed to properly rollback any changes. Detect that and
1452 // throw and error (causing rollback).
1453 $conn->assertNoOpenTransactions();
1454 // Assert that the time to replicate the transaction will be sane.
1455 // If this fails, then all DB transactions will be rollback back together.
1456 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1457 if ( $limit > 0 && $time > $limit ) {
1458 throw new DBTransactionSizeError(
1460 "Transaction spent $time second(s) in writes, exceeding the limit of $limit",
1464 // If a connection sits idle while slow queries execute on another, that connection
1465 // may end up dropped before the commit round is reached. Ping servers to detect this.
1466 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1467 throw new DBTransactionError(
1469 "A connection to the {$conn->getDBname()} database was lost before commit"
1473 $this->trxRoundStage
= self
::ROUND_APPROVED
;
1476 public function beginMasterChanges( $fname = __METHOD__
, $owner = null ) {
1477 $this->assertOwnership( $fname, $owner );
1478 if ( $this->trxRoundId
!== false ) {
1479 throw new DBTransactionError(
1481 "$fname: Transaction round '{$this->trxRoundId}' already started"
1484 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
1486 // Clear any empty transactions (no writes/callbacks) from the implicit round
1487 $this->flushMasterSnapshots( $fname );
1489 $this->trxRoundId
= $fname;
1490 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1491 // Mark applicable handles as participating in this explicit transaction round.
1492 // For each of these handles, any writes and callbacks will be tied to a single
1493 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1494 // are part of an en masse commit or an en masse rollback.
1495 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1496 $this->applyTransactionRoundFlags( $conn );
1498 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1501 public function commitMasterChanges( $fname = __METHOD__
, $owner = null ) {
1502 $this->assertOwnership( $fname, $owner );
1503 $this->assertTransactionRoundStage( self
::ROUND_APPROVED
);
1507 /** @noinspection PhpUnusedLocalVariableInspection */
1508 $scope = ScopedCallback
::newScopedIgnoreUserAbort(); // try to ignore client aborts
1510 $restore = ( $this->trxRoundId
!== false );
1511 $this->trxRoundId
= false;
1512 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1513 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1514 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1515 $this->forEachOpenMasterConnection(
1516 function ( IDatabase
$conn ) use ( $fname, &$failures ) {
1518 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1519 } catch ( DBError
$e ) {
1520 ( $this->errorLogger
)( $e );
1521 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1526 throw new DBTransactionError(
1528 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1532 // Unmark handles as participating in this explicit transaction round
1533 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1534 $this->undoTransactionRoundFlags( $conn );
1537 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
1540 public function runMasterTransactionIdleCallbacks( $fname = __METHOD__
, $owner = null ) {
1541 $this->assertOwnership( $fname, $owner );
1542 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1543 $type = IDatabase
::TRIGGER_COMMIT
;
1544 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1545 $type = IDatabase
::TRIGGER_ROLLBACK
;
1547 throw new DBTransactionError(
1549 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1553 $oldStage = $this->trxRoundStage
;
1554 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1556 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1557 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1558 $conn->setTrxEndCallbackSuppression( false );
1561 $e = null; // first exception
1562 $fname = __METHOD__
;
1563 // Loop until callbacks stop adding callbacks on other connections
1565 // Run any pending callbacks for each connection...
1566 $count = 0; // callback execution attempts
1567 $this->forEachOpenMasterConnection(
1568 function ( Database
$conn ) use ( $type, &$e, &$count ) {
1569 if ( $conn->trxLevel() ) {
1570 return; // retry in the next iteration, after commit() is called
1573 $count +
= $conn->runOnTransactionIdleCallbacks( $type );
1574 } catch ( Exception
$ex ) {
1579 // Clear out any active transactions left over from callbacks...
1580 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$e, $fname ) {
1581 if ( $conn->writesPending() ) {
1582 // A callback from another handle wrote to this one and DBO_TRX is set
1583 $this->queryLogger
->warning( $fname . ": found writes pending." );
1584 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1585 $this->queryLogger
->warning(
1586 $fname . ": found writes pending ($fnames).",
1588 'db_server' => $conn->getServer(),
1589 'db_name' => $conn->getDBname()
1592 } elseif ( $conn->trxLevel() ) {
1593 // A callback from another handle read from this one and DBO_TRX is set,
1594 // which can easily happen if there is only one DB (no replicas)
1595 $this->queryLogger
->debug( $fname . ": found empty transaction." );
1598 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1599 } catch ( Exception
$ex ) {
1603 } while ( $count > 0 );
1605 $this->trxRoundStage
= $oldStage;
1610 public function runMasterTransactionListenerCallbacks( $fname = __METHOD__
, $owner = null ) {
1611 $this->assertOwnership( $fname, $owner );
1612 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1613 $type = IDatabase
::TRIGGER_COMMIT
;
1614 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1615 $type = IDatabase
::TRIGGER_ROLLBACK
;
1617 throw new DBTransactionError(
1619 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1625 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1626 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1628 $conn->runTransactionListenerCallbacks( $type );
1629 } catch ( Exception
$ex ) {
1633 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1638 public function rollbackMasterChanges( $fname = __METHOD__
, $owner = null ) {
1639 $this->assertOwnership( $fname, $owner );
1641 $restore = ( $this->trxRoundId
!== false );
1642 $this->trxRoundId
= false;
1643 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1644 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1645 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1648 // Unmark handles as participating in this explicit transaction round
1649 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1650 $this->undoTransactionRoundFlags( $conn );
1653 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
1657 * @param string|string[] $stage
1658 * @throws DBTransactionError
1660 private function assertTransactionRoundStage( $stage ) {
1661 $stages = (array)$stage;
1663 if ( !in_array( $this->trxRoundStage
, $stages, true ) ) {
1664 $stageList = implode(
1666 array_map( function ( $v ) {
1670 throw new DBTransactionError(
1672 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1678 * @param string $fname
1679 * @param int|null $owner Owner ID of the caller
1680 * @throws DBTransactionError
1682 private function assertOwnership( $fname, $owner ) {
1683 if ( $this->ownerId
!== null && $owner !== $this->ownerId
) {
1684 throw new DBTransactionError(
1686 "$fname: LoadBalancer is owned by LBFactory #{$this->ownerId} (got '$owner')."
1692 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1694 * Some servers may have neither flag enabled, meaning that they opt out of such
1695 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1696 * when a DB server is used for something like simple key/value storage.
1698 * @param Database $conn
1700 private function applyTransactionRoundFlags( Database
$conn ) {
1701 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1702 return; // transaction rounds do not apply to these connections
1705 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1706 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1707 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1708 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1711 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1712 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1717 * @param Database $conn
1719 private function undoTransactionRoundFlags( Database
$conn ) {
1720 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1721 return; // transaction rounds do not apply to these connections
1724 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1725 $conn->setLBInfo( 'trxRoundId', false );
1728 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1729 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1733 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1734 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) use ( $fname ) {
1735 $conn->flushSnapshot( $fname );
1739 public function flushMasterSnapshots( $fname = __METHOD__
) {
1740 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1741 $conn->flushSnapshot( $fname );
1749 public function getTransactionRoundStage() {
1750 return $this->trxRoundStage
;
1753 public function hasMasterConnection() {
1754 return $this->isOpen( $this->getWriterIndex() );
1757 public function hasMasterChanges() {
1759 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1760 $pending |
= $conn->writesOrCallbacksPending();
1763 return (bool)$pending;
1766 public function lastMasterChangeTimestamp() {
1768 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1769 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1775 public function hasOrMadeRecentMasterChanges( $age = null ) {
1776 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1778 return ( $this->hasMasterChanges()
1779 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1782 public function pendingMasterChangeCallers() {
1784 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1785 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1791 public function getLaggedReplicaMode( $domain = false ) {
1793 // Avoid recursion if there is only one DB
1794 $this->hasStreamingReplicaServers() &&
1795 // Avoid recursion if the (non-zero load) master DB was picked for generic reads
1796 $this->genericReadIndex
!== $this->getWriterIndex() &&
1797 // Stay in lagged replica mode during the load balancer instance lifetime
1798 !$this->laggedReplicaMode
1801 // Calling this method will set "laggedReplicaMode" as needed
1802 $this->getReaderIndex( false, $domain );
1803 } catch ( DBConnectionError
$e ) {
1804 // Avoid expensive re-connect attempts and failures
1805 $this->allReplicasDownMode
= true;
1806 $this->laggedReplicaMode
= true;
1810 return $this->laggedReplicaMode
;
1813 public function laggedReplicaUsed() {
1814 return $this->laggedReplicaMode
;
1820 * @deprecated Since 1.28; use laggedReplicaUsed()
1822 public function laggedSlaveUsed() {
1823 return $this->laggedReplicaUsed();
1826 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1827 if ( $this->readOnlyReason
!== false ) {
1828 return $this->readOnlyReason
;
1829 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1830 if ( $this->allReplicasDownMode
) {
1831 return 'The database has been automatically locked ' .
1832 'until the replica database servers become available';
1834 return 'The database has been automatically locked ' .
1835 'while the replica database servers catch up to the master.';
1837 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1838 return 'The database master is running in read-only mode.';
1845 * @param string $domain Domain ID, or false for the current domain
1846 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1849 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1850 $cache = $this->wanCache
;
1851 $masterServer = $this->getServerName( $this->getWriterIndex() );
1853 return (bool)$cache->getWithSetCallback(
1854 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1855 self
::TTL_CACHE_READONLY
,
1856 function () use ( $domain, $conn ) {
1857 $old = $this->trxProfiler
->setSilenced( true );
1859 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1860 $readOnly = (int)$dbw->serverIsReadOnly();
1862 $this->reuseConnection( $dbw );
1864 } catch ( DBError
$e ) {
1867 $this->trxProfiler
->setSilenced( $old );
1870 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1874 public function allowLagged( $mode = null ) {
1875 if ( $mode === null ) {
1876 return $this->allowLagged
;
1878 $this->allowLagged
= $mode;
1880 return $this->allowLagged
;
1883 public function pingAll() {
1885 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1886 if ( !$conn->ping() ) {
1894 public function forEachOpenConnection( $callback, array $params = [] ) {
1895 foreach ( $this->conns
as $connsByServer ) {
1896 foreach ( $connsByServer as $serverConns ) {
1897 foreach ( $serverConns as $conn ) {
1898 $callback( $conn, ...$params );
1904 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1905 $masterIndex = $this->getWriterIndex();
1906 foreach ( $this->conns
as $connsByServer ) {
1907 if ( isset( $connsByServer[$masterIndex] ) ) {
1908 /** @var IDatabase $conn */
1909 foreach ( $connsByServer[$masterIndex] as $conn ) {
1910 $callback( $conn, ...$params );
1916 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1917 foreach ( $this->conns
as $connsByServer ) {
1918 foreach ( $connsByServer as $i => $serverConns ) {
1919 if ( $i === $this->getWriterIndex() ) {
1920 continue; // skip master
1922 foreach ( $serverConns as $conn ) {
1923 $callback( $conn, ...$params );
1932 private function getCurrentConnectionCount() {
1934 foreach ( $this->conns
as $connsByServer ) {
1935 foreach ( $connsByServer as $serverConns ) {
1936 $count +
= count( $serverConns );
1943 public function getMaxLag( $domain = false ) {
1948 if ( $this->hasReplicaServers() ) {
1949 $lagTimes = $this->getLagTimes( $domain );
1950 foreach ( $lagTimes as $i => $lag ) {
1951 if ( $this->genericLoads
[$i] > 0 && $lag > $maxLag ) {
1953 $host = $this->getServerInfoStrict( $i, 'host' );
1959 return [ $host, $maxLag, $maxIndex ];
1962 public function getLagTimes( $domain = false ) {
1963 if ( !$this->hasReplicaServers() ) {
1964 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1967 $knownLagTimes = []; // map of (server index => 0 seconds)
1968 $indexesWithLag = [];
1969 foreach ( $this->servers
as $i => $server ) {
1970 if ( empty( $server['is static'] ) ) {
1971 $indexesWithLag[] = $i; // DB server might have replication lag
1973 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1977 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1981 * Get the lag in seconds for a given connection, or zero if this load
1982 * balancer does not have replication enabled.
1984 * This should be used in preference to Database::getLag() in cases where
1985 * replication may not be in use, since there is no way to determine if
1986 * replication is in use at the connection level without running
1987 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1988 * function instead of Database::getLag() avoids a fatal error in this
1989 * case on many installations.
1991 * @param IDatabase $conn
1992 * @return int|bool Returns false on error
1993 * @deprecated Since 1.34 Use IDatabase::getLag() instead
1995 public function safeGetLag( IDatabase
$conn ) {
1996 if ( $conn->getLBInfo( 'is static' ) ) {
1997 return 0; // static dataset
1998 } elseif ( $conn->getLBInfo( 'serverIndex' ) == $this->getWriterIndex() ) {
1999 return 0; // this is the master
2002 return $conn->getLag();
2005 public function waitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
2006 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
2008 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
2009 return true; // server is not a replica DB
2013 // Get the current master position, opening a connection if needed
2014 $index = $this->getWriterIndex();
2015 $masterConn = $this->getAnyOpenConnection( $index );
2016 if ( $masterConn ) {
2017 $pos = $masterConn->getMasterPos();
2019 $flags = self
::CONN_SILENCE_ERRORS
;
2020 $masterConn = $this->getConnection( $index, [], self
::DOMAIN_ANY
, $flags );
2021 if ( !$masterConn ) {
2022 throw new DBReplicationWaitError(
2024 "Could not obtain a master database connection to get the position"
2027 $pos = $masterConn->getMasterPos();
2028 $this->closeConnection( $masterConn );
2032 if ( $pos instanceof DBMasterPos
) {
2033 $start = microtime( true );
2034 $result = $conn->masterPosWait( $pos, $timeout );
2035 $seconds = max( microtime( true ) - $start, 0 );
2036 if ( $result == -1 ||
is_null( $result ) ) {
2037 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos} [{seconds}s]';
2038 $this->replLogger
->warning( $msg, [
2039 'host' => $conn->getServer(),
2041 'seconds' => round( $seconds, 6 ),
2042 'trace' => ( new RuntimeException() )->getTraceAsString()
2046 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
2050 $ok = false; // something is misconfigured
2051 $this->replLogger
->error(
2052 __METHOD__
. ': could not get master pos for {host}',
2054 'host' => $conn->getServer(),
2055 'trace' => ( new RuntimeException() )->getTraceAsString()
2064 * Wait for a replica DB to reach a specified master position
2066 * This will connect to the master to get an accurate position if $pos is not given
2068 * @param IDatabase $conn Replica DB
2069 * @param DBMasterPos|bool $pos Master position; default: current position
2070 * @param int $timeout Timeout in seconds [optional]
2071 * @return bool Success
2073 * @deprecated Since 1.34 Use waitForMasterPos() instead
2075 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
2076 return $this->waitForMasterPos( $conn, $pos, $timeout );
2079 public function setTransactionListener( $name, callable
$callback = null ) {
2081 $this->trxRecurringCallbacks
[$name] = $callback;
2083 unset( $this->trxRecurringCallbacks
[$name] );
2085 $this->forEachOpenMasterConnection(
2086 function ( IDatabase
$conn ) use ( $name, $callback ) {
2087 $conn->setTransactionListener( $name, $callback );
2092 public function setTableAliases( array $aliases ) {
2093 $this->tableAliases
= $aliases;
2096 public function setIndexAliases( array $aliases ) {
2097 $this->indexAliases
= $aliases;
2101 * @param string $prefix
2102 * @deprecated Since 1.33
2104 public function setDomainPrefix( $prefix ) {
2105 $this->setLocalDomainPrefix( $prefix );
2108 public function setLocalDomainPrefix( $prefix ) {
2109 // Find connections to explicit foreign domains still marked as in-use...
2111 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
2112 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
2113 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
2114 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
2115 $domainsInUse[] = $conn->getDomainID();
2119 // Do not switch connections to explicit foreign domains unless marked as safe
2120 if ( $domainsInUse ) {
2121 $domains = implode( ', ', $domainsInUse );
2122 throw new DBUnexpectedError( null,
2123 "Foreign domain connections are still in use ($domains)" );
2126 $this->setLocalDomain( new DatabaseDomain(
2127 $this->localDomain
->getDatabase(),
2128 $this->localDomain
->getSchema(),
2132 // Update the prefix for all local connections...
2133 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
2134 if ( !$db->getLBInfo( 'foreign' ) ) {
2135 $db->tablePrefix( $prefix );
2140 public function redefineLocalDomain( $domain ) {
2143 $this->setLocalDomain( DatabaseDomain
::newFromId( $domain ) );
2147 * @param DatabaseDomain $domain
2149 private function setLocalDomain( DatabaseDomain
$domain ) {
2150 $this->localDomain
= $domain;
2151 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
2152 // always true, gracefully handle the case when they fail to account for escaping.
2153 if ( $this->localDomain
->getTablePrefix() != '' ) {
2154 $this->localDomainIdAlias
=
2155 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
2157 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
2162 * @param int $i Server index
2163 * @param string|null $field Server index field [optional]
2164 * @return array|mixed
2165 * @throws InvalidArgumentException
2167 private function getServerInfoStrict( $i, $field = null ) {
2168 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
2169 throw new InvalidArgumentException( "No server with index '$i'" );
2172 if ( $field !== null ) {
2173 if ( !array_key_exists( $field, $this->servers
[$i] ) ) {
2174 throw new InvalidArgumentException( "No field '$field' in server index '$i'" );
2177 return $this->servers
[$i][$field];
2180 return $this->servers
[$i];
2183 function __destruct() {
2184 // Avoid connection leaks for sanity
2190 * @deprecated since 1.29
2192 class_alias( LoadBalancer
::class, 'LoadBalancer' );