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|null Integer ID of the managing LBFactory instance or null if none */
126 /** @var string|bool Explicit DBO_TRX transaction round active or false if none */
127 private $trxRoundId = false;
128 /** @var string Stage of the current transaction round in the transaction round life-cycle */
129 private $trxRoundStage = self
::ROUND_CURSORY
;
131 /** @var int Warn when this many connection are held */
132 const CONN_HELD_WARN_THRESHOLD
= 10;
134 /** @var int Default 'maxLag' when unspecified */
135 const MAX_LAG_DEFAULT
= 6;
136 /** @var int Default 'waitTimeout' when unspecified */
137 const MAX_WAIT_DEFAULT
= 10;
138 /** @var int Seconds to cache master DB server read-only status */
139 const TTL_CACHE_READONLY
= 5;
141 const KEY_LOCAL
= 'local';
142 const KEY_FOREIGN_FREE
= 'foreignFree';
143 const KEY_FOREIGN_INUSE
= 'foreignInUse';
145 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
146 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
147 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
149 /** @var string Transaction round, explicit or implicit, has not finished writing */
150 const ROUND_CURSORY
= 'cursory';
151 /** @var string Transaction round writes are complete and ready for pre-commit checks */
152 const ROUND_FINALIZED
= 'finalized';
153 /** @var string Transaction round passed final pre-commit checks */
154 const ROUND_APPROVED
= 'approved';
155 /** @var string Transaction round was committed and post-commit callbacks must be run */
156 const ROUND_COMMIT_CALLBACKS
= 'commit-callbacks';
157 /** @var string Transaction round was rolled back and post-rollback callbacks must be run */
158 const ROUND_ROLLBACK_CALLBACKS
= 'rollback-callbacks';
159 /** @var string Transaction round encountered an error */
160 const ROUND_ERROR
= 'error';
162 public function __construct( array $params ) {
163 if ( !isset( $params['servers'] ) ||
!count( $params['servers'] ) ) {
164 throw new InvalidArgumentException( 'Missing or empty "servers" parameter' );
169 $this->groupLoads
= [ self
::GROUP_GENERIC
=> [] ];
170 foreach ( $params['servers'] as $i => $server ) {
171 if ( ++
$listKey !== $i ) {
172 throw new UnexpectedValueException( 'List expected for "servers" parameter' );
175 $server['master'] = true;
177 $server['replica'] = true;
179 $this->servers
[$i] = $server;
180 $serverGroupLoads = [ self
::GROUP_GENERIC
=> $server['load'] ];
181 $serverGroupLoads +
= ( $server['groupLoads'] ??
[] );
182 foreach ( $serverGroupLoads as $group => $ratio ) {
183 $this->groupLoads
[$group][$i] = $ratio;
187 $localDomain = isset( $params['localDomain'] )
188 ? DatabaseDomain
::newFromId( $params['localDomain'] )
189 : DatabaseDomain
::newUnspecified();
190 $this->setLocalDomain( $localDomain );
192 $this->waitTimeout
= $params['waitTimeout'] ?? self
::MAX_WAIT_DEFAULT
;
194 $this->conns
= self
::newTrackedConnectionsArray();
195 $this->waitForPos
= false;
196 $this->allowLagged
= false;
198 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
199 $this->readOnlyReason
= $params['readOnlyReason'];
202 $this->maxLag
= $params['maxLag'] ?? self
::MAX_LAG_DEFAULT
;
204 $this->loadMonitorConfig
= $params['loadMonitor'] ??
[ 'class' => 'LoadMonitorNull' ];
205 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
207 $this->srvCache
= $params['srvCache'] ??
new EmptyBagOStuff();
208 $this->wanCache
= $params['wanCache'] ?? WANObjectCache
::newEmpty();
209 $this->profiler
= $params['profiler'] ??
null;
210 $this->trxProfiler
= $params['trxProfiler'] ??
new TransactionProfiler();
212 $this->errorLogger
= $params['errorLogger'] ??
function ( Exception
$e ) {
213 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
215 $this->deprecationLogger
= $params['deprecationLogger'] ??
function ( $msg ) {
216 trigger_error( $msg, E_USER_DEPRECATED
);
219 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
220 $this->$key = $params[$key] ??
new NullLogger();
223 $this->hostname
= $params['hostname'] ??
( gethostname() ?
: 'unknown' );
224 $this->cliMode
= $params['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
225 $this->agent
= $params['agent'] ??
'';
227 if ( isset( $params['chronologyCallback'] ) ) {
228 $this->chronologyCallback
= $params['chronologyCallback'];
231 if ( isset( $params['roundStage'] ) ) {
232 if ( $params['roundStage'] === self
::STAGE_POSTCOMMIT_CALLBACKS
) {
233 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
234 } elseif ( $params['roundStage'] === self
::STAGE_POSTROLLBACK_CALLBACKS
) {
235 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
239 $group = $params['defaultGroup'] ?? self
::GROUP_GENERIC
;
240 $this->defaultGroup
= isset( $this->groupLoads
[$group] ) ?
$group : self
::GROUP_GENERIC
;
242 $this->ownerId
= $params['ownerId'] ??
null;
245 private static function newTrackedConnectionsArray() {
247 // Connection were transaction rounds may be applied
248 self
::KEY_LOCAL
=> [],
249 self
::KEY_FOREIGN_INUSE
=> [],
250 self
::KEY_FOREIGN_FREE
=> [],
251 // Auto-committing counterpart connections that ignore transaction rounds
252 self
::KEY_LOCAL_NOROUND
=> [],
253 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
254 self
::KEY_FOREIGN_FREE_NOROUND
=> []
258 public function getLocalDomainID() {
259 return $this->localDomain
->getId();
262 public function resolveDomainID( $domain ) {
263 if ( $domain === $this->localDomainIdAlias ||
$domain === false ) {
264 // Local connection requested via some backwards-compatibility domain alias
265 return $this->getLocalDomainID();
268 return (string)$domain;
272 * Resolve $groups into a list of query groups defining as having database servers
274 * @param string[]|string|bool $groups Query group(s) in preference order, [], or false
275 * @param int $i Specific server index or DB_MASTER/DB_REPLICA
276 * @return string[] Non-empty group list in preference order with the default group appended
278 private function resolveGroups( $groups, $i ) {
279 // If a specific replica server was specified, then $groups makes no sense
280 if ( $i > 0 && $groups !== [] && $groups !== false ) {
281 $list = implode( ', ', (array)$groups );
282 throw new LogicException( "Query group(s) ($list) given with server index (#$i)" );
285 if ( $groups === [] ||
$groups === false ||
$groups === $this->defaultGroup
) {
286 $resolvedGroups = [ $this->defaultGroup
]; // common case
287 } elseif ( is_string( $groups ) && isset( $this->groupLoads
[$groups] ) ) {
288 $resolvedGroups = [ $groups, $this->defaultGroup
];
289 } elseif ( is_array( $groups ) ) {
290 $resolvedGroups = array_keys( array_flip( $groups ) +
[ self
::GROUP_GENERIC
=> 1 ] );
292 $resolvedGroups = [ $this->defaultGroup
];
295 return $resolvedGroups;
299 * @param int $flags Bitfield of class CONN_* constants
300 * @param int $i Specific server index or DB_MASTER/DB_REPLICA
301 * @return int Sanitized bitfield
303 private function sanitizeConnectionFlags( $flags, $i ) {
304 // Whether an outside caller is explicitly requesting the master database server
305 if ( $i === self
::DB_MASTER ||
$i === $this->getWriterIndex() ) {
306 $flags |
= self
::CONN_INTENT_WRITABLE
;
309 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
) {
310 // Callers use CONN_TRX_AUTOCOMMIT to bypass REPEATABLE-READ staleness without
311 // resorting to row locks (e.g. FOR UPDATE) or to make small out-of-band commits
312 // during larger transactions. This is useful for avoiding lock contention.
314 // Master DB server attributes (should match those of the replica DB servers)
315 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
316 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
317 // The RDBMS does not support concurrent writes (e.g. SQLite), so attempts
318 // to use separate connections would just cause self-deadlocks. Note that
319 // REPEATABLE-READ staleness is not an issue since DB-level locking means
320 // that transactions are Strict Serializable anyway.
321 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
322 $type = $this->getServerType( $this->getWriterIndex() );
323 $this->connLogger
->info( __METHOD__
. ": CONN_TRX_AUTOCOMMIT disallowed ($type)" );
331 * @param IDatabase $conn
333 * @throws DBUnexpectedError
335 private function enforceConnectionFlags( IDatabase
$conn, $flags ) {
336 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
) {
337 if ( $conn->trxLevel() ) { // sanity
338 throw new DBUnexpectedError(
340 'Handle requested with CONN_TRX_AUTOCOMMIT yet it has a transaction'
344 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
349 * Get a LoadMonitor instance
351 * @return ILoadMonitor
353 private function getLoadMonitor() {
354 if ( !isset( $this->loadMonitor
) ) {
356 'LoadMonitor' => LoadMonitor
::class,
357 'LoadMonitorNull' => LoadMonitorNull
::class,
358 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
361 $class = $this->loadMonitorConfig
['class'];
362 if ( isset( $compat[$class] ) ) {
363 $class = $compat[$class];
366 $this->loadMonitor
= new $class(
367 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
368 $this->loadMonitor
->setLogger( $this->replLogger
);
371 return $this->loadMonitor
;
375 * @param array $loads
376 * @param bool|string $domain Domain to get non-lagged for
377 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
378 * @return bool|int|string
380 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
381 $lags = $this->getLagTimes( $domain );
383 # Unset excessively lagged servers
384 foreach ( $lags as $i => $lag ) {
385 if ( $i !== $this->getWriterIndex() ) {
386 # How much lag this server nominally is allowed to have
387 $maxServerLag = $this->servers
[$i]['max lag'] ??
$this->maxLag
; // default
388 # Constrain that futher by $maxLag argument
389 $maxServerLag = min( $maxServerLag, $maxLag );
391 $host = $this->getServerName( $i );
392 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
393 $this->replLogger
->debug(
395 ": server {host} is not replicating?", [ 'host' => $host ] );
397 } elseif ( $lag > $maxServerLag ) {
398 $this->replLogger
->debug(
400 ": server {host} has {lag} seconds of lag (>= {maxlag})",
401 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
408 # Find out if all the replica DBs with non-zero load are lagged
410 foreach ( $loads as $load ) {
414 # No appropriate DB servers except maybe the master and some replica DBs with zero load
415 # Do NOT use the master
416 # Instead, this function will return false, triggering read-only mode,
417 # and a lagged replica DB will be used instead.
421 if ( count( $loads ) == 0 ) {
425 # Return a random representative of the remainder
426 return ArrayUtils
::pickRandom( $loads );
430 * Get the server index to use for a specified server index and query group list
432 * @param int $i Specific server index or DB_MASTER/DB_REPLICA
433 * @param string[] $groups Non-empty query group list in preference order
434 * @param string|bool $domain
435 * @return int A specific server index (replica DBs are checked for connectivity)
437 private function getConnectionIndex( $i, array $groups, $domain ) {
438 if ( $i === self
::DB_MASTER
) {
439 $i = $this->getWriterIndex();
440 } elseif ( $i === self
::DB_REPLICA
) {
441 foreach ( $groups as $group ) {
442 $groupIndex = $this->getReaderIndex( $group, $domain );
443 if ( $groupIndex !== false ) {
444 $i = $groupIndex; // group connection succeeded
448 } elseif ( !isset( $this->servers
[$i] ) ) {
449 throw new UnexpectedValueException( "Invalid server index index #$i" );
452 if ( $i === self
::DB_REPLICA
) {
453 $this->lastError
= 'Unknown error'; // set here in case of worse failure
454 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
455 $this->reportConnectionError();
456 return null; // unreachable due to exception
462 public function getReaderIndex( $group = false, $domain = false ) {
463 if ( $this->getServerCount() == 1 ) {
464 // Skip the load balancing if there's only one server
465 return $this->getWriterIndex();
468 $group = is_string( $group ) ?
$group : self
::GROUP_GENERIC
;
470 $index = $this->getExistingReaderIndex( $group );
472 // A reader index was already selected and "waitForPos" was handled
476 // Use the server weight array for this load group
477 if ( isset( $this->groupLoads
[$group] ) ) {
478 $loads = $this->groupLoads
[$group];
480 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
485 // Scale the configured load ratios according to each server's load and state
486 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
488 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
489 $this->lazyLoadReplicationPositions(); // optimizes server candidate selection
490 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
491 if ( $i === false ) {
492 // DB connection unsuccessful
496 // If data seen by queries is expected to reflect the transactions committed as of
497 // or after a given replication position then wait for the DB to apply those changes
498 if ( $this->waitForPos
&& $i !== $this->getWriterIndex() && !$this->doWait( $i ) ) {
499 // Data will be outdated compared to what was expected
500 $laggedReplicaMode = true;
503 // Cache the reader index for future DB_REPLICA handles
504 $this->setExistingReaderIndex( $group, $i );
505 // Record whether the generic reader index is in "lagged replica DB" mode
506 if ( $group === self
::GROUP_GENERIC
&& $laggedReplicaMode ) {
507 $this->laggedReplicaMode
= true;
510 $serverName = $this->getServerName( $i );
511 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
517 * Get the server index chosen by the load balancer for use with the given query group
519 * @param string $group Query group; use false for the generic group
520 * @return int Server index or -1 if none was chosen
522 protected function getExistingReaderIndex( $group ) {
523 return $this->readIndexByGroup
[$group] ??
-1;
527 * Set the server index chosen by the load balancer for use with the given query group
529 * @param string $group Query group; use false for the generic group
530 * @param int $index The index of a specific server
532 private function setExistingReaderIndex( $group, $index ) {
534 throw new UnexpectedValueException( "Cannot set a negative read server index" );
536 $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, 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 // Get a connection to this server without triggering other server connections
596 $flags = self
::CONN_SILENCE_ERRORS
;
597 $conn = $this->getServerConnection( $i, $domain, $flags );
599 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
600 unset( $currentLoads[$i] ); // avoid this server next iteration
605 // Decrement reference counter, we are finished with this connection.
606 // It will be incremented for the caller later.
607 if ( $domain !== false ) {
608 $this->reuseConnection( $conn );
611 // Return this server
615 // If all servers were down, quit now
616 if ( $currentLoads === [] ) {
617 $this->connLogger
->error( __METHOD__
. ": all servers down" );
620 return [ $i, $laggedReplicaMode ];
623 public function waitFor( $pos ) {
624 $oldPos = $this->waitForPos
;
626 $this->waitForPos
= $pos;
627 // If a generic reader connection was already established, then wait now
628 $i = $this->getExistingReaderIndex( self
::GROUP_GENERIC
);
629 if ( $i > 0 && !$this->doWait( $i ) ) {
630 $this->laggedReplicaMode
= true;
632 // Otherwise, wait until a connection is established in getReaderIndex()
634 // Restore the older position if it was higher since this is used for lag-protection
635 $this->setWaitForPositionIfHigher( $oldPos );
639 public function waitForOne( $pos, $timeout = null ) {
640 $oldPos = $this->waitForPos
;
642 $this->waitForPos
= $pos;
644 $i = $this->getExistingReaderIndex( self
::GROUP_GENERIC
);
646 // Pick a generic replica DB if there isn't one yet
647 $readLoads = $this->groupLoads
[self
::GROUP_GENERIC
];
648 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
649 $readLoads = array_filter( $readLoads ); // with non-zero load
650 $i = ArrayUtils
::pickRandom( $readLoads );
654 $ok = $this->doWait( $i, true, $timeout );
656 $ok = true; // no applicable loads
659 // Restore the old position; this is used for throttling, not lag-protection
660 $this->waitForPos
= $oldPos;
666 public function waitForAll( $pos, $timeout = null ) {
667 $timeout = $timeout ?
: $this->waitTimeout
;
669 $oldPos = $this->waitForPos
;
671 $this->waitForPos
= $pos;
672 $serverCount = $this->getServerCount();
675 for ( $i = 1; $i < $serverCount; $i++
) {
676 if ( $this->serverHasLoadInAnyGroup( $i ) ) {
677 $start = microtime( true );
678 $ok = $this->doWait( $i, true, $timeout ) && $ok;
679 $timeout -= intval( microtime( true ) - $start );
680 if ( $timeout <= 0 ) {
681 break; // timeout reached
686 // Restore the old position; this is used for throttling, not lag-protection
687 $this->waitForPos
= $oldPos;
694 * @param int $i Specific server index
697 private function serverHasLoadInAnyGroup( $i ) {
698 foreach ( $this->groupLoads
as $loadsByIndex ) {
699 if ( ( $loadsByIndex[$i] ??
0 ) > 0 ) {
708 * @param DBMasterPos|bool $pos
710 private function setWaitForPositionIfHigher( $pos ) {
715 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
716 $this->waitForPos
= $pos;
720 public function getAnyOpenConnection( $i, $flags = 0 ) {
721 $i = ( $i === self
::DB_MASTER
) ?
$this->getWriterIndex() : $i;
722 // Connection handles required to be in auto-commit mode use a separate connection
723 // pool since the main pool is effected by implicit and explicit transaction rounds
724 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
727 foreach ( $this->conns
as $connsByServer ) {
728 // Get the connection array server indexes to inspect
729 if ( $i === self
::DB_REPLICA
) {
730 $indexes = array_keys( $connsByServer );
732 $indexes = isset( $connsByServer[$i] ) ?
[ $i ] : [];
735 foreach ( $indexes as $index ) {
736 $conn = $this->pickAnyOpenConnection( $connsByServer[$index], $autocommit );
744 $this->enforceConnectionFlags( $conn, $flags );
751 * @param IDatabase[] $candidateConns
752 * @param bool $autocommit Whether to only look for auto-commit connections
753 * @return IDatabase|false An appropriate open connection or false if none found
755 private function pickAnyOpenConnection( $candidateConns, $autocommit ) {
758 foreach ( $candidateConns as $candidateConn ) {
759 if ( !$candidateConn->isOpen() ) {
760 continue; // some sort of error occured?
764 // Connection is transaction round aware
765 !$candidateConn->getLBInfo( 'autoCommitOnly' ) ||
766 // Some sort of error left a transaction open?
767 $candidateConn->trxLevel()
770 continue; // some sort of error left a transaction open?
773 $conn = $candidateConn;
780 * Wait for a given replica DB to catch up to the master pos stored in "waitForPos"
781 * @param int $index Specific server index
782 * @param bool $open Check the server even if a new connection has to be made
783 * @param int|null $timeout Max seconds to wait; default is "waitTimeout"
786 protected function doWait( $index, $open = false, $timeout = null ) {
787 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
789 // Check if we already know that the DB has reached this point
790 $server = $this->getServerName( $index );
791 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
792 /** @var DBMasterPos $knownReachedPos */
793 $knownReachedPos = $this->srvCache
->get( $key );
795 $knownReachedPos instanceof DBMasterPos
&&
796 $knownReachedPos->hasReached( $this->waitForPos
)
798 $this->replLogger
->debug(
800 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
801 [ 'dbserver' => $server ]
806 // Find a connection to wait on, creating one if needed and allowed
807 $close = false; // close the connection afterwards
808 $flags = self
::CONN_SILENCE_ERRORS
;
809 $conn = $this->getAnyOpenConnection( $index, $flags );
812 $this->replLogger
->debug(
813 __METHOD__
. ': no connection open for {dbserver}',
814 [ 'dbserver' => $server ]
819 // Get a connection to this server without triggering other server connections
820 $conn = $this->getServerConnection( $index, self
::DOMAIN_ANY
, $flags );
822 $this->replLogger
->warning(
823 __METHOD__
. ': failed to connect to {dbserver}',
824 [ 'dbserver' => $server ]
829 // Avoid connection spam in waitForAll() when connections
830 // are made just for the sake of doing this lag check.
834 $this->replLogger
->info(
836 ': waiting for replica DB {dbserver} to catch up...',
837 [ 'dbserver' => $server ]
840 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
842 if ( $result === null ) {
843 $this->replLogger
->warning(
844 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
847 'pos' => $this->waitForPos
,
848 'trace' => ( new RuntimeException() )->getTraceAsString()
852 } elseif ( $result == -1 ) {
853 $this->replLogger
->warning(
854 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
857 'pos' => $this->waitForPos
,
858 'trace' => ( new RuntimeException() )->getTraceAsString()
863 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
865 // Remember that the DB reached this point
866 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
870 $this->closeConnection( $conn );
876 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
877 $domain = $this->resolveDomainID( $domain );
878 $groups = $this->resolveGroups( $groups, $i );
879 $flags = $this->sanitizeConnectionFlags( $flags, $i );
880 // If given DB_MASTER/DB_REPLICA, resolve it to a specific server index. Resolving
881 // DB_REPLICA might trigger getServerConnection() calls due to the getReaderIndex()
882 // connectivity checks or LoadMonitor::scaleLoads() server state cache regeneration.
883 // The use of getServerConnection() instead of getConnection() avoids infinite loops.
884 $serverIndex = $this->getConnectionIndex( $i, $groups, $domain );
885 // Get an open connection to that server (might trigger a new connection)
886 $conn = $this->getServerConnection( $serverIndex, $domain, $flags );
887 // Set master DB handles as read-only if there is high replication lag
888 if ( $serverIndex === $this->getWriterIndex() && $this->getLaggedReplicaMode( $domain ) ) {
889 $reason = ( $this->getExistingReaderIndex( self
::GROUP_GENERIC
) >= 0 )
890 ?
'The database is read-only until replication lag decreases.'
891 : 'The database is read-only until replica database servers becomes reachable.';
892 $conn->setLBInfo( 'readOnlyReason', $reason );
899 * @param int $i Specific server index
900 * @param string $domain Resolved DB domain
901 * @param int $flags Bitfield of class CONN_* constants
902 * @return IDatabase|bool
903 * @throws InvalidArgumentException When the server index is invalid
905 public function getServerConnection( $i, $domain, $flags = 0 ) {
906 // Number of connections made before getting the server index and handle
907 $priorConnectionsMade = $this->connectionCounter
;
908 // Get an open connection to this server (might trigger a new connection)
909 $conn = $this->localDomain
->equals( $domain )
910 ?
$this->getLocalConnection( $i, $flags )
911 : $this->getForeignConnection( $i, $domain, $flags );
912 // Throw an error or otherwise bail out if the connection attempt failed
913 if ( !( $conn instanceof IDatabase
) ) {
914 if ( ( $flags & self
::CONN_SILENCE_ERRORS
) != self
::CONN_SILENCE_ERRORS
) {
915 $this->reportConnectionError();
921 // Profile any new connections caused by this method
922 if ( $this->connectionCounter
> $priorConnectionsMade ) {
923 $this->trxProfiler
->recordConnection(
926 ( ( $flags & self
::CONN_INTENT_WRITABLE
) == self
::CONN_INTENT_WRITABLE
)
930 if ( !$conn->isOpen() ) {
931 $this->errorConnection
= $conn;
932 // Connection was made but later unrecoverably lost for some reason.
933 // Do not return a handle that will just throw exceptions on use, but
934 // let the calling code, e.g. getReaderIndex(), try another server.
938 // Make sure that flags like CONN_TRX_AUTOCOMMIT are respected by this handle
939 $this->enforceConnectionFlags( $conn, $flags );
940 // Set master DB handles as read-only if the load balancer is configured as read-only
941 // or the master database server is running in server-side read-only mode. Note that
942 // replica DB handles are always read-only via Database::assertIsWritableMaster().
943 // Read-only mode due to replication lag is *avoided* here to avoid recursion.
944 if ( $conn->getLBInfo( 'serverIndex' ) === $this->getWriterIndex() ) {
945 if ( $this->readOnlyReason
!== false ) {
946 $conn->setLBInfo( 'readOnlyReason', $this->readOnlyReason
);
947 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
950 'The master database server is running in read-only mode.'
958 public function reuseConnection( IDatabase
$conn ) {
959 $serverIndex = $conn->getLBInfo( 'serverIndex' );
960 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
961 if ( $serverIndex === null ||
$refCount === null ) {
963 * This can happen in code like:
964 * foreach ( $dbs as $db ) {
965 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
967 * $lb->reuseConnection( $conn );
969 * When a connection to the local DB is opened in this way, reuseConnection()
973 } elseif ( $conn instanceof DBConnRef
) {
974 // DBConnRef already handles calling reuseConnection() and only passes the live
975 // Database instance to this method. Any caller passing in a DBConnRef is broken.
976 $this->connLogger
->error(
977 __METHOD__
. ": got DBConnRef instance.\n" .
978 ( new LogicException() )->getTraceAsString() );
983 if ( $this->disabled
) {
984 return; // DBConnRef handle probably survived longer than the LoadBalancer
987 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
988 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
989 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
991 $connFreeKey = self
::KEY_FOREIGN_FREE
;
992 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
995 $domain = $conn->getDomainID();
996 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
997 throw new InvalidArgumentException(
998 "Connection $serverIndex/$domain not found; it may have already been freed" );
999 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
1000 throw new InvalidArgumentException(
1001 "Connection $serverIndex/$domain mismatched; it may have already been freed" );
1004 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
1005 if ( $refCount <= 0 ) {
1006 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
1007 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
1008 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
1009 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
1011 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
1013 $this->connLogger
->debug( __METHOD__
.
1014 ": reference count for $serverIndex/$domain reduced to $refCount" );
1018 public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1019 $domain = $this->resolveDomainID( $domain );
1020 $role = $this->getRoleFromIndex( $i );
1022 return new DBConnRef( $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
1025 public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1026 $domain = $this->resolveDomainID( $domain );
1027 $role = $this->getRoleFromIndex( $i );
1029 return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role );
1032 public function getMaintenanceConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1033 $domain = $this->resolveDomainID( $domain );
1034 $role = $this->getRoleFromIndex( $i );
1036 return new MaintainableDBConnRef(
1037 $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
1041 * @param int $i Server index or DB_MASTER/DB_REPLICA
1042 * @return int One of DB_MASTER/DB_REPLICA
1044 private function getRoleFromIndex( $i ) {
1045 return ( $i === self
::DB_MASTER ||
$i === $this->getWriterIndex() )
1052 * @param string|bool $domain
1054 * @return Database|bool Live database handle or false on failure
1055 * @deprecated Since 1.34 Use getConnection() instead
1057 public function openConnection( $i, $domain = false, $flags = 0 ) {
1058 return $this->getConnection( $i, [], $domain, $flags | self
::CONN_SILENCE_ERRORS
);
1062 * Open a connection to a local DB, or return one if it is already open.
1064 * On error, returns false, and the connection which caused the
1065 * error will be available via $this->errorConnection.
1067 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
1069 * @param int $i Server index
1070 * @param int $flags Class CONN_* constant bitfield
1072 * @throws InvalidArgumentException When the server index is invalid
1073 * @throws UnexpectedValueException When the DB domain of the connection is corrupted
1075 private function getLocalConnection( $i, $flags = 0 ) {
1076 // Connection handles required to be in auto-commit mode use a separate connection
1077 // pool since the main pool is effected by implicit and explicit transaction rounds
1078 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
1080 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
1081 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
1082 $conn = $this->conns
[$connKey][$i][0];
1084 // Open a new connection
1085 $server = $this->getServerInfoStrict( $i );
1086 $server['serverIndex'] = $i;
1087 $server['autoCommitOnly'] = $autoCommit;
1088 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
1089 $host = $this->getServerName( $i );
1090 if ( $conn->isOpen() ) {
1091 $this->connLogger
->debug(
1092 __METHOD__
. ": connected to database $i at '$host'." );
1093 $this->conns
[$connKey][$i][0] = $conn;
1095 $this->connLogger
->warning(
1096 __METHOD__
. ": failed to connect to database $i at '$host'." );
1097 $this->errorConnection
= $conn;
1102 // Final sanity check to make sure the right domain is selected
1104 $conn instanceof IDatabase
&&
1105 !$this->localDomain
->isCompatible( $conn->getDomainID() )
1107 throw new UnexpectedValueException(
1108 "Got connection to '{$conn->getDomainID()}', " .
1109 "but expected local domain ('{$this->localDomain}')" );
1116 * Open a connection to a foreign DB, or return one if it is already open.
1118 * Increments a reference count on the returned connection which locks the
1119 * connection to the requested domain. This reference count can be
1120 * decremented by calling reuseConnection().
1122 * If a connection is open to the appropriate server already, but with the wrong
1123 * database, it will be switched to the right database and returned, as long as
1124 * it has been freed first with reuseConnection().
1126 * On error, returns false, and the connection which caused the
1127 * error will be available via $this->errorConnection.
1129 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
1131 * @param int $i Server index
1132 * @param string $domain Domain ID to open
1133 * @param int $flags Class CONN_* constant bitfield
1134 * @return Database|bool Returns false on connection error
1135 * @throws DBError When database selection fails
1136 * @throws InvalidArgumentException When the server index is invalid
1137 * @throws UnexpectedValueException When the DB domain of the connection is corrupted
1139 private function getForeignConnection( $i, $domain, $flags = 0 ) {
1140 $domainInstance = DatabaseDomain
::newFromId( $domain );
1141 // Connection handles required to be in auto-commit mode use a separate connection
1142 // pool since the main pool is effected by implicit and explicit transaction rounds
1143 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
1145 if ( $autoCommit ) {
1146 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
1147 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
1149 $connFreeKey = self
::KEY_FOREIGN_FREE
;
1150 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
1153 /** @var Database $conn */
1156 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
1157 // Reuse an in-use connection for the same domain
1158 $conn = $this->conns
[$connInUseKey][$i][$domain];
1159 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
1160 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
1161 // Reuse a free connection for the same domain
1162 $conn = $this->conns
[$connFreeKey][$i][$domain];
1163 unset( $this->conns
[$connFreeKey][$i][$domain] );
1164 $this->conns
[$connInUseKey][$i][$domain] = $conn;
1165 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
1166 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
1167 // Reuse a free connection from another domain if possible
1168 foreach ( $this->conns
[$connFreeKey][$i] as $oldDomain => $conn ) {
1169 if ( $domainInstance->getDatabase() !== null ) {
1170 // Check if changing the database will require a new connection.
1171 // In that case, leave the connection handle alone and keep looking.
1172 // This prevents connections from being closed mid-transaction and can
1173 // also avoid overhead if the same database will later be requested.
1175 $conn->databasesAreIndependent() &&
1176 $conn->getDBname() !== $domainInstance->getDatabase()
1180 // Select the new database, schema, and prefix
1181 $conn->selectDomain( $domainInstance );
1183 // Stay on the current database, but update the schema/prefix
1184 $conn->dbSchema( $domainInstance->getSchema() );
1185 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1187 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
1188 // Note that if $domain is an empty string, getDomainID() might not match it
1189 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1190 $this->connLogger
->debug( __METHOD__
.
1191 ": reusing free connection from $oldDomain for $domain" );
1197 // Open a new connection
1198 $server = $this->getServerInfoStrict( $i );
1199 $server['serverIndex'] = $i;
1200 $server['foreignPoolRefCount'] = 0;
1201 $server['foreign'] = true;
1202 $server['autoCommitOnly'] = $autoCommit;
1203 $conn = $this->reallyOpenConnection( $server, $domainInstance );
1204 if ( !$conn->isOpen() ) {
1205 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
1206 $this->errorConnection
= $conn;
1209 // Note that if $domain is an empty string, getDomainID() might not match it
1210 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1211 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1215 if ( $conn instanceof IDatabase
) {
1216 // Final sanity check to make sure the right domain is selected
1217 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1218 throw new UnexpectedValueException(
1219 "Got connection to '{$conn->getDomainID()}', but expected '$domain'" );
1221 // Increment reference count
1222 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1223 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1229 public function getServerAttributes( $i ) {
1230 return Database
::attributesFromType(
1231 $this->getServerType( $i ),
1232 $this->servers
[$i]['driver'] ??
null
1237 * Test if the specified index represents an open connection
1239 * @param int $index Server index
1242 private function isOpen( $index ) {
1243 return (bool)$this->getAnyOpenConnection( $index );
1247 * Open a new network connection to a server (uncached)
1249 * Returns a Database object whether or not the connection was successful.
1251 * @param array $server
1252 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
1254 * @throws DBAccessError
1255 * @throws InvalidArgumentException
1257 protected function reallyOpenConnection( array $server, DatabaseDomain
$domain ) {
1258 if ( $this->disabled
) {
1259 throw new DBAccessError();
1262 if ( $domain->getDatabase() === null ) {
1263 // The database domain does not specify a DB name and some database systems require a
1264 // valid DB specified on connection. The $server configuration array contains a default
1265 // DB name to use for connections in such cases.
1266 if ( $server['type'] === 'mysql' ) {
1267 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1268 // and the DB name in $server might not exist due to legacy reasons (the default
1269 // domain used to ignore the local LB domain, even when mismatched).
1270 $server['dbname'] = null;
1273 $server['dbname'] = $domain->getDatabase();
1276 if ( $domain->getSchema() !== null ) {
1277 $server['schema'] = $domain->getSchema();
1280 // It is always possible to connect with any prefix, even the empty string
1281 $server['tablePrefix'] = $domain->getTablePrefix();
1283 // Let the handle know what the cluster master is (e.g. "db1052")
1284 $masterName = $this->getServerName( $this->getWriterIndex() );
1285 $server['clusterMasterHost'] = $masterName;
1287 $server['srvCache'] = $this->srvCache
;
1288 // Set loggers and profilers
1289 $server['connLogger'] = $this->connLogger
;
1290 $server['queryLogger'] = $this->queryLogger
;
1291 $server['errorLogger'] = $this->errorLogger
;
1292 $server['deprecationLogger'] = $this->deprecationLogger
;
1293 $server['profiler'] = $this->profiler
;
1294 $server['trxProfiler'] = $this->trxProfiler
;
1295 // Use the same agent and PHP mode for all DB handles
1296 $server['cliMode'] = $this->cliMode
;
1297 $server['agent'] = $this->agent
;
1298 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1299 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1300 $server['flags'] = $server['flags'] ?? IDatabase
::DBO_DEFAULT
;
1302 // Create a live connection object
1304 $db = Database
::factory( $server['type'], $server );
1305 // Log when many connection are made on requests
1306 ++
$this->connectionCounter
;
1307 $currentConnCount = $this->getCurrentConnectionCount();
1308 if ( $currentConnCount >= self
::CONN_HELD_WARN_THRESHOLD
) {
1309 $this->perfLogger
->warning(
1310 __METHOD__
. ": {connections}+ connections made (master={masterdb})",
1311 [ 'connections' => $currentConnCount, 'masterdb' => $masterName ]
1314 } catch ( DBConnectionError
$e ) {
1315 // FIXME: This is probably the ugliest thing I have ever done to
1316 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1320 $db->setLBInfo( $server );
1321 $db->setLazyMasterHandle(
1322 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1324 $db->setTableAliases( $this->tableAliases
);
1325 $db->setIndexAliases( $this->indexAliases
);
1327 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1328 if ( $this->trxRoundId
!== false ) {
1329 $this->applyTransactionRoundFlags( $db );
1331 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1332 $db->setTransactionListener( $name, $callback );
1336 $this->lazyLoadReplicationPositions(); // session consistency
1342 * Make sure that any "waitForPos" positions are loaded and available to doWait()
1344 private function lazyLoadReplicationPositions() {
1345 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
1346 $this->connectionAttempted
= true;
1347 ( $this->chronologyCallback
)( $this ); // generally calls waitFor()
1348 $this->connLogger
->debug( __METHOD__
. ': executed chronology callback.' );
1353 * @throws DBConnectionError
1355 private function reportConnectionError() {
1356 $conn = $this->errorConnection
; // the connection which caused the error
1358 'method' => __METHOD__
,
1359 'last_error' => $this->lastError
,
1362 if ( $conn instanceof IDatabase
) {
1363 $context['db_server'] = $conn->getServer();
1364 $this->connLogger
->warning(
1365 __METHOD__
. ": connection error: {last_error} ({db_server})",
1369 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1371 // No last connection, probably due to all servers being too busy
1372 $this->connLogger
->error(
1374 ": LB failure with no last connection. Connection error: {last_error}",
1378 // If all servers were busy, "lastError" will contain something sensible
1379 throw new DBConnectionError( null, $this->lastError
);
1383 public function getWriterIndex() {
1388 * Returns true if the specified index is a valid server index
1392 * @deprecated Since 1.34
1394 public function haveIndex( $i ) {
1395 return array_key_exists( $i, $this->servers
);
1399 * Returns true if the specified index is valid and has non-zero load
1403 * @deprecated Since 1.34
1405 public function isNonZeroLoad( $i ) {
1406 return ( isset( $this->servers
[$i] ) && $this->groupLoads
[self
::GROUP_GENERIC
][$i] > 0 );
1409 public function getServerCount() {
1410 return count( $this->servers
);
1413 public function hasReplicaServers() {
1414 return ( $this->getServerCount() > 1 );
1417 public function hasStreamingReplicaServers() {
1418 foreach ( $this->servers
as $i => $server ) {
1419 if ( $i !== $this->getWriterIndex() && empty( $server['is static'] ) ) {
1427 public function getServerName( $i ) {
1428 $name = $this->servers
[$i]['hostName'] ??
( $this->servers
[$i]['host'] ??
'' );
1430 return ( $name != '' ) ?
$name : 'localhost';
1433 public function getServerInfo( $i ) {
1434 return $this->servers
[$i] ??
false;
1437 public function getServerType( $i ) {
1438 return $this->servers
[$i]['type'] ??
'unknown';
1441 public function getMasterPos() {
1442 $index = $this->getWriterIndex();
1444 $conn = $this->getAnyOpenConnection( $index );
1446 return $conn->getMasterPos();
1449 $conn = $this->getConnection( $index, self
::CONN_SILENCE_ERRORS
);
1451 $this->reportConnectionError();
1452 return null; // unreachable due to exception
1456 $pos = $conn->getMasterPos();
1458 $this->closeConnection( $conn );
1464 public function getReplicaResumePos() {
1465 // Get the position of any existing master server connection
1466 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1467 if ( $masterConn ) {
1468 return $masterConn->getMasterPos();
1471 // Get the highest position of any existing replica server connection
1472 $highestPos = false;
1473 $serverCount = $this->getServerCount();
1474 for ( $i = 1; $i < $serverCount; $i++
) {
1475 if ( !empty( $this->servers
[$i]['is static'] ) ) {
1476 continue; // server does not use replication
1479 $conn = $this->getAnyOpenConnection( $i );
1480 $pos = $conn ?
$conn->getReplicaPos() : false;
1482 continue; // no open connection or could not get position
1485 $highestPos = $highestPos ?
: $pos;
1486 if ( $pos->hasReached( $highestPos ) ) {
1494 public function disable() {
1496 $this->disabled
= true;
1499 public function closeAll() {
1500 $fname = __METHOD__
;
1501 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( $fname ) {
1502 $host = $conn->getServer();
1503 $this->connLogger
->debug(
1504 $fname . ": closing connection to database '$host'." );
1508 $this->conns
= self
::newTrackedConnectionsArray();
1511 public function closeConnection( IDatabase
$conn ) {
1512 if ( $conn instanceof DBConnRef
) {
1513 // Avoid calling close() but still leaving the handle in the pool
1514 throw new RuntimeException( 'Cannot close DBConnRef instance; it must be shareable' );
1517 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1518 foreach ( $this->conns
as $type => $connsByServer ) {
1519 if ( !isset( $connsByServer[$serverIndex] ) ) {
1523 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1524 if ( $conn === $trackedConn ) {
1525 $host = $this->getServerName( $i );
1526 $this->connLogger
->debug(
1527 __METHOD__
. ": closing connection to database $i at '$host'." );
1528 unset( $this->conns
[$type][$serverIndex][$i] );
1537 public function commitAll( $fname = __METHOD__
, $owner = null ) {
1538 $this->commitMasterChanges( $fname, $owner );
1539 $this->flushMasterSnapshots( $fname );
1540 $this->flushReplicaSnapshots( $fname );
1543 public function finalizeMasterChanges( $fname = __METHOD__
, $owner = null ) {
1544 $this->assertOwnership( $fname, $owner );
1545 $this->assertTransactionRoundStage( [ self
::ROUND_CURSORY
, self
::ROUND_FINALIZED
] );
1547 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1548 // Loop until callbacks stop adding callbacks on other connections
1551 $count = 0; // callbacks execution attempts
1552 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$count ) {
1553 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1554 // Any error should cause all (peer) transactions to be rolled back together.
1555 $count +
= $conn->runOnTransactionPreCommitCallbacks();
1558 } while ( $count > 0 );
1559 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1560 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1561 $conn->setTrxEndCallbackSuppression( true );
1563 $this->trxRoundStage
= self
::ROUND_FINALIZED
;
1568 public function approveMasterChanges( array $options, $fname = __METHOD__
, $owner = null ) {
1569 $this->assertOwnership( $fname, $owner );
1570 $this->assertTransactionRoundStage( self
::ROUND_FINALIZED
);
1572 $limit = $options['maxWriteDuration'] ??
0;
1574 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1575 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1576 // If atomic sections or explicit transactions are still open, some caller must have
1577 // caught an exception but failed to properly rollback any changes. Detect that and
1578 // throw and error (causing rollback).
1579 $conn->assertNoOpenTransactions();
1580 // Assert that the time to replicate the transaction will be sane.
1581 // If this fails, then all DB transactions will be rollback back together.
1582 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1583 if ( $limit > 0 && $time > $limit ) {
1584 throw new DBTransactionSizeError(
1586 "Transaction spent $time second(s) in writes, exceeding the limit of $limit",
1590 // If a connection sits idle while slow queries execute on another, that connection
1591 // may end up dropped before the commit round is reached. Ping servers to detect this.
1592 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1593 throw new DBTransactionError(
1595 "A connection to the {$conn->getDBname()} database was lost before commit"
1599 $this->trxRoundStage
= self
::ROUND_APPROVED
;
1602 public function beginMasterChanges( $fname = __METHOD__
, $owner = null ) {
1603 $this->assertOwnership( $fname, $owner );
1604 if ( $this->trxRoundId
!== false ) {
1605 throw new DBTransactionError(
1607 "$fname: Transaction round '{$this->trxRoundId}' already started"
1610 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
1612 // Clear any empty transactions (no writes/callbacks) from the implicit round
1613 $this->flushMasterSnapshots( $fname );
1615 $this->trxRoundId
= $fname;
1616 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1617 // Mark applicable handles as participating in this explicit transaction round.
1618 // For each of these handles, any writes and callbacks will be tied to a single
1619 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1620 // are part of an en masse commit or an en masse rollback.
1621 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1622 $this->applyTransactionRoundFlags( $conn );
1624 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1627 public function commitMasterChanges( $fname = __METHOD__
, $owner = null ) {
1628 $this->assertOwnership( $fname, $owner );
1629 $this->assertTransactionRoundStage( self
::ROUND_APPROVED
);
1633 /** @noinspection PhpUnusedLocalVariableInspection */
1634 $scope = ScopedCallback
::newScopedIgnoreUserAbort(); // try to ignore client aborts
1636 $restore = ( $this->trxRoundId
!== false );
1637 $this->trxRoundId
= false;
1638 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1639 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1640 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1641 $this->forEachOpenMasterConnection(
1642 function ( IDatabase
$conn ) use ( $fname, &$failures ) {
1644 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1645 } catch ( DBError
$e ) {
1646 ( $this->errorLogger
)( $e );
1647 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1652 throw new DBTransactionError(
1654 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1658 // Unmark handles as participating in this explicit transaction round
1659 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1660 $this->undoTransactionRoundFlags( $conn );
1663 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
1666 public function runMasterTransactionIdleCallbacks( $fname = __METHOD__
, $owner = null ) {
1667 $this->assertOwnership( $fname, $owner );
1668 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1669 $type = IDatabase
::TRIGGER_COMMIT
;
1670 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1671 $type = IDatabase
::TRIGGER_ROLLBACK
;
1673 throw new DBTransactionError(
1675 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1679 $oldStage = $this->trxRoundStage
;
1680 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1682 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1683 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1684 $conn->setTrxEndCallbackSuppression( false );
1687 $e = null; // first exception
1688 $fname = __METHOD__
;
1689 // Loop until callbacks stop adding callbacks on other connections
1691 // Run any pending callbacks for each connection...
1692 $count = 0; // callback execution attempts
1693 $this->forEachOpenMasterConnection(
1694 function ( Database
$conn ) use ( $type, &$e, &$count ) {
1695 if ( $conn->trxLevel() ) {
1696 return; // retry in the next iteration, after commit() is called
1699 $count +
= $conn->runOnTransactionIdleCallbacks( $type );
1700 } catch ( Exception
$ex ) {
1705 // Clear out any active transactions left over from callbacks...
1706 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$e, $fname ) {
1707 if ( $conn->writesPending() ) {
1708 // A callback from another handle wrote to this one and DBO_TRX is set
1709 $this->queryLogger
->warning( $fname . ": found writes pending." );
1710 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1711 $this->queryLogger
->warning(
1712 $fname . ": found writes pending ($fnames).",
1714 'db_server' => $conn->getServer(),
1715 'db_name' => $conn->getDBname()
1718 } elseif ( $conn->trxLevel() ) {
1719 // A callback from another handle read from this one and DBO_TRX is set,
1720 // which can easily happen if there is only one DB (no replicas)
1721 $this->queryLogger
->debug( $fname . ": found empty transaction." );
1724 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1725 } catch ( Exception
$ex ) {
1729 } while ( $count > 0 );
1731 $this->trxRoundStage
= $oldStage;
1736 public function runMasterTransactionListenerCallbacks( $fname = __METHOD__
, $owner = null ) {
1737 $this->assertOwnership( $fname, $owner );
1738 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1739 $type = IDatabase
::TRIGGER_COMMIT
;
1740 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1741 $type = IDatabase
::TRIGGER_ROLLBACK
;
1743 throw new DBTransactionError(
1745 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1751 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1752 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1754 $conn->runTransactionListenerCallbacks( $type );
1755 } catch ( Exception
$ex ) {
1759 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1764 public function rollbackMasterChanges( $fname = __METHOD__
, $owner = null ) {
1765 $this->assertOwnership( $fname, $owner );
1767 $restore = ( $this->trxRoundId
!== false );
1768 $this->trxRoundId
= false;
1769 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1770 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1771 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1774 // Unmark handles as participating in this explicit transaction round
1775 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1776 $this->undoTransactionRoundFlags( $conn );
1779 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
1783 * @param string|string[] $stage
1784 * @throws DBTransactionError
1786 private function assertTransactionRoundStage( $stage ) {
1787 $stages = (array)$stage;
1789 if ( !in_array( $this->trxRoundStage
, $stages, true ) ) {
1790 $stageList = implode(
1792 array_map( function ( $v ) {
1796 throw new DBTransactionError(
1798 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1804 * @param string $fname
1805 * @param int|null $owner Owner ID of the caller
1806 * @throws DBTransactionError
1808 private function assertOwnership( $fname, $owner ) {
1809 if ( $this->ownerId
!== null && $owner !== $this->ownerId
) {
1810 throw new DBTransactionError(
1812 "$fname: LoadBalancer is owned by LBFactory #{$this->ownerId} (got '$owner')."
1818 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1820 * Some servers may have neither flag enabled, meaning that they opt out of such
1821 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1822 * when a DB server is used for something like simple key/value storage.
1824 * @param Database $conn
1826 private function applyTransactionRoundFlags( Database
$conn ) {
1827 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1828 return; // transaction rounds do not apply to these connections
1831 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1832 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1833 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1834 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1837 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1838 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1843 * @param Database $conn
1845 private function undoTransactionRoundFlags( Database
$conn ) {
1846 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1847 return; // transaction rounds do not apply to these connections
1850 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1851 $conn->setLBInfo( 'trxRoundId', null ); // remove the round ID
1854 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1855 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1859 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1860 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) use ( $fname ) {
1861 $conn->flushSnapshot( $fname );
1865 public function flushMasterSnapshots( $fname = __METHOD__
) {
1866 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1867 $conn->flushSnapshot( $fname );
1875 public function getTransactionRoundStage() {
1876 return $this->trxRoundStage
;
1879 public function hasMasterConnection() {
1880 return $this->isOpen( $this->getWriterIndex() );
1883 public function hasMasterChanges() {
1885 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1886 $pending |
= $conn->writesOrCallbacksPending();
1889 return (bool)$pending;
1892 public function lastMasterChangeTimestamp() {
1894 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1895 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1901 public function hasOrMadeRecentMasterChanges( $age = null ) {
1902 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1904 return ( $this->hasMasterChanges()
1905 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1908 public function pendingMasterChangeCallers() {
1910 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1911 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1917 public function getLaggedReplicaMode( $domain = false ) {
1918 if ( $this->laggedReplicaMode
) {
1919 return true; // stay in lagged replica mode
1922 if ( $this->hasStreamingReplicaServers() ) {
1924 // Set "laggedReplicaMode"
1925 $this->getReaderIndex( self
::GROUP_GENERIC
, $domain );
1926 } catch ( DBConnectionError
$e ) {
1927 // Sanity: avoid expensive re-connect attempts and failures
1928 $this->laggedReplicaMode
= true;
1932 return $this->laggedReplicaMode
;
1935 public function laggedReplicaUsed() {
1936 return $this->laggedReplicaMode
;
1939 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1940 if ( $this->readOnlyReason
!== false ) {
1941 return $this->readOnlyReason
;
1942 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1943 return 'The master database server is running in read-only mode.';
1944 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1945 return ( $this->getExistingReaderIndex( self
::GROUP_GENERIC
) >= 0 )
1946 ?
'The database is read-only until replication lag decreases.'
1947 : 'The database is read-only until a replica database server becomes reachable.';
1954 * @param string $domain Domain ID, or false for the current domain
1955 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1958 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1959 $cache = $this->wanCache
;
1960 $masterServer = $this->getServerName( $this->getWriterIndex() );
1962 return (bool)$cache->getWithSetCallback(
1963 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1964 self
::TTL_CACHE_READONLY
,
1965 function () use ( $domain, $conn ) {
1966 $old = $this->trxProfiler
->setSilenced( true );
1968 $index = $this->getWriterIndex();
1969 $dbw = $conn ?
: $this->getServerConnection( $index, $domain );
1970 $readOnly = (int)$dbw->serverIsReadOnly();
1972 $this->reuseConnection( $dbw );
1974 } catch ( DBError
$e ) {
1977 $this->trxProfiler
->setSilenced( $old );
1981 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1985 public function allowLagged( $mode = null ) {
1986 if ( $mode === null ) {
1987 return $this->allowLagged
;
1989 $this->allowLagged
= $mode;
1991 return $this->allowLagged
;
1994 public function pingAll() {
1996 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1997 if ( !$conn->ping() ) {
2005 public function forEachOpenConnection( $callback, array $params = [] ) {
2006 foreach ( $this->conns
as $connsByServer ) {
2007 foreach ( $connsByServer as $serverConns ) {
2008 foreach ( $serverConns as $conn ) {
2009 $callback( $conn, ...$params );
2015 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
2016 $masterIndex = $this->getWriterIndex();
2017 foreach ( $this->conns
as $connsByServer ) {
2018 if ( isset( $connsByServer[$masterIndex] ) ) {
2019 /** @var IDatabase $conn */
2020 foreach ( $connsByServer[$masterIndex] as $conn ) {
2021 $callback( $conn, ...$params );
2027 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
2028 foreach ( $this->conns
as $connsByServer ) {
2029 foreach ( $connsByServer as $i => $serverConns ) {
2030 if ( $i === $this->getWriterIndex() ) {
2031 continue; // skip master
2033 foreach ( $serverConns as $conn ) {
2034 $callback( $conn, ...$params );
2043 private function getCurrentConnectionCount() {
2045 foreach ( $this->conns
as $connsByServer ) {
2046 foreach ( $connsByServer as $serverConns ) {
2047 $count +
= count( $serverConns );
2054 public function getMaxLag( $domain = false ) {
2059 if ( $this->hasReplicaServers() ) {
2060 $lagTimes = $this->getLagTimes( $domain );
2061 foreach ( $lagTimes as $i => $lag ) {
2062 if ( $this->groupLoads
[self
::GROUP_GENERIC
][$i] > 0 && $lag > $maxLag ) {
2064 $host = $this->getServerInfoStrict( $i, 'host' );
2070 return [ $host, $maxLag, $maxIndex ];
2073 public function getLagTimes( $domain = false ) {
2074 if ( !$this->hasReplicaServers() ) {
2075 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
2078 $knownLagTimes = []; // map of (server index => 0 seconds)
2079 $indexesWithLag = [];
2080 foreach ( $this->servers
as $i => $server ) {
2081 if ( empty( $server['is static'] ) ) {
2082 $indexesWithLag[] = $i; // DB server might have replication lag
2084 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
2088 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
2092 * Get the lag in seconds for a given connection, or zero if this load
2093 * balancer does not have replication enabled.
2095 * This should be used in preference to Database::getLag() in cases where
2096 * replication may not be in use, since there is no way to determine if
2097 * replication is in use at the connection level without running
2098 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
2099 * function instead of Database::getLag() avoids a fatal error in this
2100 * case on many installations.
2102 * @param IDatabase $conn
2103 * @return int|bool Returns false on error
2104 * @deprecated Since 1.34 Use IDatabase::getLag() instead
2106 public function safeGetLag( IDatabase
$conn ) {
2107 if ( $conn->getLBInfo( 'is static' ) ) {
2108 return 0; // static dataset
2109 } elseif ( $conn->getLBInfo( 'serverIndex' ) == $this->getWriterIndex() ) {
2110 return 0; // this is the master
2113 return $conn->getLag();
2116 public function waitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
2117 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
2119 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
2120 return true; // server is not a replica DB
2124 // Get the current master position, opening a connection if needed
2125 $index = $this->getWriterIndex();
2126 $flags = self
::CONN_SILENCE_ERRORS
;
2127 $masterConn = $this->getAnyOpenConnection( $index, $flags );
2128 if ( $masterConn ) {
2129 $pos = $masterConn->getMasterPos();
2131 $masterConn = $this->getServerConnection( $index, self
::DOMAIN_ANY
, $flags );
2132 if ( !$masterConn ) {
2133 throw new DBReplicationWaitError(
2135 "Could not obtain a master database connection to get the position"
2138 $pos = $masterConn->getMasterPos();
2139 $this->closeConnection( $masterConn );
2143 if ( $pos instanceof DBMasterPos
) {
2144 $start = microtime( true );
2145 $result = $conn->masterPosWait( $pos, $timeout );
2146 $seconds = max( microtime( true ) - $start, 0 );
2147 if ( $result == -1 ||
is_null( $result ) ) {
2148 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos} [{seconds}s]';
2149 $this->replLogger
->warning( $msg, [
2150 'host' => $conn->getServer(),
2152 'seconds' => round( $seconds, 6 ),
2153 'trace' => ( new RuntimeException() )->getTraceAsString()
2157 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
2161 $ok = false; // something is misconfigured
2162 $this->replLogger
->error(
2163 __METHOD__
. ': could not get master pos for {host}',
2165 'host' => $conn->getServer(),
2166 'trace' => ( new RuntimeException() )->getTraceAsString()
2175 * Wait for a replica DB to reach a specified master position
2177 * This will connect to the master to get an accurate position if $pos is not given
2179 * @param IDatabase $conn Replica DB
2180 * @param DBMasterPos|bool $pos Master position; default: current position
2181 * @param int $timeout Timeout in seconds [optional]
2182 * @return bool Success
2184 * @deprecated Since 1.34 Use waitForMasterPos() instead
2186 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
2187 return $this->waitForMasterPos( $conn, $pos, $timeout );
2190 public function setTransactionListener( $name, callable
$callback = null ) {
2192 $this->trxRecurringCallbacks
[$name] = $callback;
2194 unset( $this->trxRecurringCallbacks
[$name] );
2196 $this->forEachOpenMasterConnection(
2197 function ( IDatabase
$conn ) use ( $name, $callback ) {
2198 $conn->setTransactionListener( $name, $callback );
2203 public function setTableAliases( array $aliases ) {
2204 $this->tableAliases
= $aliases;
2207 public function setIndexAliases( array $aliases ) {
2208 $this->indexAliases
= $aliases;
2211 public function setLocalDomainPrefix( $prefix ) {
2212 // Find connections to explicit foreign domains still marked as in-use...
2214 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
2215 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
2216 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
2217 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
2218 $domainsInUse[] = $conn->getDomainID();
2222 // Do not switch connections to explicit foreign domains unless marked as safe
2223 if ( $domainsInUse ) {
2224 $domains = implode( ', ', $domainsInUse );
2225 throw new DBUnexpectedError( null,
2226 "Foreign domain connections are still in use ($domains)" );
2229 $this->setLocalDomain( new DatabaseDomain(
2230 $this->localDomain
->getDatabase(),
2231 $this->localDomain
->getSchema(),
2235 // Update the prefix for all local connections...
2236 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
2237 if ( !$db->getLBInfo( 'foreign' ) ) {
2238 $db->tablePrefix( $prefix );
2243 public function redefineLocalDomain( $domain ) {
2246 $this->setLocalDomain( DatabaseDomain
::newFromId( $domain ) );
2250 * @param DatabaseDomain $domain
2252 private function setLocalDomain( DatabaseDomain
$domain ) {
2253 $this->localDomain
= $domain;
2254 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
2255 // always true, gracefully handle the case when they fail to account for escaping.
2256 if ( $this->localDomain
->getTablePrefix() != '' ) {
2257 $this->localDomainIdAlias
=
2258 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
2260 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
2265 * @param int $i Server index
2266 * @param string|null $field Server index field [optional]
2267 * @return array|mixed
2268 * @throws InvalidArgumentException
2270 private function getServerInfoStrict( $i, $field = null ) {
2271 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
2272 throw new InvalidArgumentException( "No server with index '$i'" );
2275 if ( $field !== null ) {
2276 if ( !array_key_exists( $field, $this->servers
[$i] ) ) {
2277 throw new InvalidArgumentException( "No field '$field' in server index '$i'" );
2280 return $this->servers
[$i][$field];
2283 return $this->servers
[$i];
2286 function __destruct() {
2287 // Avoid connection leaks for sanity
2293 * @deprecated since 1.29
2295 class_alias( LoadBalancer
::class, 'LoadBalancer' );