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 connections opened */
121 private $connsOpened = 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
::newConnsArray();
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 newConnsArray() {
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->connsOpened
;
839 // Choose a server if $i is DB_MASTER/DB_REPLICA (might trigger new connections)
840 $serverIndex = $this->getConnectionIndex( $i, $groups, $domain );
841 // Get an open connection to that server (might trigger a new connection)
842 $conn = $this->localDomain
->equals( $domain )
843 ?
$this->getLocalConnection( $serverIndex, $flags )
844 : $this->getForeignConnection( $serverIndex, $domain, $flags );
845 // Throw an error or bail out if the connection attempt failed
846 if ( !( $conn instanceof IDatabase
) ) {
847 if ( ( $flags & self
::CONN_SILENCE_ERRORS
) != self
::CONN_SILENCE_ERRORS
) {
848 $this->reportConnectionError();
854 // Profile any new connections caused by this method
855 if ( $this->connsOpened
> $priorConnectionsMade ) {
856 $host = $conn->getServer();
857 $dbname = $conn->getDBname();
858 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
861 if ( !$conn->isOpen() ) {
862 // Connection was made but later unrecoverably lost for some reason.
863 // Do not return a handle that will just throw exceptions on use,
864 // but let the calling code (e.g. getReaderIndex) try another server.
865 $this->errorConnection
= $conn;
869 $this->enforceConnectionFlags( $conn, $flags );
870 if ( $serverIndex === $this->getWriterIndex() ) {
871 // If the load balancer is read-only, perhaps due to replication lag, then master
872 // DB handles will reflect that. Note that Database::assertIsWritableMaster() takes
873 // care of replica DB handles whereas getReadOnlyReason() would cause infinite loops.
874 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
880 public function reuseConnection( IDatabase
$conn ) {
881 $serverIndex = $conn->getLBInfo( 'serverIndex' );
882 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
883 if ( $serverIndex === null ||
$refCount === null ) {
885 * This can happen in code like:
886 * foreach ( $dbs as $db ) {
887 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
889 * $lb->reuseConnection( $conn );
891 * When a connection to the local DB is opened in this way, reuseConnection()
895 } elseif ( $conn instanceof DBConnRef
) {
896 // DBConnRef already handles calling reuseConnection() and only passes the live
897 // Database instance to this method. Any caller passing in a DBConnRef is broken.
898 $this->connLogger
->error(
899 __METHOD__
. ": got DBConnRef instance.\n" .
900 ( new RuntimeException() )->getTraceAsString() );
905 if ( $this->disabled
) {
906 return; // DBConnRef handle probably survived longer than the LoadBalancer
909 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
910 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
911 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
913 $connFreeKey = self
::KEY_FOREIGN_FREE
;
914 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
917 $domain = $conn->getDomainID();
918 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
919 throw new InvalidArgumentException(
920 "Connection $serverIndex/$domain not found; it may have already been freed" );
921 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
922 throw new InvalidArgumentException(
923 "Connection $serverIndex/$domain mismatched; it may have already been freed" );
926 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
927 if ( $refCount <= 0 ) {
928 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
929 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
930 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
931 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
933 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
935 $this->connLogger
->debug( __METHOD__
.
936 ": reference count for $serverIndex/$domain reduced to $refCount" );
940 public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
941 $domain = $this->resolveDomainID( $domain );
942 $role = $this->getRoleFromIndex( $i );
944 return new DBConnRef( $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
947 public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
948 $domain = $this->resolveDomainID( $domain );
949 $role = $this->getRoleFromIndex( $i );
951 return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role );
954 public function getMaintenanceConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
955 $domain = $this->resolveDomainID( $domain );
956 $role = $this->getRoleFromIndex( $i );
958 return new MaintainableDBConnRef(
959 $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
963 * @param int $i Server index or DB_MASTER/DB_REPLICA
964 * @return int One of DB_MASTER/DB_REPLICA
966 private function getRoleFromIndex( $i ) {
967 return ( $i === self
::DB_MASTER ||
$i === $this->getWriterIndex() )
974 * @param bool $domain
976 * @return Database|bool Live database handle or false on failure
977 * @deprecated Since 1.34 Use getConnection() instead
979 public function openConnection( $i, $domain = false, $flags = 0 ) {
980 return $this->getConnection( $i, [], $domain, $flags | self
::CONN_SILENCE_ERRORS
);
984 * Open a connection to a local DB, or return one if it is already open.
986 * On error, returns false, and the connection which caused the
987 * error will be available via $this->errorConnection.
989 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
991 * @param int $i Server index
992 * @param int $flags Class CONN_* constant bitfield
995 private function getLocalConnection( $i, $flags = 0 ) {
996 // Connection handles required to be in auto-commit mode use a separate connection
997 // pool since the main pool is effected by implicit and explicit transaction rounds
998 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
1000 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
1001 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
1002 $conn = $this->conns
[$connKey][$i][0];
1004 // Open a new connection
1005 $server = $this->getServerInfoStrict( $i );
1006 $server['serverIndex'] = $i;
1007 $server['autoCommitOnly'] = $autoCommit;
1008 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
1009 $host = $this->getServerName( $i );
1010 if ( $conn->isOpen() ) {
1011 $this->connLogger
->debug(
1012 __METHOD__
. ": connected to database $i at '$host'." );
1013 $this->conns
[$connKey][$i][0] = $conn;
1015 $this->connLogger
->warning(
1016 __METHOD__
. ": failed to connect to database $i at '$host'." );
1017 $this->errorConnection
= $conn;
1022 // Final sanity check to make sure the right domain is selected
1024 $conn instanceof IDatabase
&&
1025 !$this->localDomain
->isCompatible( $conn->getDomainID() )
1027 throw new UnexpectedValueException(
1028 "Got connection to '{$conn->getDomainID()}', " .
1029 "but expected local domain ('{$this->localDomain}')" );
1036 * Open a connection to a foreign DB, or return one if it is already open.
1038 * Increments a reference count on the returned connection which locks the
1039 * connection to the requested domain. This reference count can be
1040 * decremented by calling reuseConnection().
1042 * If a connection is open to the appropriate server already, but with the wrong
1043 * database, it will be switched to the right database and returned, as long as
1044 * it has been freed first with reuseConnection().
1046 * On error, returns false, and the connection which caused the
1047 * error will be available via $this->errorConnection.
1049 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
1051 * @param int $i Server index
1052 * @param string $domain Domain ID to open
1053 * @param int $flags Class CONN_* constant bitfield
1054 * @return Database|bool Returns false on connection error
1055 * @throws DBError When database selection fails
1057 private function getForeignConnection( $i, $domain, $flags = 0 ) {
1058 $domainInstance = DatabaseDomain
::newFromId( $domain );
1059 // Connection handles required to be in auto-commit mode use a separate connection
1060 // pool since the main pool is effected by implicit and explicit transaction rounds
1061 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
1063 if ( $autoCommit ) {
1064 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
1065 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
1067 $connFreeKey = self
::KEY_FOREIGN_FREE
;
1068 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
1071 /** @var Database $conn */
1074 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
1075 // Reuse an in-use connection for the same domain
1076 $conn = $this->conns
[$connInUseKey][$i][$domain];
1077 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
1078 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
1079 // Reuse a free connection for the same domain
1080 $conn = $this->conns
[$connFreeKey][$i][$domain];
1081 unset( $this->conns
[$connFreeKey][$i][$domain] );
1082 $this->conns
[$connInUseKey][$i][$domain] = $conn;
1083 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
1084 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
1085 // Reuse a free connection from another domain if possible
1086 foreach ( $this->conns
[$connFreeKey][$i] as $oldDomain => $conn ) {
1087 if ( $domainInstance->getDatabase() !== null ) {
1088 // Check if changing the database will require a new connection.
1089 // In that case, leave the connection handle alone and keep looking.
1090 // This prevents connections from being closed mid-transaction and can
1091 // also avoid overhead if the same database will later be requested.
1093 $conn->databasesAreIndependent() &&
1094 $conn->getDBname() !== $domainInstance->getDatabase()
1098 // Select the new database, schema, and prefix
1099 $conn->selectDomain( $domainInstance );
1101 // Stay on the current database, but update the schema/prefix
1102 $conn->dbSchema( $domainInstance->getSchema() );
1103 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1105 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
1106 // Note that if $domain is an empty string, getDomainID() might not match it
1107 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1108 $this->connLogger
->debug( __METHOD__
.
1109 ": reusing free connection from $oldDomain for $domain" );
1115 // Open a new connection
1116 $server = $this->getServerInfoStrict( $i );
1117 $server['serverIndex'] = $i;
1118 $server['foreignPoolRefCount'] = 0;
1119 $server['foreign'] = true;
1120 $server['autoCommitOnly'] = $autoCommit;
1121 $conn = $this->reallyOpenConnection( $server, $domainInstance );
1122 if ( !$conn->isOpen() ) {
1123 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
1124 $this->errorConnection
= $conn;
1127 // Note that if $domain is an empty string, getDomainID() might not match it
1128 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1129 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1133 if ( $conn instanceof IDatabase
) {
1134 // Final sanity check to make sure the right domain is selected
1135 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1136 throw new UnexpectedValueException(
1137 "Got connection to '{$conn->getDomainID()}', but expected '$domain'" );
1139 // Increment reference count
1140 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1141 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1147 public function getServerAttributes( $i ) {
1148 return Database
::attributesFromType(
1149 $this->getServerType( $i ),
1150 $this->servers
[$i]['driver'] ??
null
1155 * Test if the specified index represents an open connection
1157 * @param int $index Server index
1161 private function isOpen( $index ) {
1162 if ( !is_int( $index ) ) {
1166 return (bool)$this->getAnyOpenConnection( $index );
1170 * Open a new network connection to a server (uncached)
1172 * Returns a Database object whether or not the connection was successful.
1174 * @param array $server
1175 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
1177 * @throws DBAccessError
1178 * @throws InvalidArgumentException
1180 protected function reallyOpenConnection( array $server, DatabaseDomain
$domain ) {
1181 if ( $this->disabled
) {
1182 throw new DBAccessError();
1185 if ( $domain->getDatabase() === null ) {
1186 // The database domain does not specify a DB name and some database systems require a
1187 // valid DB specified on connection. The $server configuration array contains a default
1188 // DB name to use for connections in such cases.
1189 if ( $server['type'] === 'mysql' ) {
1190 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1191 // and the DB name in $server might not exist due to legacy reasons (the default
1192 // domain used to ignore the local LB domain, even when mismatched).
1193 $server['dbname'] = null;
1196 $server['dbname'] = $domain->getDatabase();
1199 if ( $domain->getSchema() !== null ) {
1200 $server['schema'] = $domain->getSchema();
1203 // It is always possible to connect with any prefix, even the empty string
1204 $server['tablePrefix'] = $domain->getTablePrefix();
1206 // Let the handle know what the cluster master is (e.g. "db1052")
1207 $masterName = $this->getServerName( $this->getWriterIndex() );
1208 $server['clusterMasterHost'] = $masterName;
1210 // Log when many connection are made on requests
1211 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
1212 $this->perfLogger
->warning( __METHOD__
. ": " .
1213 "{$this->connsOpened}+ connections made (master=$masterName)" );
1216 $server['srvCache'] = $this->srvCache
;
1217 // Set loggers and profilers
1218 $server['connLogger'] = $this->connLogger
;
1219 $server['queryLogger'] = $this->queryLogger
;
1220 $server['errorLogger'] = $this->errorLogger
;
1221 $server['deprecationLogger'] = $this->deprecationLogger
;
1222 $server['profiler'] = $this->profiler
;
1223 $server['trxProfiler'] = $this->trxProfiler
;
1224 // Use the same agent and PHP mode for all DB handles
1225 $server['cliMode'] = $this->cliMode
;
1226 $server['agent'] = $this->agent
;
1227 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1228 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1229 $server['flags'] = $server['flags'] ?? IDatabase
::DBO_DEFAULT
;
1231 // Create a live connection object
1233 $db = Database
::factory( $server['type'], $server );
1234 } catch ( DBConnectionError
$e ) {
1235 // FIXME: This is probably the ugliest thing I have ever done to
1236 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1240 $db->setLBInfo( $server );
1241 $db->setLazyMasterHandle(
1242 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1244 $db->setTableAliases( $this->tableAliases
);
1245 $db->setIndexAliases( $this->indexAliases
);
1247 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1248 if ( $this->trxRoundId
!== false ) {
1249 $this->applyTransactionRoundFlags( $db );
1251 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1252 $db->setTransactionListener( $name, $callback );
1256 $this->lazyLoadReplicationPositions(); // session consistency
1262 * Make sure that any "waitForPos" positions are loaded and available to doWait()
1264 private function lazyLoadReplicationPositions() {
1265 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
1266 $this->connectionAttempted
= true;
1267 ( $this->chronologyCallback
)( $this ); // generally calls waitFor()
1268 $this->connLogger
->debug( __METHOD__
. ': executed chronology callback.' );
1273 * @throws DBConnectionError
1275 private function reportConnectionError() {
1276 $conn = $this->errorConnection
; // the connection which caused the error
1278 'method' => __METHOD__
,
1279 'last_error' => $this->lastError
,
1282 if ( $conn instanceof IDatabase
) {
1283 $context['db_server'] = $conn->getServer();
1284 $this->connLogger
->warning(
1285 __METHOD__
. ": connection error: {last_error} ({db_server})",
1289 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1291 // No last connection, probably due to all servers being too busy
1292 $this->connLogger
->error(
1294 ": LB failure with no last connection. Connection error: {last_error}",
1298 // If all servers were busy, "lastError" will contain something sensible
1299 throw new DBConnectionError( null, $this->lastError
);
1303 public function getWriterIndex() {
1307 public function haveIndex( $i ) {
1308 return array_key_exists( $i, $this->servers
);
1311 public function isNonZeroLoad( $i ) {
1312 return array_key_exists( $i, $this->servers
) && $this->genericLoads
[$i] != 0;
1315 public function getServerCount() {
1316 return count( $this->servers
);
1319 public function hasReplicaServers() {
1320 return ( $this->getServerCount() > 1 );
1323 public function hasStreamingReplicaServers() {
1324 foreach ( $this->servers
as $i => $server ) {
1325 if ( $i !== $this->getWriterIndex() && empty( $server['is static'] ) ) {
1333 public function getServerName( $i ) {
1334 $name = $this->servers
[$i]['hostName'] ??
( $this->servers
[$i]['host'] ??
'' );
1336 return ( $name != '' ) ?
$name : 'localhost';
1339 public function getServerInfo( $i ) {
1340 return $this->servers
[$i] ??
false;
1343 public function getServerType( $i ) {
1344 return $this->servers
[$i]['type'] ??
'unknown';
1347 public function getMasterPos() {
1348 # If this entire request was served from a replica DB without opening a connection to the
1349 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1350 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1351 if ( !$masterConn ) {
1352 $serverCount = $this->getServerCount();
1353 for ( $i = 1; $i < $serverCount; $i++
) {
1354 $conn = $this->getAnyOpenConnection( $i );
1356 return $conn->getReplicaPos();
1360 return $masterConn->getMasterPos();
1366 public function disable() {
1368 $this->disabled
= true;
1371 public function closeAll() {
1372 $fname = __METHOD__
;
1373 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( $fname ) {
1374 $host = $conn->getServer();
1375 $this->connLogger
->debug(
1376 $fname . ": closing connection to database '$host'." );
1380 $this->conns
= self
::newConnsArray();
1381 $this->connsOpened
= 0;
1384 public function closeConnection( IDatabase
$conn ) {
1385 if ( $conn instanceof DBConnRef
) {
1386 // Avoid calling close() but still leaving the handle in the pool
1387 throw new RuntimeException( 'Cannot close DBConnRef instance; it must be shareable' );
1390 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1391 foreach ( $this->conns
as $type => $connsByServer ) {
1392 if ( !isset( $connsByServer[$serverIndex] ) ) {
1396 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1397 if ( $conn === $trackedConn ) {
1398 $host = $this->getServerName( $i );
1399 $this->connLogger
->debug(
1400 __METHOD__
. ": closing connection to database $i at '$host'." );
1401 unset( $this->conns
[$type][$serverIndex][$i] );
1402 --$this->connsOpened
;
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 );
1929 public function getMaxLag( $domain = false ) {
1934 if ( $this->hasReplicaServers() ) {
1935 $lagTimes = $this->getLagTimes( $domain );
1936 foreach ( $lagTimes as $i => $lag ) {
1937 if ( $this->genericLoads
[$i] > 0 && $lag > $maxLag ) {
1939 $host = $this->getServerInfoStrict( $i, 'host' );
1945 return [ $host, $maxLag, $maxIndex ];
1948 public function getLagTimes( $domain = false ) {
1949 if ( !$this->hasReplicaServers() ) {
1950 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1953 $knownLagTimes = []; // map of (server index => 0 seconds)
1954 $indexesWithLag = [];
1955 foreach ( $this->servers
as $i => $server ) {
1956 if ( empty( $server['is static'] ) ) {
1957 $indexesWithLag[] = $i; // DB server might have replication lag
1959 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1963 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1967 * Get the lag in seconds for a given connection, or zero if this load
1968 * balancer does not have replication enabled.
1970 * This should be used in preference to Database::getLag() in cases where
1971 * replication may not be in use, since there is no way to determine if
1972 * replication is in use at the connection level without running
1973 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1974 * function instead of Database::getLag() avoids a fatal error in this
1975 * case on many installations.
1977 * @param IDatabase $conn
1978 * @return int|bool Returns false on error
1979 * @deprecated Since 1.34 Use IDatabase::getLag() instead
1981 public function safeGetLag( IDatabase
$conn ) {
1982 if ( $conn->getLBInfo( 'is static' ) ) {
1983 return 0; // static dataset
1984 } elseif ( $conn->getLBInfo( 'serverIndex' ) == $this->getWriterIndex() ) {
1985 return 0; // this is the master
1988 return $conn->getLag();
1991 public function waitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
1992 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
1994 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1995 return true; // server is not a replica DB
1999 // Get the current master position, opening a connection if needed
2000 $index = $this->getWriterIndex();
2001 $masterConn = $this->getAnyOpenConnection( $index );
2002 if ( $masterConn ) {
2003 $pos = $masterConn->getMasterPos();
2005 $flags = self
::CONN_SILENCE_ERRORS
;
2006 $masterConn = $this->getConnection( $index, [], self
::DOMAIN_ANY
, $flags );
2007 if ( !$masterConn ) {
2008 throw new DBReplicationWaitError(
2010 "Could not obtain a master database connection to get the position"
2013 $pos = $masterConn->getMasterPos();
2014 $this->closeConnection( $masterConn );
2018 if ( $pos instanceof DBMasterPos
) {
2019 $start = microtime( true );
2020 $result = $conn->masterPosWait( $pos, $timeout );
2021 $seconds = max( microtime( true ) - $start, 0 );
2022 if ( $result == -1 ||
is_null( $result ) ) {
2023 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos} [{seconds}s]';
2024 $this->replLogger
->warning( $msg, [
2025 'host' => $conn->getServer(),
2027 'seconds' => round( $seconds, 6 ),
2028 'trace' => ( new RuntimeException() )->getTraceAsString()
2032 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
2036 $ok = false; // something is misconfigured
2037 $this->replLogger
->error(
2038 __METHOD__
. ': could not get master pos for {host}',
2040 'host' => $conn->getServer(),
2041 'trace' => ( new RuntimeException() )->getTraceAsString()
2050 * Wait for a replica DB to reach a specified master position
2052 * This will connect to the master to get an accurate position if $pos is not given
2054 * @param IDatabase $conn Replica DB
2055 * @param DBMasterPos|bool $pos Master position; default: current position
2056 * @param int $timeout Timeout in seconds [optional]
2057 * @return bool Success
2059 * @deprecated Since 1.34 Use waitForMasterPos() instead
2061 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
2062 return $this->waitForMasterPos( $conn, $pos, $timeout );
2065 public function setTransactionListener( $name, callable
$callback = null ) {
2067 $this->trxRecurringCallbacks
[$name] = $callback;
2069 unset( $this->trxRecurringCallbacks
[$name] );
2071 $this->forEachOpenMasterConnection(
2072 function ( IDatabase
$conn ) use ( $name, $callback ) {
2073 $conn->setTransactionListener( $name, $callback );
2078 public function setTableAliases( array $aliases ) {
2079 $this->tableAliases
= $aliases;
2082 public function setIndexAliases( array $aliases ) {
2083 $this->indexAliases
= $aliases;
2087 * @param string $prefix
2088 * @deprecated Since 1.33
2090 public function setDomainPrefix( $prefix ) {
2091 $this->setLocalDomainPrefix( $prefix );
2094 public function setLocalDomainPrefix( $prefix ) {
2095 // Find connections to explicit foreign domains still marked as in-use...
2097 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
2098 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
2099 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
2100 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
2101 $domainsInUse[] = $conn->getDomainID();
2105 // Do not switch connections to explicit foreign domains unless marked as safe
2106 if ( $domainsInUse ) {
2107 $domains = implode( ', ', $domainsInUse );
2108 throw new DBUnexpectedError( null,
2109 "Foreign domain connections are still in use ($domains)" );
2112 $this->setLocalDomain( new DatabaseDomain(
2113 $this->localDomain
->getDatabase(),
2114 $this->localDomain
->getSchema(),
2118 // Update the prefix for all local connections...
2119 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
2120 if ( !$db->getLBInfo( 'foreign' ) ) {
2121 $db->tablePrefix( $prefix );
2126 public function redefineLocalDomain( $domain ) {
2129 $this->setLocalDomain( DatabaseDomain
::newFromId( $domain ) );
2133 * @param DatabaseDomain $domain
2135 private function setLocalDomain( DatabaseDomain
$domain ) {
2136 $this->localDomain
= $domain;
2137 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
2138 // always true, gracefully handle the case when they fail to account for escaping.
2139 if ( $this->localDomain
->getTablePrefix() != '' ) {
2140 $this->localDomainIdAlias
=
2141 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
2143 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
2148 * @param int $i Server index
2149 * @param string|null $field Server index field [optional]
2150 * @return array|mixed
2151 * @throws InvalidArgumentException
2153 private function getServerInfoStrict( $i, $field = null ) {
2154 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
2155 throw new InvalidArgumentException( "No server with index '$i'" );
2158 if ( $field !== null ) {
2159 if ( !array_key_exists( $field, $this->servers
[$i] ) ) {
2160 throw new InvalidArgumentException( "No field '$field' in server index '$i'" );
2163 return $this->servers
[$i][$field];
2166 return $this->servers
[$i];
2169 function __destruct() {
2170 // Avoid connection leaks for sanity
2176 * @deprecated since 1.29
2178 class_alias( LoadBalancer
::class, 'LoadBalancer' );