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
;
32 use UnexpectedValueException
;
33 use InvalidArgumentException
;
38 * Database connection, tracking, load balancing, and transaction manager for a cluster
42 class LoadBalancer
implements ILoadBalancer
{
43 /** @var ILoadMonitor */
45 /** @var callable|null Callback to run before the first connection attempt */
46 private $chronologyCallback;
49 /** @var WANObjectCache */
51 /** @var mixed Class name or object With profileIn/profileOut methods */
53 /** @var TransactionProfiler */
55 /** @var LoggerInterface */
57 /** @var LoggerInterface */
59 /** @var LoggerInterface */
61 /** @var LoggerInterface */
63 /** @var callable Exception logger */
65 /** @var callable Deprecation logger */
66 private $deprecationLogger;
68 /** @var DatabaseDomain Local DB domain ID and default for selectDB() calls */
71 /** @var Database[][][] Map of (connection category => server index => IDatabase[]) */
74 /** @var array[] Map of (server index => server config array) */
76 /** @var array[] Map of (group => server index => weight) */
78 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
80 /** @var int Seconds to spend waiting on replica DB lag to resolve */
82 /** @var array The LoadMonitor configuration */
83 private $loadMonitorConfig;
84 /** @var string Alternate local DB domain instead of DatabaseDomain::getId() */
85 private $localDomainIdAlias;
86 /** @var int Amount of replication lag, in seconds, that is considered "high" */
88 /** @var string|null Default query group to use with getConnection() */
89 private $defaultGroup;
91 /** @var string Current server name */
93 /** @var bool Whether this PHP instance is for a CLI script */
95 /** @var string Agent name for query profiling */
98 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
99 private $tableAliases = [];
100 /** @var string[] Map of (index alias => index) */
101 private $indexAliases = [];
102 /** @var array[] Map of (name => callable) */
103 private $trxRecurringCallbacks = [];
105 /** @var Database Connection handle that caused a problem */
106 private $errorConnection;
107 /** @var int[] The group replica server indexes keyed by group */
108 private $readIndexByGroup = [];
109 /** @var bool|DBMasterPos Replication sync position or false if not set */
111 /** @var bool Whether the generic reader fell back to a lagged replica DB */
112 private $laggedReplicaMode = false;
113 /** @var string The last DB selection or connection error */
114 private $lastError = 'Unknown error';
115 /** @var string|bool Reason this instance is read-only or false if not */
116 private $readOnlyReason = false;
117 /** @var int Total number of new connections ever made with this instance */
118 private $connectionCounter = 0;
120 private $disabled = false;
121 /** @var bool Whether any connection has been attempted yet */
122 private $connectionAttempted = false;
124 /** var int An identifier for this class instance */
126 /** @var int|null Integer ID of the managing LBFactory instance or null if none */
128 /** @var string|bool Explicit DBO_TRX transaction round active or false if none */
129 private $trxRoundId = false;
130 /** @var string Stage of the current transaction round in the transaction round life-cycle */
131 private $trxRoundStage = self
::ROUND_CURSORY
;
133 /** @var int Warn when this many connection are held */
134 const CONN_HELD_WARN_THRESHOLD
= 10;
136 /** @var int Default 'maxLag' when unspecified */
137 const MAX_LAG_DEFAULT
= 6;
138 /** @var int Default 'waitTimeout' when unspecified */
139 const MAX_WAIT_DEFAULT
= 10;
140 /** @var int Seconds to cache master DB server read-only status */
141 const TTL_CACHE_READONLY
= 5;
143 const KEY_LOCAL
= 'local';
144 const KEY_FOREIGN_FREE
= 'foreignFree';
145 const KEY_FOREIGN_INUSE
= 'foreignInUse';
147 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
148 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
149 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
151 /** @var string Transaction round, explicit or implicit, has not finished writing */
152 const ROUND_CURSORY
= 'cursory';
153 /** @var string Transaction round writes are complete and ready for pre-commit checks */
154 const ROUND_FINALIZED
= 'finalized';
155 /** @var string Transaction round passed final pre-commit checks */
156 const ROUND_APPROVED
= 'approved';
157 /** @var string Transaction round was committed and post-commit callbacks must be run */
158 const ROUND_COMMIT_CALLBACKS
= 'commit-callbacks';
159 /** @var string Transaction round was rolled back and post-rollback callbacks must be run */
160 const ROUND_ROLLBACK_CALLBACKS
= 'rollback-callbacks';
161 /** @var string Transaction round encountered an error */
162 const ROUND_ERROR
= 'error';
164 public function __construct( array $params ) {
165 if ( !isset( $params['servers'] ) ||
!count( $params['servers'] ) ) {
166 throw new InvalidArgumentException( 'Missing or empty "servers" parameter' );
171 $this->groupLoads
= [ self
::GROUP_GENERIC
=> [] ];
172 foreach ( $params['servers'] as $i => $server ) {
173 if ( ++
$listKey !== $i ) {
174 throw new UnexpectedValueException( 'List expected for "servers" parameter' );
176 $this->servers
[$i] = $server;
177 foreach ( ( $server['groupLoads'] ??
[] ) as $group => $ratio ) {
178 $this->groupLoads
[$group][$i] = $ratio;
180 $this->groupLoads
[self
::GROUP_GENERIC
][$i] = $server['load'];
183 $localDomain = isset( $params['localDomain'] )
184 ? DatabaseDomain
::newFromId( $params['localDomain'] )
185 : DatabaseDomain
::newUnspecified();
186 $this->setLocalDomain( $localDomain );
188 $this->waitTimeout
= $params['waitTimeout'] ?? self
::MAX_WAIT_DEFAULT
;
190 $this->conns
= self
::newTrackedConnectionsArray();
191 $this->waitForPos
= false;
192 $this->allowLagged
= false;
194 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
195 $this->readOnlyReason
= $params['readOnlyReason'];
198 $this->maxLag
= $params['maxLag'] ?? self
::MAX_LAG_DEFAULT
;
200 $this->loadMonitorConfig
= $params['loadMonitor'] ??
[ 'class' => 'LoadMonitorNull' ];
201 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
203 $this->srvCache
= $params['srvCache'] ??
new EmptyBagOStuff();
204 $this->wanCache
= $params['wanCache'] ?? WANObjectCache
::newEmpty();
205 $this->profiler
= $params['profiler'] ??
null;
206 $this->trxProfiler
= $params['trxProfiler'] ??
new TransactionProfiler();
208 $this->errorLogger
= $params['errorLogger'] ??
function ( Exception
$e ) {
209 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
211 $this->deprecationLogger
= $params['deprecationLogger'] ??
function ( $msg ) {
212 trigger_error( $msg, E_USER_DEPRECATED
);
215 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
216 $this->$key = $params[$key] ??
new NullLogger();
219 $this->hostname
= $params['hostname'] ??
( gethostname() ?
: 'unknown' );
220 $this->cliMode
= $params['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
221 $this->agent
= $params['agent'] ??
'';
223 if ( isset( $params['chronologyCallback'] ) ) {
224 $this->chronologyCallback
= $params['chronologyCallback'];
227 if ( isset( $params['roundStage'] ) ) {
228 if ( $params['roundStage'] === self
::STAGE_POSTCOMMIT_CALLBACKS
) {
229 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
230 } elseif ( $params['roundStage'] === self
::STAGE_POSTROLLBACK_CALLBACKS
) {
231 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
235 $group = $params['defaultGroup'] ?? self
::GROUP_GENERIC
;
236 $this->defaultGroup
= isset( $this->groupLoads
[$group] ) ?
$group : self
::GROUP_GENERIC
;
239 $this->id
= $nextId = ( is_int( $nextId ) ?
$nextId++
: mt_rand() );
240 $this->ownerId
= $params['ownerId'] ??
null;
243 private static function newTrackedConnectionsArray() {
245 // Connection were transaction rounds may be applied
246 self
::KEY_LOCAL
=> [],
247 self
::KEY_FOREIGN_INUSE
=> [],
248 self
::KEY_FOREIGN_FREE
=> [],
249 // Auto-committing counterpart connections that ignore transaction rounds
250 self
::KEY_LOCAL_NOROUND
=> [],
251 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
252 self
::KEY_FOREIGN_FREE_NOROUND
=> []
256 public function getLocalDomainID() {
257 return $this->localDomain
->getId();
260 public function resolveDomainID( $domain ) {
261 if ( $domain === $this->localDomainIdAlias ||
$domain === false ) {
262 // Local connection requested via some backwards-compatibility domain alias
263 return $this->getLocalDomainID();
266 return (string)$domain;
270 * Resolve $groups into a list of query groups defining as having database servers
272 * @param string[]|string|bool $groups Query group(s) in preference order, [], or false
273 * @param int $i Specific server index or DB_MASTER/DB_REPLICA
274 * @return string[] Non-empty group list in preference order with the default group appended
276 private function resolveGroups( $groups, $i ) {
277 // If a specific replica server was specified, then $groups makes no sense
278 if ( $i > 0 && $groups !== [] && $groups !== false ) {
279 $list = implode( ', ', (array)$groups );
280 throw new LogicException( "Query group(s) ($list) given with server index (#$i)" );
283 if ( $groups === [] ||
$groups === false ||
$groups === $this->defaultGroup
) {
284 $resolvedGroups = [ $this->defaultGroup
]; // common case
285 } elseif ( is_string( $groups ) && isset( $this->groupLoads
[$groups] ) ) {
286 $resolvedGroups = [ $groups, $this->defaultGroup
];
287 } elseif ( is_array( $groups ) ) {
288 $resolvedGroups = array_keys( array_flip( $groups ) +
[ self
::GROUP_GENERIC
=> 1 ] );
290 $resolvedGroups = [ $this->defaultGroup
];
293 return $resolvedGroups;
297 * @param int $flags Bitfield of class CONN_* constants
298 * @param int $i Specific server index or DB_MASTER/DB_REPLICA
299 * @return int Sanitized bitfield
301 private function sanitizeConnectionFlags( $flags, $i ) {
302 // Whether an outside caller is explicitly requesting the master database server
303 if ( $i === self
::DB_MASTER ||
$i === $this->getWriterIndex() ) {
304 $flags |
= self
::CONN_INTENT_WRITABLE
;
307 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
) {
308 // Callers use CONN_TRX_AUTOCOMMIT to bypass REPEATABLE-READ staleness without
309 // resorting to row locks (e.g. FOR UPDATE) or to make small out-of-band commits
310 // during larger transactions. This is useful for avoiding lock contention.
312 // Master DB server attributes (should match those of the replica DB servers)
313 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
314 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
315 // The RDBMS does not support concurrent writes (e.g. SQLite), so attempts
316 // to use separate connections would just cause self-deadlocks. Note that
317 // REPEATABLE-READ staleness is not an issue since DB-level locking means
318 // that transactions are Strict Serializable anyway.
319 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
320 $type = $this->getServerType( $this->getWriterIndex() );
321 $this->connLogger
->info( __METHOD__
. ": CONN_TRX_AUTOCOMMIT disallowed ($type)" );
329 * @param IDatabase $conn
331 * @throws DBUnexpectedError
333 private function enforceConnectionFlags( IDatabase
$conn, $flags ) {
334 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
) {
335 if ( $conn->trxLevel() ) { // sanity
336 throw new DBUnexpectedError(
338 'Handle requested with CONN_TRX_AUTOCOMMIT yet it has a transaction'
342 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
347 * Get a LoadMonitor instance
349 * @return ILoadMonitor
351 private function getLoadMonitor() {
352 if ( !isset( $this->loadMonitor
) ) {
354 'LoadMonitor' => LoadMonitor
::class,
355 'LoadMonitorNull' => LoadMonitorNull
::class,
356 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
359 $class = $this->loadMonitorConfig
['class'];
360 if ( isset( $compat[$class] ) ) {
361 $class = $compat[$class];
364 $this->loadMonitor
= new $class(
365 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
366 $this->loadMonitor
->setLogger( $this->replLogger
);
369 return $this->loadMonitor
;
373 * @param array $loads
374 * @param bool|string $domain Domain to get non-lagged for
375 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
376 * @return bool|int|string
378 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
379 $lags = $this->getLagTimes( $domain );
381 # Unset excessively lagged servers
382 foreach ( $lags as $i => $lag ) {
383 if ( $i !== $this->getWriterIndex() ) {
384 # How much lag this server nominally is allowed to have
385 $maxServerLag = $this->servers
[$i]['max lag'] ??
$this->maxLag
; // default
386 # Constrain that futher by $maxLag argument
387 $maxServerLag = min( $maxServerLag, $maxLag );
389 $host = $this->getServerName( $i );
390 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
391 $this->replLogger
->debug(
393 ": server {host} is not replicating?", [ 'host' => $host ] );
395 } elseif ( $lag > $maxServerLag ) {
396 $this->replLogger
->debug(
398 ": server {host} has {lag} seconds of lag (>= {maxlag})",
399 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
406 # Find out if all the replica DBs with non-zero load are lagged
408 foreach ( $loads as $load ) {
412 # No appropriate DB servers except maybe the master and some replica DBs with zero load
413 # Do NOT use the master
414 # Instead, this function will return false, triggering read-only mode,
415 # and a lagged replica DB will be used instead.
419 if ( count( $loads ) == 0 ) {
423 # Return a random representative of the remainder
424 return ArrayUtils
::pickRandom( $loads );
428 * Get the server index to use for a specified server index and query group list
430 * @param int $i Specific server index or DB_MASTER/DB_REPLICA
431 * @param string[] $groups Non-empty query group list in preference order
432 * @param string|bool $domain
433 * @return int A specific server index (replica DBs are checked for connectivity)
435 private function getConnectionIndex( $i, array $groups, $domain ) {
436 if ( $i === self
::DB_MASTER
) {
437 $i = $this->getWriterIndex();
438 } elseif ( $i === self
::DB_REPLICA
) {
439 foreach ( $groups as $group ) {
440 $groupIndex = $this->getReaderIndex( $group, $domain );
441 if ( $groupIndex !== false ) {
442 $i = $groupIndex; // group connection succeeded
446 } elseif ( !isset( $this->servers
[$i] ) ) {
447 throw new UnexpectedValueException( "Invalid server index index #$i" );
450 if ( $i === self
::DB_REPLICA
) {
451 $this->lastError
= 'Unknown error'; // set here in case of worse failure
452 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
453 $this->reportConnectionError();
454 return null; // unreachable due to exception
460 public function getReaderIndex( $group = false, $domain = false ) {
461 if ( $this->getServerCount() == 1 ) {
462 // Skip the load balancing if there's only one server
463 return $this->getWriterIndex();
466 $group = is_string( $group ) ?
$group : self
::GROUP_GENERIC
;
468 $index = $this->getExistingReaderIndex( $group );
470 // A reader index was already selected and "waitForPos" was handled
474 // Use the server weight array for this load group
475 if ( isset( $this->groupLoads
[$group] ) ) {
476 $loads = $this->groupLoads
[$group];
478 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
483 // Scale the configured load ratios according to each server's load and state
484 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
486 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
487 $this->lazyLoadReplicationPositions(); // optimizes server candidate selection
488 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
489 if ( $i === false ) {
490 // DB connection unsuccessful
494 // If data seen by queries is expected to reflect the transactions committed as of
495 // or after a given replication position then wait for the DB to apply those changes
496 if ( $this->waitForPos
&& $i !== $this->getWriterIndex() && !$this->doWait( $i ) ) {
497 // Data will be outdated compared to what was expected
498 $laggedReplicaMode = true;
501 // Cache the reader index for future DB_REPLICA handles
502 $this->setExistingReaderIndex( $group, $i );
503 // Record whether the generic reader index is in "lagged replica DB" mode
504 if ( $group === self
::GROUP_GENERIC
&& $laggedReplicaMode ) {
505 $this->laggedReplicaMode
= true;
508 $serverName = $this->getServerName( $i );
509 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
515 * Get the server index chosen by the load balancer for use with the given query group
517 * @param string $group Query group; use false for the generic group
518 * @return int Server index or -1 if none was chosen
520 protected function getExistingReaderIndex( $group ) {
521 return $this->readIndexByGroup
[$group] ??
-1;
525 * Set the server index chosen by the load balancer for use with the given query group
527 * @param string $group Query group; use false for the generic group
528 * @param int $index The index of a specific server
530 private function setExistingReaderIndex( $group, $index ) {
532 throw new UnexpectedValueException( "Cannot set a negative read server index" );
534 $this->readIndexByGroup
[$group] = $index;
538 * @param array $loads List of server weights
539 * @param string|bool $domain
540 * @return array (reader index, lagged replica mode) or (false, false) on failure
542 private function pickReaderIndex( array $loads, $domain = false ) {
543 if ( $loads === [] ) {
544 throw new InvalidArgumentException( "Server configuration array is empty" );
547 /** @var int|bool $i Index of selected server */
549 /** @var bool $laggedReplicaMode Whether server is considered lagged */
550 $laggedReplicaMode = false;
552 // Quickly look through the available servers for a server that meets criteria...
553 $currentLoads = $loads;
554 while ( count( $currentLoads ) ) {
555 if ( $this->allowLagged ||
$laggedReplicaMode ) {
556 $i = ArrayUtils
::pickRandom( $currentLoads );
559 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
560 $this->replLogger
->debug( __METHOD__
. ": replication positions detected" );
561 // "chronologyCallback" sets "waitForPos" for session consistency.
562 // This triggers doWait() after connect, so it's especially good to
563 // avoid lagged servers so as to avoid excessive delay in that method.
564 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
565 // Aim for <= 1 second of waiting (being too picky can backfire)
566 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
568 if ( $i === false ) {
569 // Any server with less lag than it's 'max lag' param is preferable
570 $i = $this->getRandomNonLagged( $currentLoads, $domain );
572 if ( $i === false && count( $currentLoads ) ) {
573 // All replica DBs lagged. Switch to read-only mode
574 $this->replLogger
->error(
575 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
576 $i = ArrayUtils
::pickRandom( $currentLoads );
577 $laggedReplicaMode = true;
581 if ( $i === false ) {
582 // pickRandom() returned false.
583 // This is permanent and means the configuration or the load monitor
584 // wants us to return false.
585 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
587 return [ false, false ];
590 $serverName = $this->getServerName( $i );
591 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
593 // Get a connection to this server without triggering other server connections
594 $conn = $this->getServerConnection( $i, $domain, self
::CONN_SILENCE_ERRORS
);
596 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
597 unset( $currentLoads[$i] ); // avoid this server next iteration
602 // Decrement reference counter, we are finished with this connection.
603 // It will be incremented for the caller later.
604 if ( $domain !== false ) {
605 $this->reuseConnection( $conn );
608 // Return this server
612 // If all servers were down, quit now
613 if ( $currentLoads === [] ) {
614 $this->connLogger
->error( __METHOD__
. ": all servers down" );
617 return [ $i, $laggedReplicaMode ];
620 public function waitFor( $pos ) {
621 $oldPos = $this->waitForPos
;
623 $this->waitForPos
= $pos;
624 // If a generic reader connection was already established, then wait now
625 $i = $this->getExistingReaderIndex( self
::GROUP_GENERIC
);
626 if ( $i > 0 && !$this->doWait( $i ) ) {
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->getExistingReaderIndex( self
::GROUP_GENERIC
);
643 // Pick a generic replica DB if there isn't one yet
644 $readLoads = $this->groupLoads
[self
::GROUP_GENERIC
];
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; this is used for throttling, not lag-protection
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->serverHasLoadInAnyGroup( $i ) ) {
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; this is used for throttling, not lag-protection
684 $this->waitForPos
= $oldPos;
691 * @param int $i Specific server index
694 private function serverHasLoadInAnyGroup( $i ) {
695 foreach ( $this->groupLoads
as $loadsByIndex ) {
696 if ( ( $loadsByIndex[$i] ??
0 ) > 0 ) {
705 * @param DBMasterPos|bool $pos
707 private function setWaitForPositionIfHigher( $pos ) {
712 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
713 $this->waitForPos
= $pos;
717 public function getAnyOpenConnection( $i, $flags = 0 ) {
718 $i = ( $i === self
::DB_MASTER
) ?
$this->getWriterIndex() : $i;
719 // Connection handles required to be in auto-commit mode use a separate connection
720 // pool since the main pool is effected by implicit and explicit transaction rounds
721 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
724 foreach ( $this->conns
as $connsByServer ) {
725 // Get the connection array server indexes to inspect
726 if ( $i === self
::DB_REPLICA
) {
727 $indexes = array_keys( $connsByServer );
729 $indexes = isset( $connsByServer[$i] ) ?
[ $i ] : [];
732 foreach ( $indexes as $index ) {
733 $conn = $this->pickAnyOpenConnection( $connsByServer[$index], $autocommit );
741 $this->enforceConnectionFlags( $conn, $flags );
748 * @param IDatabase[] $candidateConns
749 * @param bool $autocommit Whether to only look for auto-commit connections
750 * @return IDatabase|false An appropriate open connection or false if none found
752 private function pickAnyOpenConnection( $candidateConns, $autocommit ) {
755 foreach ( $candidateConns as $candidateConn ) {
756 if ( !$candidateConn->isOpen() ) {
757 continue; // some sort of error occured?
761 // Connection is transaction round aware
762 !$candidateConn->getLBInfo( 'autoCommitOnly' ) ||
763 // Some sort of error left a transaction open?
764 $candidateConn->trxLevel()
767 continue; // some sort of error left a transaction open?
770 $conn = $candidateConn;
777 * Wait for a given replica DB to catch up to the master pos stored in "waitForPos"
778 * @param int $index Specific server index
779 * @param bool $open Check the server even if a new connection has to be made
780 * @param int|null $timeout Max seconds to wait; default is "waitTimeout"
783 protected function doWait( $index, $open = false, $timeout = null ) {
784 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
786 // Check if we already know that the DB has reached this point
787 $server = $this->getServerName( $index );
788 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
789 /** @var DBMasterPos $knownReachedPos */
790 $knownReachedPos = $this->srvCache
->get( $key );
792 $knownReachedPos instanceof DBMasterPos
&&
793 $knownReachedPos->hasReached( $this->waitForPos
)
795 $this->replLogger
->debug(
797 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
798 [ 'dbserver' => $server ]
803 // Find a connection to wait on, creating one if needed and allowed
804 $close = false; // close the connection afterwards
805 $flags = self
::CONN_SILENCE_ERRORS
;
806 $conn = $this->getAnyOpenConnection( $index, $flags );
809 $this->replLogger
->debug(
810 __METHOD__
. ': no connection open for {dbserver}',
811 [ 'dbserver' => $server ]
816 // Get a connection to this server without triggering other server connections
817 $conn = $this->getServerConnection( $index, self
::DOMAIN_ANY
, $flags );
819 $this->replLogger
->warning(
820 __METHOD__
. ': failed to connect to {dbserver}',
821 [ 'dbserver' => $server ]
826 // Avoid connection spam in waitForAll() when connections
827 // are made just for the sake of doing this lag check.
831 $this->replLogger
->info(
833 ': waiting for replica DB {dbserver} to catch up...',
834 [ 'dbserver' => $server ]
837 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
839 if ( $result === null ) {
840 $this->replLogger
->warning(
841 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
844 'pos' => $this->waitForPos
,
845 'trace' => ( new RuntimeException() )->getTraceAsString()
849 } elseif ( $result == -1 ) {
850 $this->replLogger
->warning(
851 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
854 'pos' => $this->waitForPos
,
855 'trace' => ( new RuntimeException() )->getTraceAsString()
860 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
862 // Remember that the DB reached this point
863 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
867 $this->closeConnection( $conn );
873 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
874 $domain = $this->resolveDomainID( $domain );
875 $groups = $this->resolveGroups( $groups, $i );
876 $flags = $this->sanitizeConnectionFlags( $flags, $i );
877 // If given DB_MASTER/DB_REPLICA, resolve it to a specific server index. Resolving
878 // DB_REPLICA might trigger getServerConnection() calls due to the getReaderIndex()
879 // connectivity checks or LoadMonitor::scaleLoads() server state cache regeneration.
880 // The use of getServerConnection() instead of getConnection() avoids infinite loops.
881 $serverIndex = $this->getConnectionIndex( $i, $groups, $domain );
882 // Get an open connection to that server (might trigger a new connection)
883 $conn = $this->getServerConnection( $serverIndex, $domain, $flags );
884 // Set master DB handles as read-only if there is high replication lag
885 if ( $serverIndex === $this->getWriterIndex() && $this->getLaggedReplicaMode( $domain ) ) {
886 $reason = ( $this->getExistingReaderIndex( self
::GROUP_GENERIC
) >= 0 )
887 ?
'The database is read-only until replication lag decreases.'
888 : 'The database is read-only until replica database servers becomes reachable.';
889 $conn->setLBInfo( 'readOnlyReason', $reason );
896 * @param int $i Specific server index
897 * @param string $domain Resolved DB domain
898 * @param int $flags Bitfield of class CONN_* constants
899 * @return IDatabase|bool
900 * @throws InvalidArgumentException When the server index is invalid
902 public function getServerConnection( $i, $domain, $flags = 0 ) {
903 // Number of connections made before getting the server index and handle
904 $priorConnectionsMade = $this->connectionCounter
;
905 // Get an open connection to this server (might trigger a new connection)
906 $conn = $this->localDomain
->equals( $domain )
907 ?
$this->getLocalConnection( $i, $flags )
908 : $this->getForeignConnection( $i, $domain, $flags );
909 // Throw an error or otherwise bail out if the connection attempt failed
910 if ( !( $conn instanceof IDatabase
) ) {
911 if ( ( $flags & self
::CONN_SILENCE_ERRORS
) != self
::CONN_SILENCE_ERRORS
) {
912 $this->reportConnectionError();
918 // Profile any new connections caused by this method
919 if ( $this->connectionCounter
> $priorConnectionsMade ) {
920 $this->trxProfiler
->recordConnection(
923 ( ( $flags & self
::CONN_INTENT_WRITABLE
) == self
::CONN_INTENT_WRITABLE
)
927 if ( !$conn->isOpen() ) {
928 $this->errorConnection
= $conn;
929 // Connection was made but later unrecoverably lost for some reason.
930 // Do not return a handle that will just throw exceptions on use, but
931 // let the calling code, e.g. getReaderIndex(), try another server.
935 // Make sure that flags like CONN_TRX_AUTOCOMMIT are respected by this handle
936 $this->enforceConnectionFlags( $conn, $flags );
937 // Set master DB handles as read-only if the load balancer is configured as read-only
938 // or the master database server is running in server-side read-only mode. Note that
939 // replica DB handles are always read-only via Database::assertIsWritableMaster().
940 // Read-only mode due to replication lag is *avoided* here to avoid recursion.
941 if ( $conn->getLBInfo( 'serverIndex' ) === $this->getWriterIndex() ) {
942 if ( $this->readOnlyReason
!== false ) {
943 $conn->setLBInfo( 'readOnlyReason', $this->readOnlyReason
);
944 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
947 'The master database server is running in read-only mode.'
955 public function reuseConnection( IDatabase
$conn ) {
956 $serverIndex = $conn->getLBInfo( 'serverIndex' );
957 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
958 if ( $serverIndex === null ||
$refCount === null ) {
959 return; // non-foreign connection; no domain-use tracking to update
960 } elseif ( $conn instanceof DBConnRef
) {
961 // DBConnRef already handles calling reuseConnection() and only passes the live
962 // Database instance to this method. Any caller passing in a DBConnRef is broken.
963 $this->connLogger
->error(
964 __METHOD__
. ": got DBConnRef instance.\n" .
965 ( new LogicException() )->getTraceAsString() );
970 if ( $this->disabled
) {
971 return; // DBConnRef handle probably survived longer than the LoadBalancer
974 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
975 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
976 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
978 $connFreeKey = self
::KEY_FOREIGN_FREE
;
979 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
982 $domain = $conn->getDomainID();
983 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
984 throw new InvalidArgumentException(
985 "Connection $serverIndex/$domain not found; it may have already been freed" );
986 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
987 throw new InvalidArgumentException(
988 "Connection $serverIndex/$domain mismatched; it may have already been freed" );
991 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
992 if ( $refCount <= 0 ) {
993 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
994 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
995 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
996 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
998 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
1000 $this->connLogger
->debug( __METHOD__
.
1001 ": reference count for $serverIndex/$domain reduced to $refCount" );
1005 public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1006 $domain = $this->resolveDomainID( $domain );
1007 $role = $this->getRoleFromIndex( $i );
1009 return new DBConnRef( $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
1012 public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1013 $domain = $this->resolveDomainID( $domain );
1014 $role = $this->getRoleFromIndex( $i );
1016 return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role );
1019 public function getMaintenanceConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1020 $domain = $this->resolveDomainID( $domain );
1021 $role = $this->getRoleFromIndex( $i );
1023 return new MaintainableDBConnRef(
1024 $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
1028 * @param int $i Server index or DB_MASTER/DB_REPLICA
1029 * @return int One of DB_MASTER/DB_REPLICA
1031 private function getRoleFromIndex( $i ) {
1032 return ( $i === self
::DB_MASTER ||
$i === $this->getWriterIndex() )
1039 * @param string|bool $domain
1041 * @return Database|bool Live database handle or false on failure
1042 * @deprecated Since 1.34 Use getConnection() instead
1044 public function openConnection( $i, $domain = false, $flags = 0 ) {
1045 return $this->getConnection( $i, [], $domain, $flags | self
::CONN_SILENCE_ERRORS
);
1049 * Open a connection to a local DB, or return one if it is already open.
1051 * On error, returns false, and the connection which caused the
1052 * error will be available via $this->errorConnection.
1054 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
1056 * @param int $i Specific server index
1057 * @param int $flags Class CONN_* constant bitfield
1059 * @throws InvalidArgumentException When the server index is invalid
1060 * @throws UnexpectedValueException When the DB domain of the connection is corrupted
1062 private function getLocalConnection( $i, $flags = 0 ) {
1063 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
1064 // Connection handles required to be in auto-commit mode use a separate connection
1065 // pool since the main pool is effected by implicit and explicit transaction rounds
1066 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
1068 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
1069 $conn = $this->conns
[$connKey][$i][0];
1071 $conn = $this->reallyOpenConnection(
1074 [ 'autoCommitOnly' => $autoCommit ]
1076 if ( $conn->isOpen() ) {
1077 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i" );
1078 $this->conns
[$connKey][$i][0] = $conn;
1080 $this->connLogger
->warning( __METHOD__
. ": connection error for $i" );
1081 $this->errorConnection
= $conn;
1086 // Sanity check to make sure that the right domain is selected
1088 $conn instanceof IDatabase
&&
1089 !$this->localDomain
->isCompatible( $conn->getDomainID() )
1091 throw new UnexpectedValueException(
1092 "Got connection to '{$conn->getDomainID()}', " .
1093 "but expected local domain ('{$this->localDomain}')"
1101 * Open a connection to a foreign DB, or return one if it is already open.
1103 * Increments a reference count on the returned connection which locks the
1104 * connection to the requested domain. This reference count can be
1105 * decremented by calling reuseConnection().
1107 * If a connection is open to the appropriate server already, but with the wrong
1108 * database, it will be switched to the right database and returned, as long as
1109 * it has been freed first with reuseConnection().
1111 * On error, returns false, and the connection which caused the
1112 * error will be available via $this->errorConnection.
1114 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
1116 * @param int $i Specific server index
1117 * @param string $domain Domain ID to open
1118 * @param int $flags Class CONN_* constant bitfield
1119 * @return Database|bool Returns false on connection error
1120 * @throws DBError When database selection fails
1121 * @throws InvalidArgumentException When the server index is invalid
1122 * @throws UnexpectedValueException When the DB domain of the connection is corrupted
1124 private function getForeignConnection( $i, $domain, $flags = 0 ) {
1125 $domainInstance = DatabaseDomain
::newFromId( $domain );
1126 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
1127 // Connection handles required to be in auto-commit mode use a separate connection
1128 // pool since the main pool is effected by implicit and explicit transaction rounds
1129 if ( $autoCommit ) {
1130 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
1131 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
1133 $connFreeKey = self
::KEY_FOREIGN_FREE
;
1134 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
1137 /** @var Database $conn */
1140 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
1141 // Reuse an in-use connection for the same domain
1142 $conn = $this->conns
[$connInUseKey][$i][$domain];
1143 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
1144 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
1145 // Reuse a free connection for the same domain
1146 $conn = $this->conns
[$connFreeKey][$i][$domain];
1147 unset( $this->conns
[$connFreeKey][$i][$domain] );
1148 $this->conns
[$connInUseKey][$i][$domain] = $conn;
1149 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
1150 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
1151 // Reuse a free connection from another domain if possible
1152 foreach ( $this->conns
[$connFreeKey][$i] as $oldDomain => $conn ) {
1153 if ( $domainInstance->getDatabase() !== null ) {
1154 // Check if changing the database will require a new connection.
1155 // In that case, leave the connection handle alone and keep looking.
1156 // This prevents connections from being closed mid-transaction and can
1157 // also avoid overhead if the same database will later be requested.
1159 $conn->databasesAreIndependent() &&
1160 $conn->getDBname() !== $domainInstance->getDatabase()
1164 // Select the new database, schema, and prefix
1165 $conn->selectDomain( $domainInstance );
1167 // Stay on the current database, but update the schema/prefix
1168 $conn->dbSchema( $domainInstance->getSchema() );
1169 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1171 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
1172 // Note that if $domain is an empty string, getDomainID() might not match it
1173 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1174 $this->connLogger
->debug( __METHOD__
.
1175 ": reusing free connection from $oldDomain for $domain" );
1181 $conn = $this->reallyOpenConnection(
1185 'autoCommitOnly' => $autoCommit,
1187 'foreignPoolRefCount' => 0
1190 if ( $conn->isOpen() ) {
1191 // Note that if $domain is an empty string, getDomainID() might not match it
1192 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1193 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1195 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
1196 $this->errorConnection
= $conn;
1201 if ( $conn instanceof IDatabase
) {
1202 // Sanity check to make sure that the right domain is selected
1203 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1204 throw new UnexpectedValueException(
1205 "Got connection to '{$conn->getDomainID()}', but expected '$domain'" );
1207 // Increment reference count
1208 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1209 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1215 public function getServerAttributes( $i ) {
1216 return Database
::attributesFromType(
1217 $this->getServerType( $i ),
1218 $this->servers
[$i]['driver'] ??
null
1223 * Test if the specified index represents an open connection
1225 * @param int $index Server index
1228 private function isOpen( $index ) {
1229 return (bool)$this->getAnyOpenConnection( $index );
1233 * Open a new network connection to a server (uncached)
1235 * Returns a Database object whether or not the connection was successful.
1237 * @param int $i Specific server index
1238 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
1239 * @param array $lbInfo Additional information for setLBInfo()
1241 * @throws DBAccessError
1242 * @throws InvalidArgumentException
1244 protected function reallyOpenConnection( $i, DatabaseDomain
$domain, array $lbInfo ) {
1245 if ( $this->disabled
) {
1246 throw new DBAccessError();
1249 $server = $this->getServerInfoStrict( $i );
1250 $server = array_merge( $server, [
1251 // Use the database specified in $domain (null means "none or entrypoint DB");
1252 // fallback to the $server default if the RDBMs is an embedded library using a file
1253 // on disk since there would be nothing to access to without a DB/file name.
1254 'dbname' => $this->getServerAttributes( $i )[Database
::ATTR_DB_IS_FILE
]
1255 ?
( $domain->getDatabase() ??
$server['dbname'] ??
null )
1256 : $domain->getDatabase(),
1257 // Override the $server default schema with that of $domain if specified
1258 'schema' => $domain->getSchema() ??
$server['schema'] ??
null,
1259 // Use the table prefix specified in $domain
1260 'tablePrefix' => $domain->getTablePrefix(),
1261 // Participate in transaction rounds if $server does not specify otherwise
1262 'flags' => $server['flags'] ?? IDatabase
::DBO_DEFAULT
,
1263 // Inject the PHP execution mode and the agent string
1264 'cliMode' => $this->cliMode
,
1265 'agent' => $this->agent
,
1266 // Inject object and callback dependencies
1267 'srvCache' => $this->srvCache
,
1268 'connLogger' => $this->connLogger
,
1269 'queryLogger' => $this->queryLogger
,
1270 'errorLogger' => $this->errorLogger
,
1271 'deprecationLogger' => $this->deprecationLogger
,
1272 'profiler' => $this->profiler
,
1273 'trxProfiler' => $this->trxProfiler
1276 $lbInfo = array_merge( $lbInfo, [
1277 'ownerId' => $this->id
,
1278 'serverIndex' => $i,
1279 'master' => ( $i === $this->getWriterIndex() ),
1280 'replica' => ( $i !== $this->getWriterIndex() ),
1281 // Name of the master server of the relevant DB cluster (e.g. "db1052")
1282 'clusterMasterHost' => $this->getServerName( $this->getWriterIndex() )
1285 $conn = Database
::factory( $server['type'], $server, Database
::NEW_UNCONNECTED
);
1287 $conn->initConnection();
1288 ++
$this->connectionCounter
;
1289 } catch ( DBConnectionError
$e ) {
1290 // ignore; let the DB handle the logging
1293 $conn->setLBInfo( $lbInfo );
1294 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1295 if ( $this->cliMode
) {
1296 $conn->clearFlag( $conn::DBO_TRX
);
1298 $conn->setFlag( $conn::DBO_TRX
);
1301 if ( $i === $this->getWriterIndex() ) {
1302 if ( $this->trxRoundId
!== false ) {
1303 $this->applyTransactionRoundFlags( $conn );
1305 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1306 $conn->setTransactionListener( $name, $callback );
1309 $conn->setTableAliases( $this->tableAliases
);
1310 $conn->setIndexAliases( $this->indexAliases
);
1312 $conn->setLazyMasterHandle(
1313 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $conn->getDomainID() )
1316 $this->lazyLoadReplicationPositions(); // session consistency
1318 // Log when many connection are made on requests
1319 $count = $this->getCurrentConnectionCount();
1320 if ( $count >= self
::CONN_HELD_WARN_THRESHOLD
) {
1321 $this->perfLogger
->warning(
1322 __METHOD__
. ": {connections}+ connections made (master={masterdb})",
1324 'connections' => $count,
1325 'dbserver' => $conn->getServer(),
1326 'masterdb' => $conn->getLBInfo( 'clusterMasterHost' )
1335 * Make sure that any "waitForPos" positions are loaded and available to doWait()
1337 private function lazyLoadReplicationPositions() {
1338 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
1339 $this->connectionAttempted
= true;
1340 ( $this->chronologyCallback
)( $this ); // generally calls waitFor()
1341 $this->connLogger
->debug( __METHOD__
. ': executed chronology callback.' );
1346 * @throws DBConnectionError
1348 private function reportConnectionError() {
1349 $conn = $this->errorConnection
; // the connection which caused the error
1351 'method' => __METHOD__
,
1352 'last_error' => $this->lastError
,
1355 if ( $conn instanceof IDatabase
) {
1356 $context['db_server'] = $conn->getServer();
1357 $this->connLogger
->warning(
1358 __METHOD__
. ": connection error: {last_error} ({db_server})",
1362 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1364 // No last connection, probably due to all servers being too busy
1365 $this->connLogger
->error(
1367 ": LB failure with no last connection. Connection error: {last_error}",
1371 // If all servers were busy, "lastError" will contain something sensible
1372 throw new DBConnectionError( null, $this->lastError
);
1376 public function getWriterIndex() {
1381 * Returns true if the specified index is a valid server index
1385 * @deprecated Since 1.34
1387 public function haveIndex( $i ) {
1388 return array_key_exists( $i, $this->servers
);
1392 * Returns true if the specified index is valid and has non-zero load
1396 * @deprecated Since 1.34
1398 public function isNonZeroLoad( $i ) {
1399 return ( isset( $this->servers
[$i] ) && $this->groupLoads
[self
::GROUP_GENERIC
][$i] > 0 );
1402 public function getServerCount() {
1403 return count( $this->servers
);
1406 public function hasReplicaServers() {
1407 return ( $this->getServerCount() > 1 );
1410 public function hasStreamingReplicaServers() {
1411 foreach ( $this->servers
as $i => $server ) {
1412 if ( $i !== $this->getWriterIndex() && empty( $server['is static'] ) ) {
1420 public function getServerName( $i ) {
1421 $name = $this->servers
[$i]['hostName'] ??
( $this->servers
[$i]['host'] ??
'' );
1423 return ( $name != '' ) ?
$name : 'localhost';
1426 public function getServerInfo( $i ) {
1427 return $this->servers
[$i] ??
false;
1430 public function getServerType( $i ) {
1431 return $this->servers
[$i]['type'] ??
'unknown';
1434 public function getMasterPos() {
1435 $index = $this->getWriterIndex();
1437 $conn = $this->getAnyOpenConnection( $index );
1439 return $conn->getMasterPos();
1442 $conn = $this->getConnection( $index, self
::CONN_SILENCE_ERRORS
);
1444 $this->reportConnectionError();
1445 return null; // unreachable due to exception
1449 $pos = $conn->getMasterPos();
1451 $this->closeConnection( $conn );
1457 public function getReplicaResumePos() {
1458 // Get the position of any existing master server connection
1459 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1460 if ( $masterConn ) {
1461 return $masterConn->getMasterPos();
1464 // Get the highest position of any existing replica server connection
1465 $highestPos = false;
1466 $serverCount = $this->getServerCount();
1467 for ( $i = 1; $i < $serverCount; $i++
) {
1468 if ( !empty( $this->servers
[$i]['is static'] ) ) {
1469 continue; // server does not use replication
1472 $conn = $this->getAnyOpenConnection( $i );
1473 $pos = $conn ?
$conn->getReplicaPos() : false;
1475 continue; // no open connection or could not get position
1478 $highestPos = $highestPos ?
: $pos;
1479 if ( $pos->hasReached( $highestPos ) ) {
1487 public function disable() {
1489 $this->disabled
= true;
1492 public function closeAll() {
1493 $fname = __METHOD__
;
1494 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( $fname ) {
1495 $host = $conn->getServer();
1496 $this->connLogger
->debug(
1497 $fname . ": closing connection to database '$host'." );
1501 $this->conns
= self
::newTrackedConnectionsArray();
1504 public function closeConnection( IDatabase
$conn ) {
1505 if ( $conn instanceof DBConnRef
) {
1506 // Avoid calling close() but still leaving the handle in the pool
1507 throw new RuntimeException( 'Cannot close DBConnRef instance; it must be shareable' );
1510 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1511 foreach ( $this->conns
as $type => $connsByServer ) {
1512 if ( !isset( $connsByServer[$serverIndex] ) ) {
1516 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1517 if ( $conn === $trackedConn ) {
1518 $host = $this->getServerName( $i );
1519 $this->connLogger
->debug(
1520 __METHOD__
. ": closing connection to database $i at '$host'." );
1521 unset( $this->conns
[$type][$serverIndex][$i] );
1530 public function commitAll( $fname = __METHOD__
, $owner = null ) {
1531 $this->commitMasterChanges( $fname, $owner );
1532 $this->flushMasterSnapshots( $fname );
1533 $this->flushReplicaSnapshots( $fname );
1536 public function finalizeMasterChanges( $fname = __METHOD__
, $owner = null ) {
1537 $this->assertOwnership( $fname, $owner );
1538 $this->assertTransactionRoundStage( [ self
::ROUND_CURSORY
, self
::ROUND_FINALIZED
] );
1540 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1541 // Loop until callbacks stop adding callbacks on other connections
1544 $count = 0; // callbacks execution attempts
1545 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$count ) {
1546 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1547 // Any error should cause all (peer) transactions to be rolled back together.
1548 $count +
= $conn->runOnTransactionPreCommitCallbacks();
1551 } while ( $count > 0 );
1552 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1553 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1554 $conn->setTrxEndCallbackSuppression( true );
1556 $this->trxRoundStage
= self
::ROUND_FINALIZED
;
1561 public function approveMasterChanges( array $options, $fname = __METHOD__
, $owner = null ) {
1562 $this->assertOwnership( $fname, $owner );
1563 $this->assertTransactionRoundStage( self
::ROUND_FINALIZED
);
1565 $limit = $options['maxWriteDuration'] ??
0;
1567 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1568 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1569 // If atomic sections or explicit transactions are still open, some caller must have
1570 // caught an exception but failed to properly rollback any changes. Detect that and
1571 // throw and error (causing rollback).
1572 $conn->assertNoOpenTransactions();
1573 // Assert that the time to replicate the transaction will be sane.
1574 // If this fails, then all DB transactions will be rollback back together.
1575 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1576 if ( $limit > 0 && $time > $limit ) {
1577 throw new DBTransactionSizeError(
1579 "Transaction spent $time second(s) in writes, exceeding the limit of $limit",
1583 // If a connection sits idle while slow queries execute on another, that connection
1584 // may end up dropped before the commit round is reached. Ping servers to detect this.
1585 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1586 throw new DBTransactionError(
1588 "A connection to the {$conn->getDBname()} database was lost before commit"
1592 $this->trxRoundStage
= self
::ROUND_APPROVED
;
1595 public function beginMasterChanges( $fname = __METHOD__
, $owner = null ) {
1596 $this->assertOwnership( $fname, $owner );
1597 if ( $this->trxRoundId
!== false ) {
1598 throw new DBTransactionError(
1600 "$fname: Transaction round '{$this->trxRoundId}' already started"
1603 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
1605 // Clear any empty transactions (no writes/callbacks) from the implicit round
1606 $this->flushMasterSnapshots( $fname );
1608 $this->trxRoundId
= $fname;
1609 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1610 // Mark applicable handles as participating in this explicit transaction round.
1611 // For each of these handles, any writes and callbacks will be tied to a single
1612 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1613 // are part of an en masse commit or an en masse rollback.
1614 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1615 $this->applyTransactionRoundFlags( $conn );
1617 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1620 public function commitMasterChanges( $fname = __METHOD__
, $owner = null ) {
1621 $this->assertOwnership( $fname, $owner );
1622 $this->assertTransactionRoundStage( self
::ROUND_APPROVED
);
1626 /** @noinspection PhpUnusedLocalVariableInspection */
1627 $scope = ScopedCallback
::newScopedIgnoreUserAbort(); // try to ignore client aborts
1629 $restore = ( $this->trxRoundId
!== false );
1630 $this->trxRoundId
= false;
1631 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1632 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1633 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1634 $this->forEachOpenMasterConnection(
1635 function ( IDatabase
$conn ) use ( $fname, &$failures ) {
1637 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1638 } catch ( DBError
$e ) {
1639 ( $this->errorLogger
)( $e );
1640 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1645 throw new DBTransactionError(
1647 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1651 // Unmark handles as participating in this explicit transaction round
1652 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1653 $this->undoTransactionRoundFlags( $conn );
1656 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
1659 public function runMasterTransactionIdleCallbacks( $fname = __METHOD__
, $owner = null ) {
1660 $this->assertOwnership( $fname, $owner );
1661 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1662 $type = IDatabase
::TRIGGER_COMMIT
;
1663 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1664 $type = IDatabase
::TRIGGER_ROLLBACK
;
1666 throw new DBTransactionError(
1668 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1672 $oldStage = $this->trxRoundStage
;
1673 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1675 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1676 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1677 $conn->setTrxEndCallbackSuppression( false );
1680 $e = null; // first exception
1681 $fname = __METHOD__
;
1682 // Loop until callbacks stop adding callbacks on other connections
1684 // Run any pending callbacks for each connection...
1685 $count = 0; // callback execution attempts
1686 $this->forEachOpenMasterConnection(
1687 function ( Database
$conn ) use ( $type, &$e, &$count ) {
1688 if ( $conn->trxLevel() ) {
1689 return; // retry in the next iteration, after commit() is called
1692 $count +
= $conn->runOnTransactionIdleCallbacks( $type );
1693 } catch ( Exception
$ex ) {
1698 // Clear out any active transactions left over from callbacks...
1699 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$e, $fname ) {
1700 if ( $conn->writesPending() ) {
1701 // A callback from another handle wrote to this one and DBO_TRX is set
1702 $this->queryLogger
->warning( $fname . ": found writes pending." );
1703 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1704 $this->queryLogger
->warning(
1705 $fname . ": found writes pending ($fnames).",
1707 'db_server' => $conn->getServer(),
1708 'db_name' => $conn->getDBname()
1711 } elseif ( $conn->trxLevel() ) {
1712 // A callback from another handle read from this one and DBO_TRX is set,
1713 // which can easily happen if there is only one DB (no replicas)
1714 $this->queryLogger
->debug( $fname . ": found empty transaction." );
1717 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1718 } catch ( Exception
$ex ) {
1722 } while ( $count > 0 );
1724 $this->trxRoundStage
= $oldStage;
1729 public function runMasterTransactionListenerCallbacks( $fname = __METHOD__
, $owner = null ) {
1730 $this->assertOwnership( $fname, $owner );
1731 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1732 $type = IDatabase
::TRIGGER_COMMIT
;
1733 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1734 $type = IDatabase
::TRIGGER_ROLLBACK
;
1736 throw new DBTransactionError(
1738 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1744 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1745 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1747 $conn->runTransactionListenerCallbacks( $type );
1748 } catch ( Exception
$ex ) {
1752 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1757 public function rollbackMasterChanges( $fname = __METHOD__
, $owner = null ) {
1758 $this->assertOwnership( $fname, $owner );
1760 $restore = ( $this->trxRoundId
!== false );
1761 $this->trxRoundId
= false;
1762 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1763 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1764 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1767 // Unmark handles as participating in this explicit transaction round
1768 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1769 $this->undoTransactionRoundFlags( $conn );
1772 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
1776 * @param string|string[] $stage
1777 * @throws DBTransactionError
1779 private function assertTransactionRoundStage( $stage ) {
1780 $stages = (array)$stage;
1782 if ( !in_array( $this->trxRoundStage
, $stages, true ) ) {
1783 $stageList = implode(
1785 array_map( function ( $v ) {
1789 throw new DBTransactionError(
1791 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1797 * @param string $fname
1798 * @param int|null $owner Owner ID of the caller
1799 * @throws DBTransactionError
1801 private function assertOwnership( $fname, $owner ) {
1802 if ( $this->ownerId
!== null && $owner !== $this->ownerId
) {
1803 throw new DBTransactionError(
1805 "$fname: LoadBalancer is owned by LBFactory #{$this->ownerId} (got '$owner')."
1811 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1813 * Some servers may have neither flag enabled, meaning that they opt out of such
1814 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1815 * when a DB server is used for something like simple key/value storage.
1817 * @param Database $conn
1819 private function applyTransactionRoundFlags( Database
$conn ) {
1820 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1821 return; // transaction rounds do not apply to these connections
1824 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1825 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1826 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1827 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1830 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1831 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1836 * @param Database $conn
1838 private function undoTransactionRoundFlags( Database
$conn ) {
1839 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1840 return; // transaction rounds do not apply to these connections
1843 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1844 $conn->setLBInfo( 'trxRoundId', null ); // remove the round ID
1847 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1848 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1852 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1853 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) use ( $fname ) {
1854 $conn->flushSnapshot( $fname );
1858 public function flushMasterSnapshots( $fname = __METHOD__
) {
1859 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1860 $conn->flushSnapshot( $fname );
1868 public function getTransactionRoundStage() {
1869 return $this->trxRoundStage
;
1872 public function hasMasterConnection() {
1873 return $this->isOpen( $this->getWriterIndex() );
1876 public function hasMasterChanges() {
1878 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1879 $pending |
= $conn->writesOrCallbacksPending();
1882 return (bool)$pending;
1885 public function lastMasterChangeTimestamp() {
1887 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1888 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1894 public function hasOrMadeRecentMasterChanges( $age = null ) {
1895 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1897 return ( $this->hasMasterChanges()
1898 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1901 public function pendingMasterChangeCallers() {
1903 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1904 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1910 public function getLaggedReplicaMode( $domain = false ) {
1911 if ( $this->laggedReplicaMode
) {
1912 return true; // stay in lagged replica mode
1915 if ( $this->hasStreamingReplicaServers() ) {
1916 // This will set "laggedReplicaMode" as needed
1917 $this->getReaderIndex( self
::GROUP_GENERIC
, $domain );
1920 return $this->laggedReplicaMode
;
1923 public function laggedReplicaUsed() {
1924 return $this->laggedReplicaMode
;
1927 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1928 if ( $this->readOnlyReason
!== false ) {
1929 return $this->readOnlyReason
;
1930 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1931 return 'The master database server is running in read-only mode.';
1932 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1933 return ( $this->getExistingReaderIndex( self
::GROUP_GENERIC
) >= 0 )
1934 ?
'The database is read-only until replication lag decreases.'
1935 : 'The database is read-only until a replica database server becomes reachable.';
1942 * @param string $domain Domain ID, or false for the current domain
1943 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1946 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1947 $cache = $this->wanCache
;
1948 $masterServer = $this->getServerName( $this->getWriterIndex() );
1950 return (bool)$cache->getWithSetCallback(
1951 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1952 self
::TTL_CACHE_READONLY
,
1953 function () use ( $domain, $conn ) {
1954 $old = $this->trxProfiler
->setSilenced( true );
1956 $index = $this->getWriterIndex();
1957 $dbw = $conn ?
: $this->getServerConnection( $index, $domain );
1958 $readOnly = (int)$dbw->serverIsReadOnly();
1960 $this->reuseConnection( $dbw );
1962 } catch ( DBError
$e ) {
1965 $this->trxProfiler
->setSilenced( $old );
1969 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1973 public function allowLagged( $mode = null ) {
1974 if ( $mode === null ) {
1975 return $this->allowLagged
;
1977 $this->allowLagged
= $mode;
1979 return $this->allowLagged
;
1982 public function pingAll() {
1984 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1985 if ( !$conn->ping() ) {
1993 public function forEachOpenConnection( $callback, array $params = [] ) {
1994 foreach ( $this->conns
as $connsByServer ) {
1995 foreach ( $connsByServer as $serverConns ) {
1996 foreach ( $serverConns as $conn ) {
1997 $callback( $conn, ...$params );
2003 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
2004 $masterIndex = $this->getWriterIndex();
2005 foreach ( $this->conns
as $connsByServer ) {
2006 if ( isset( $connsByServer[$masterIndex] ) ) {
2007 /** @var IDatabase $conn */
2008 foreach ( $connsByServer[$masterIndex] as $conn ) {
2009 $callback( $conn, ...$params );
2015 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
2016 foreach ( $this->conns
as $connsByServer ) {
2017 foreach ( $connsByServer as $i => $serverConns ) {
2018 if ( $i === $this->getWriterIndex() ) {
2019 continue; // skip master
2021 foreach ( $serverConns as $conn ) {
2022 $callback( $conn, ...$params );
2031 private function getCurrentConnectionCount() {
2033 foreach ( $this->conns
as $connsByServer ) {
2034 foreach ( $connsByServer as $serverConns ) {
2035 $count +
= count( $serverConns );
2042 public function getMaxLag( $domain = false ) {
2047 if ( $this->hasReplicaServers() ) {
2048 $lagTimes = $this->getLagTimes( $domain );
2049 foreach ( $lagTimes as $i => $lag ) {
2050 if ( $this->groupLoads
[self
::GROUP_GENERIC
][$i] > 0 && $lag > $maxLag ) {
2052 $host = $this->getServerInfoStrict( $i, 'host' );
2058 return [ $host, $maxLag, $maxIndex ];
2061 public function getLagTimes( $domain = false ) {
2062 if ( !$this->hasReplicaServers() ) {
2063 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
2066 $knownLagTimes = []; // map of (server index => 0 seconds)
2067 $indexesWithLag = [];
2068 foreach ( $this->servers
as $i => $server ) {
2069 if ( empty( $server['is static'] ) ) {
2070 $indexesWithLag[] = $i; // DB server might have replication lag
2072 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
2076 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
2080 * Get the lag in seconds for a given connection, or zero if this load
2081 * balancer does not have replication enabled.
2083 * This should be used in preference to Database::getLag() in cases where
2084 * replication may not be in use, since there is no way to determine if
2085 * replication is in use at the connection level without running
2086 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
2087 * function instead of Database::getLag() avoids a fatal error in this
2088 * case on many installations.
2090 * @param IDatabase $conn
2091 * @return int|bool Returns false on error
2092 * @deprecated Since 1.34 Use IDatabase::getLag() instead
2094 public function safeGetLag( IDatabase
$conn ) {
2095 if ( $conn->getLBInfo( 'is static' ) ) {
2096 return 0; // static dataset
2097 } elseif ( $conn->getLBInfo( 'serverIndex' ) == $this->getWriterIndex() ) {
2098 return 0; // this is the master
2101 return $conn->getLag();
2104 public function waitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
2105 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
2107 if ( $conn->getLBInfo( 'serverIndex' ) === $this->getWriterIndex() ) {
2108 return true; // not a replica DB server
2112 // Get the current master position, opening a connection if needed
2113 $index = $this->getWriterIndex();
2114 $flags = self
::CONN_SILENCE_ERRORS
;
2115 $masterConn = $this->getAnyOpenConnection( $index, $flags );
2116 if ( $masterConn ) {
2117 $pos = $masterConn->getMasterPos();
2119 $masterConn = $this->getServerConnection( $index, self
::DOMAIN_ANY
, $flags );
2120 if ( !$masterConn ) {
2121 throw new DBReplicationWaitError(
2123 "Could not obtain a master database connection to get the position"
2126 $pos = $masterConn->getMasterPos();
2127 $this->closeConnection( $masterConn );
2131 if ( $pos instanceof DBMasterPos
) {
2132 $start = microtime( true );
2133 $result = $conn->masterPosWait( $pos, $timeout );
2134 $seconds = max( microtime( true ) - $start, 0 );
2135 if ( $result == -1 ||
is_null( $result ) ) {
2136 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos} [{seconds}s]';
2137 $this->replLogger
->warning( $msg, [
2138 'host' => $conn->getServer(),
2140 'seconds' => round( $seconds, 6 ),
2141 'trace' => ( new RuntimeException() )->getTraceAsString()
2145 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
2149 $ok = false; // something is misconfigured
2150 $this->replLogger
->error(
2151 __METHOD__
. ': could not get master pos for {host}',
2153 'host' => $conn->getServer(),
2154 'trace' => ( new RuntimeException() )->getTraceAsString()
2163 * Wait for a replica DB to reach a specified master position
2165 * This will connect to the master to get an accurate position if $pos is not given
2167 * @param IDatabase $conn Replica DB
2168 * @param DBMasterPos|bool $pos Master position; default: current position
2169 * @param int $timeout Timeout in seconds [optional]
2170 * @return bool Success
2172 * @deprecated Since 1.34 Use waitForMasterPos() instead
2174 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
2175 return $this->waitForMasterPos( $conn, $pos, $timeout );
2178 public function setTransactionListener( $name, callable
$callback = null ) {
2180 $this->trxRecurringCallbacks
[$name] = $callback;
2182 unset( $this->trxRecurringCallbacks
[$name] );
2184 $this->forEachOpenMasterConnection(
2185 function ( IDatabase
$conn ) use ( $name, $callback ) {
2186 $conn->setTransactionListener( $name, $callback );
2191 public function setTableAliases( array $aliases ) {
2192 $this->tableAliases
= $aliases;
2195 public function setIndexAliases( array $aliases ) {
2196 $this->indexAliases
= $aliases;
2199 public function setLocalDomainPrefix( $prefix ) {
2200 // Find connections to explicit foreign domains still marked as in-use...
2202 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
2203 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
2204 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
2205 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
2206 $domainsInUse[] = $conn->getDomainID();
2210 // Do not switch connections to explicit foreign domains unless marked as safe
2211 if ( $domainsInUse ) {
2212 $domains = implode( ', ', $domainsInUse );
2213 throw new DBUnexpectedError( null,
2214 "Foreign domain connections are still in use ($domains)" );
2217 $this->setLocalDomain( new DatabaseDomain(
2218 $this->localDomain
->getDatabase(),
2219 $this->localDomain
->getSchema(),
2223 // Update the prefix for all local connections...
2224 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( $prefix ) {
2225 if ( !$conn->getLBInfo( 'foreign' ) ) {
2226 $conn->tablePrefix( $prefix );
2231 public function redefineLocalDomain( $domain ) {
2234 $this->setLocalDomain( DatabaseDomain
::newFromId( $domain ) );
2238 * @param DatabaseDomain $domain
2240 private function setLocalDomain( DatabaseDomain
$domain ) {
2241 $this->localDomain
= $domain;
2242 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
2243 // always true, gracefully handle the case when they fail to account for escaping.
2244 if ( $this->localDomain
->getTablePrefix() != '' ) {
2245 $this->localDomainIdAlias
=
2246 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
2248 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
2253 * @param int $i Server index
2254 * @param string|null $field Server index field [optional]
2255 * @return array|mixed
2256 * @throws InvalidArgumentException
2258 private function getServerInfoStrict( $i, $field = null ) {
2259 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
2260 throw new InvalidArgumentException( "No server with index '$i'" );
2263 if ( $field !== null ) {
2264 if ( !array_key_exists( $field, $this->servers
[$i] ) ) {
2265 throw new InvalidArgumentException( "No field '$field' in server index '$i'" );
2268 return $this->servers
[$i][$field];
2271 return $this->servers
[$i];
2274 function __destruct() {
2275 // Avoid connection leaks for sanity
2281 * @deprecated since 1.29
2283 class_alias( LoadBalancer
::class, 'LoadBalancer' );