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 = [];
104 /** @var bool[] Map of (domain => whether to use "temp tables only" mode) */
105 private $tempTablesOnlyMode = [];
107 /** @var Database Connection handle that caused a problem */
108 private $errorConnection;
109 /** @var int[] The group replica server indexes keyed by group */
110 private $readIndexByGroup = [];
111 /** @var bool|DBMasterPos Replication sync position or false if not set */
113 /** @var bool Whether the generic reader fell back to a lagged replica DB */
114 private $laggedReplicaMode = false;
115 /** @var string The last DB selection or connection error */
116 private $lastError = 'Unknown error';
117 /** @var string|bool Reason this instance is read-only or false if not */
118 private $readOnlyReason = false;
119 /** @var int Total number of new connections ever made with this instance */
120 private $connectionCounter = 0;
122 private $disabled = false;
123 /** @var bool Whether any connection has been attempted yet */
124 private $connectionAttempted = false;
126 /** var int An identifier for this class instance */
128 /** @var int|null Integer ID of the managing LBFactory instance or null if none */
130 /** @var string|bool Explicit DBO_TRX transaction round active or false if none */
131 private $trxRoundId = false;
132 /** @var string Stage of the current transaction round in the transaction round life-cycle */
133 private $trxRoundStage = self
::ROUND_CURSORY
;
135 /** @var int Warn when this many connection are held */
136 const CONN_HELD_WARN_THRESHOLD
= 10;
138 /** @var int Default 'maxLag' when unspecified */
139 const MAX_LAG_DEFAULT
= 6;
140 /** @var int Default 'waitTimeout' when unspecified */
141 const MAX_WAIT_DEFAULT
= 10;
142 /** @var int Seconds to cache master DB server read-only status */
143 const TTL_CACHE_READONLY
= 5;
145 const KEY_LOCAL
= 'local';
146 const KEY_FOREIGN_FREE
= 'foreignFree';
147 const KEY_FOREIGN_INUSE
= 'foreignInUse';
149 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
150 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
151 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
153 /** @var string Transaction round, explicit or implicit, has not finished writing */
154 const ROUND_CURSORY
= 'cursory';
155 /** @var string Transaction round writes are complete and ready for pre-commit checks */
156 const ROUND_FINALIZED
= 'finalized';
157 /** @var string Transaction round passed final pre-commit checks */
158 const ROUND_APPROVED
= 'approved';
159 /** @var string Transaction round was committed and post-commit callbacks must be run */
160 const ROUND_COMMIT_CALLBACKS
= 'commit-callbacks';
161 /** @var string Transaction round was rolled back and post-rollback callbacks must be run */
162 const ROUND_ROLLBACK_CALLBACKS
= 'rollback-callbacks';
163 /** @var string Transaction round encountered an error */
164 const ROUND_ERROR
= 'error';
166 public function __construct( array $params ) {
167 if ( !isset( $params['servers'] ) ||
!count( $params['servers'] ) ) {
168 throw new InvalidArgumentException( 'Missing or empty "servers" parameter' );
173 $this->groupLoads
= [ self
::GROUP_GENERIC
=> [] ];
174 foreach ( $params['servers'] as $i => $server ) {
175 if ( ++
$listKey !== $i ) {
176 throw new UnexpectedValueException( 'List expected for "servers" parameter' );
178 $this->servers
[$i] = $server;
179 foreach ( ( $server['groupLoads'] ??
[] ) as $group => $ratio ) {
180 $this->groupLoads
[$group][$i] = $ratio;
182 $this->groupLoads
[self
::GROUP_GENERIC
][$i] = $server['load'];
185 $localDomain = isset( $params['localDomain'] )
186 ? DatabaseDomain
::newFromId( $params['localDomain'] )
187 : DatabaseDomain
::newUnspecified();
188 $this->setLocalDomain( $localDomain );
190 $this->waitTimeout
= $params['waitTimeout'] ?? self
::MAX_WAIT_DEFAULT
;
192 $this->conns
= self
::newTrackedConnectionsArray();
193 $this->waitForPos
= false;
194 $this->allowLagged
= false;
196 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
197 $this->readOnlyReason
= $params['readOnlyReason'];
200 $this->maxLag
= $params['maxLag'] ?? self
::MAX_LAG_DEFAULT
;
202 $this->loadMonitorConfig
= $params['loadMonitor'] ??
[ 'class' => 'LoadMonitorNull' ];
203 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
205 $this->srvCache
= $params['srvCache'] ??
new EmptyBagOStuff();
206 $this->wanCache
= $params['wanCache'] ?? WANObjectCache
::newEmpty();
207 $this->profiler
= $params['profiler'] ??
null;
208 $this->trxProfiler
= $params['trxProfiler'] ??
new TransactionProfiler();
210 $this->errorLogger
= $params['errorLogger'] ??
function ( Exception
$e ) {
211 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
213 $this->deprecationLogger
= $params['deprecationLogger'] ??
function ( $msg ) {
214 trigger_error( $msg, E_USER_DEPRECATED
);
217 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
218 $this->$key = $params[$key] ??
new NullLogger();
221 $this->hostname
= $params['hostname'] ??
( gethostname() ?
: 'unknown' );
222 $this->cliMode
= $params['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
223 $this->agent
= $params['agent'] ??
'';
225 if ( isset( $params['chronologyCallback'] ) ) {
226 $this->chronologyCallback
= $params['chronologyCallback'];
229 if ( isset( $params['roundStage'] ) ) {
230 if ( $params['roundStage'] === self
::STAGE_POSTCOMMIT_CALLBACKS
) {
231 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
232 } elseif ( $params['roundStage'] === self
::STAGE_POSTROLLBACK_CALLBACKS
) {
233 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
237 $group = $params['defaultGroup'] ?? self
::GROUP_GENERIC
;
238 $this->defaultGroup
= isset( $this->groupLoads
[$group] ) ?
$group : self
::GROUP_GENERIC
;
241 $this->id
= $nextId = ( is_int( $nextId ) ?
$nextId++
: mt_rand() );
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 * @param string $domain Database domain
302 * @return int Sanitized bitfield
304 private function sanitizeConnectionFlags( $flags, $i, $domain ) {
305 // Whether an outside caller is explicitly requesting the master database server
306 if ( $i === self
::DB_MASTER ||
$i === $this->getWriterIndex() ) {
307 $flags |
= self
::CONN_INTENT_WRITABLE
;
310 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
) {
311 // Callers use CONN_TRX_AUTOCOMMIT to bypass REPEATABLE-READ staleness without
312 // resorting to row locks (e.g. FOR UPDATE) or to make small out-of-band commits
313 // during larger transactions. This is useful for avoiding lock contention.
315 // Master DB server attributes (should match those of the replica DB servers)
316 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
317 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
318 // The RDBMS does not support concurrent writes (e.g. SQLite), so attempts
319 // to use separate connections would just cause self-deadlocks. Note that
320 // REPEATABLE-READ staleness is not an issue since DB-level locking means
321 // that transactions are Strict Serializable anyway.
322 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
323 $type = $this->getServerType( $this->getWriterIndex() );
324 $this->connLogger
->info( __METHOD__
. ": CONN_TRX_AUTOCOMMIT disallowed ($type)" );
325 } elseif ( isset( $this->tempTablesOnlyMode
[$domain] ) ) {
326 // T202116: integration tests are active and queries should be all be using
327 // temporary clone tables (via prefix). Such tables are not visible accross
328 // different connections nor can there be REPEATABLE-READ snapshot staleness,
329 // so use the same connection for everything.
330 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
338 * @param IDatabase $conn
340 * @throws DBUnexpectedError
342 private function enforceConnectionFlags( IDatabase
$conn, $flags ) {
343 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
) {
344 if ( $conn->trxLevel() ) { // sanity
345 throw new DBUnexpectedError(
347 'Handle requested with CONN_TRX_AUTOCOMMIT yet it has a transaction'
351 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
356 * Get a LoadMonitor instance
358 * @return ILoadMonitor
360 private function getLoadMonitor() {
361 if ( !isset( $this->loadMonitor
) ) {
363 'LoadMonitor' => LoadMonitor
::class,
364 'LoadMonitorNull' => LoadMonitorNull
::class,
365 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
368 $class = $this->loadMonitorConfig
['class'];
369 if ( isset( $compat[$class] ) ) {
370 $class = $compat[$class];
373 $this->loadMonitor
= new $class(
374 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
375 $this->loadMonitor
->setLogger( $this->replLogger
);
378 return $this->loadMonitor
;
382 * @param array $loads
383 * @param bool|string $domain Domain to get non-lagged for
384 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
385 * @return bool|int|string
387 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
388 $lags = $this->getLagTimes( $domain );
390 # Unset excessively lagged servers
391 foreach ( $lags as $i => $lag ) {
392 if ( $i !== $this->getWriterIndex() ) {
393 # How much lag this server nominally is allowed to have
394 $maxServerLag = $this->servers
[$i]['max lag'] ??
$this->maxLag
; // default
395 # Constrain that futher by $maxLag argument
396 $maxServerLag = min( $maxServerLag, $maxLag );
398 $host = $this->getServerName( $i );
399 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
400 $this->replLogger
->debug(
402 ": server {host} is not replicating?", [ 'host' => $host ] );
404 } elseif ( $lag > $maxServerLag ) {
405 $this->replLogger
->debug(
407 ": server {host} has {lag} seconds of lag (>= {maxlag})",
408 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
415 # Find out if all the replica DBs with non-zero load are lagged
417 foreach ( $loads as $load ) {
421 # No appropriate DB servers except maybe the master and some replica DBs with zero load
422 # Do NOT use the master
423 # Instead, this function will return false, triggering read-only mode,
424 # and a lagged replica DB will be used instead.
428 if ( count( $loads ) == 0 ) {
432 # Return a random representative of the remainder
433 return ArrayUtils
::pickRandom( $loads );
437 * Get the server index to use for a specified server index and query group list
439 * @param int $i Specific server index or DB_MASTER/DB_REPLICA
440 * @param string[] $groups Non-empty query group list in preference order
441 * @param string|bool $domain
442 * @return int A specific server index (replica DBs are checked for connectivity)
444 private function getConnectionIndex( $i, array $groups, $domain ) {
445 if ( $i === self
::DB_MASTER
) {
446 $i = $this->getWriterIndex();
447 } elseif ( $i === self
::DB_REPLICA
) {
448 foreach ( $groups as $group ) {
449 $groupIndex = $this->getReaderIndex( $group, $domain );
450 if ( $groupIndex !== false ) {
451 $i = $groupIndex; // group connection succeeded
455 } elseif ( !isset( $this->servers
[$i] ) ) {
456 throw new UnexpectedValueException( "Invalid server index index #$i" );
459 if ( $i === self
::DB_REPLICA
) {
460 $this->lastError
= 'Unknown error'; // set here in case of worse failure
461 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
462 $this->reportConnectionError();
463 return null; // unreachable due to exception
469 public function getReaderIndex( $group = false, $domain = false ) {
470 if ( $this->getServerCount() == 1 ) {
471 // Skip the load balancing if there's only one server
472 return $this->getWriterIndex();
475 $group = is_string( $group ) ?
$group : self
::GROUP_GENERIC
;
477 $index = $this->getExistingReaderIndex( $group );
479 // A reader index was already selected and "waitForPos" was handled
483 // Use the server weight array for this load group
484 if ( isset( $this->groupLoads
[$group] ) ) {
485 $loads = $this->groupLoads
[$group];
487 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
492 // Scale the configured load ratios according to each server's load and state
493 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
495 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
496 $this->lazyLoadReplicationPositions(); // optimizes server candidate selection
497 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
498 if ( $i === false ) {
499 // DB connection unsuccessful
503 // If data seen by queries is expected to reflect the transactions committed as of
504 // or after a given replication position then wait for the DB to apply those changes
505 if ( $this->waitForPos
&& $i !== $this->getWriterIndex() && !$this->doWait( $i ) ) {
506 // Data will be outdated compared to what was expected
507 $laggedReplicaMode = true;
510 // Cache the reader index for future DB_REPLICA handles
511 $this->setExistingReaderIndex( $group, $i );
512 // Record whether the generic reader index is in "lagged replica DB" mode
513 if ( $group === self
::GROUP_GENERIC
&& $laggedReplicaMode ) {
514 $this->laggedReplicaMode
= true;
517 $serverName = $this->getServerName( $i );
518 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
524 * Get the server index chosen by the load balancer for use with the given query group
526 * @param string $group Query group; use false for the generic group
527 * @return int Server index or -1 if none was chosen
529 protected function getExistingReaderIndex( $group ) {
530 return $this->readIndexByGroup
[$group] ??
-1;
534 * Set the server index chosen by the load balancer for use with the given query group
536 * @param string $group Query group; use false for the generic group
537 * @param int $index The index of a specific server
539 private function setExistingReaderIndex( $group, $index ) {
541 throw new UnexpectedValueException( "Cannot set a negative read server index" );
543 $this->readIndexByGroup
[$group] = $index;
547 * @param array $loads List of server weights
548 * @param string|bool $domain
549 * @return array (reader index, lagged replica mode) or (false, false) on failure
551 private function pickReaderIndex( array $loads, $domain = false ) {
552 if ( $loads === [] ) {
553 throw new InvalidArgumentException( "Server configuration array is empty" );
556 /** @var int|bool $i Index of selected server */
558 /** @var bool $laggedReplicaMode Whether server is considered lagged */
559 $laggedReplicaMode = false;
561 // Quickly look through the available servers for a server that meets criteria...
562 $currentLoads = $loads;
563 while ( count( $currentLoads ) ) {
564 if ( $this->allowLagged ||
$laggedReplicaMode ) {
565 $i = ArrayUtils
::pickRandom( $currentLoads );
568 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
569 $this->replLogger
->debug( __METHOD__
. ": replication positions detected" );
570 // "chronologyCallback" sets "waitForPos" for session consistency.
571 // This triggers doWait() after connect, so it's especially good to
572 // avoid lagged servers so as to avoid excessive delay in that method.
573 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
574 // Aim for <= 1 second of waiting (being too picky can backfire)
575 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
577 if ( $i === false ) {
578 // Any server with less lag than it's 'max lag' param is preferable
579 $i = $this->getRandomNonLagged( $currentLoads, $domain );
581 if ( $i === false && count( $currentLoads ) ) {
582 // All replica DBs lagged. Switch to read-only mode
583 $this->replLogger
->error(
584 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
585 $i = ArrayUtils
::pickRandom( $currentLoads );
586 $laggedReplicaMode = true;
590 if ( $i === false ) {
591 // pickRandom() returned false.
592 // This is permanent and means the configuration or the load monitor
593 // wants us to return false.
594 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
596 return [ false, false ];
599 $serverName = $this->getServerName( $i );
600 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
602 // Get a connection to this server without triggering other server connections
603 $conn = $this->getServerConnection( $i, $domain, self
::CONN_SILENCE_ERRORS
);
605 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
606 unset( $currentLoads[$i] ); // avoid this server next iteration
611 // Decrement reference counter, we are finished with this connection.
612 // It will be incremented for the caller later.
613 if ( $domain !== false ) {
614 $this->reuseConnection( $conn );
617 // Return this server
621 // If all servers were down, quit now
622 if ( $currentLoads === [] ) {
623 $this->connLogger
->error( __METHOD__
. ": all servers down" );
626 return [ $i, $laggedReplicaMode ];
629 public function waitFor( $pos ) {
630 $oldPos = $this->waitForPos
;
632 $this->waitForPos
= $pos;
633 // If a generic reader connection was already established, then wait now
634 $i = $this->getExistingReaderIndex( self
::GROUP_GENERIC
);
635 if ( $i > 0 && !$this->doWait( $i ) ) {
636 $this->laggedReplicaMode
= true;
638 // Otherwise, wait until a connection is established in getReaderIndex()
640 // Restore the older position if it was higher since this is used for lag-protection
641 $this->setWaitForPositionIfHigher( $oldPos );
645 public function waitForOne( $pos, $timeout = null ) {
646 $oldPos = $this->waitForPos
;
648 $this->waitForPos
= $pos;
650 $i = $this->getExistingReaderIndex( self
::GROUP_GENERIC
);
652 // Pick a generic replica DB if there isn't one yet
653 $readLoads = $this->groupLoads
[self
::GROUP_GENERIC
];
654 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
655 $readLoads = array_filter( $readLoads ); // with non-zero load
656 $i = ArrayUtils
::pickRandom( $readLoads );
660 $ok = $this->doWait( $i, true, $timeout );
662 $ok = true; // no applicable loads
665 // Restore the old position; this is used for throttling, not lag-protection
666 $this->waitForPos
= $oldPos;
672 public function waitForAll( $pos, $timeout = null ) {
673 $timeout = $timeout ?
: $this->waitTimeout
;
675 $oldPos = $this->waitForPos
;
677 $this->waitForPos
= $pos;
678 $serverCount = $this->getServerCount();
681 for ( $i = 1; $i < $serverCount; $i++
) {
682 if ( $this->serverHasLoadInAnyGroup( $i ) ) {
683 $start = microtime( true );
684 $ok = $this->doWait( $i, true, $timeout ) && $ok;
685 $timeout -= intval( microtime( true ) - $start );
686 if ( $timeout <= 0 ) {
687 break; // timeout reached
692 // Restore the old position; this is used for throttling, not lag-protection
693 $this->waitForPos
= $oldPos;
700 * @param int $i Specific server index
703 private function serverHasLoadInAnyGroup( $i ) {
704 foreach ( $this->groupLoads
as $loadsByIndex ) {
705 if ( ( $loadsByIndex[$i] ??
0 ) > 0 ) {
714 * @param DBMasterPos|bool $pos
716 private function setWaitForPositionIfHigher( $pos ) {
721 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
722 $this->waitForPos
= $pos;
726 public function getAnyOpenConnection( $i, $flags = 0 ) {
727 $i = ( $i === self
::DB_MASTER
) ?
$this->getWriterIndex() : $i;
728 // Connection handles required to be in auto-commit mode use a separate connection
729 // pool since the main pool is effected by implicit and explicit transaction rounds
730 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
733 foreach ( $this->conns
as $connsByServer ) {
734 // Get the connection array server indexes to inspect
735 if ( $i === self
::DB_REPLICA
) {
736 $indexes = array_keys( $connsByServer );
738 $indexes = isset( $connsByServer[$i] ) ?
[ $i ] : [];
741 foreach ( $indexes as $index ) {
742 $conn = $this->pickAnyOpenConnection( $connsByServer[$index], $autocommit );
750 $this->enforceConnectionFlags( $conn, $flags );
757 * @param IDatabase[] $candidateConns
758 * @param bool $autocommit Whether to only look for auto-commit connections
759 * @return IDatabase|false An appropriate open connection or false if none found
761 private function pickAnyOpenConnection( $candidateConns, $autocommit ) {
764 foreach ( $candidateConns as $candidateConn ) {
765 if ( !$candidateConn->isOpen() ) {
766 continue; // some sort of error occured?
770 // Connection is transaction round aware
771 !$candidateConn->getLBInfo( 'autoCommitOnly' ) ||
772 // Some sort of error left a transaction open?
773 $candidateConn->trxLevel()
776 continue; // some sort of error left a transaction open?
779 $conn = $candidateConn;
786 * Wait for a given replica DB to catch up to the master pos stored in "waitForPos"
787 * @param int $index Specific server index
788 * @param bool $open Check the server even if a new connection has to be made
789 * @param int|null $timeout Max seconds to wait; default is "waitTimeout"
792 protected function doWait( $index, $open = false, $timeout = null ) {
793 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
795 // Check if we already know that the DB has reached this point
796 $server = $this->getServerName( $index );
797 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
798 /** @var DBMasterPos $knownReachedPos */
799 $knownReachedPos = $this->srvCache
->get( $key );
801 $knownReachedPos instanceof DBMasterPos
&&
802 $knownReachedPos->hasReached( $this->waitForPos
)
804 $this->replLogger
->debug(
806 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
807 [ 'dbserver' => $server ]
812 // Find a connection to wait on, creating one if needed and allowed
813 $close = false; // close the connection afterwards
814 $flags = self
::CONN_SILENCE_ERRORS
;
815 $conn = $this->getAnyOpenConnection( $index, $flags );
818 $this->replLogger
->debug(
819 __METHOD__
. ': no connection open for {dbserver}',
820 [ 'dbserver' => $server ]
825 // Get a connection to this server without triggering other server connections
826 $conn = $this->getServerConnection( $index, self
::DOMAIN_ANY
, $flags );
828 $this->replLogger
->warning(
829 __METHOD__
. ': failed to connect to {dbserver}',
830 [ 'dbserver' => $server ]
835 // Avoid connection spam in waitForAll() when connections
836 // are made just for the sake of doing this lag check.
840 $this->replLogger
->info(
842 ': waiting for replica DB {dbserver} to catch up...',
843 [ 'dbserver' => $server ]
846 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
848 if ( $result === null ) {
849 $this->replLogger
->warning(
850 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
853 'pos' => $this->waitForPos
,
854 'trace' => ( new RuntimeException() )->getTraceAsString()
858 } elseif ( $result == -1 ) {
859 $this->replLogger
->warning(
860 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
863 'pos' => $this->waitForPos
,
864 'trace' => ( new RuntimeException() )->getTraceAsString()
869 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
871 // Remember that the DB reached this point
872 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
876 $this->closeConnection( $conn );
882 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
883 $domain = $this->resolveDomainID( $domain );
884 $groups = $this->resolveGroups( $groups, $i );
885 $flags = $this->sanitizeConnectionFlags( $flags, $i, $domain );
886 // If given DB_MASTER/DB_REPLICA, resolve it to a specific server index. Resolving
887 // DB_REPLICA might trigger getServerConnection() calls due to the getReaderIndex()
888 // connectivity checks or LoadMonitor::scaleLoads() server state cache regeneration.
889 // The use of getServerConnection() instead of getConnection() avoids infinite loops.
890 $serverIndex = $this->getConnectionIndex( $i, $groups, $domain );
891 // Get an open connection to that server (might trigger a new connection)
892 $conn = $this->getServerConnection( $serverIndex, $domain, $flags );
893 // Set master DB handles as read-only if there is high replication lag
894 if ( $serverIndex === $this->getWriterIndex() && $this->getLaggedReplicaMode( $domain ) ) {
895 $reason = ( $this->getExistingReaderIndex( self
::GROUP_GENERIC
) >= 0 )
896 ?
'The database is read-only until replication lag decreases.'
897 : 'The database is read-only until replica database servers becomes reachable.';
898 $conn->setLBInfo( 'readOnlyReason', $reason );
905 * @param int $i Specific server index
906 * @param string $domain Resolved DB domain
907 * @param int $flags Bitfield of class CONN_* constants
908 * @return IDatabase|bool
909 * @throws InvalidArgumentException When the server index is invalid
911 public function getServerConnection( $i, $domain, $flags = 0 ) {
912 // Number of connections made before getting the server index and handle
913 $priorConnectionsMade = $this->connectionCounter
;
914 // Get an open connection to this server (might trigger a new connection)
915 $conn = $this->localDomain
->equals( $domain )
916 ?
$this->getLocalConnection( $i, $flags )
917 : $this->getForeignConnection( $i, $domain, $flags );
918 // Throw an error or otherwise bail out if the connection attempt failed
919 if ( !( $conn instanceof IDatabase
) ) {
920 if ( ( $flags & self
::CONN_SILENCE_ERRORS
) != self
::CONN_SILENCE_ERRORS
) {
921 $this->reportConnectionError();
927 // Profile any new connections caused by this method
928 if ( $this->connectionCounter
> $priorConnectionsMade ) {
929 $this->trxProfiler
->recordConnection(
932 ( ( $flags & self
::CONN_INTENT_WRITABLE
) == self
::CONN_INTENT_WRITABLE
)
936 if ( !$conn->isOpen() ) {
937 $this->errorConnection
= $conn;
938 // Connection was made but later unrecoverably lost for some reason.
939 // Do not return a handle that will just throw exceptions on use, but
940 // let the calling code, e.g. getReaderIndex(), try another server.
944 // Make sure that flags like CONN_TRX_AUTOCOMMIT are respected by this handle
945 $this->enforceConnectionFlags( $conn, $flags );
946 // Set master DB handles as read-only if the load balancer is configured as read-only
947 // or the master database server is running in server-side read-only mode. Note that
948 // replica DB handles are always read-only via Database::assertIsWritableMaster().
949 // Read-only mode due to replication lag is *avoided* here to avoid recursion.
950 if ( $conn->getLBInfo( 'serverIndex' ) === $this->getWriterIndex() ) {
951 if ( $this->readOnlyReason
!== false ) {
952 $conn->setLBInfo( 'readOnlyReason', $this->readOnlyReason
);
953 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
956 'The master database server is running in read-only mode.'
964 public function reuseConnection( IDatabase
$conn ) {
965 $serverIndex = $conn->getLBInfo( 'serverIndex' );
966 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
967 if ( $serverIndex === null ||
$refCount === null ) {
968 return; // non-foreign connection; no domain-use tracking to update
969 } elseif ( $conn instanceof DBConnRef
) {
970 // DBConnRef already handles calling reuseConnection() and only passes the live
971 // Database instance to this method. Any caller passing in a DBConnRef is broken.
972 $this->connLogger
->error(
973 __METHOD__
. ": got DBConnRef instance.\n" .
974 ( new LogicException() )->getTraceAsString() );
979 if ( $this->disabled
) {
980 return; // DBConnRef handle probably survived longer than the LoadBalancer
983 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
984 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
985 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
987 $connFreeKey = self
::KEY_FOREIGN_FREE
;
988 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
991 $domain = $conn->getDomainID();
992 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
993 throw new InvalidArgumentException(
994 "Connection $serverIndex/$domain not found; it may have already been freed" );
995 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
996 throw new InvalidArgumentException(
997 "Connection $serverIndex/$domain mismatched; it may have already been freed" );
1000 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
1001 if ( $refCount <= 0 ) {
1002 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
1003 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
1004 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
1005 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
1007 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
1009 $this->connLogger
->debug( __METHOD__
.
1010 ": reference count for $serverIndex/$domain reduced to $refCount" );
1014 public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1015 $domain = $this->resolveDomainID( $domain );
1016 $role = $this->getRoleFromIndex( $i );
1018 return new DBConnRef( $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
1021 public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1022 $domain = $this->resolveDomainID( $domain );
1023 $role = $this->getRoleFromIndex( $i );
1025 return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role );
1028 public function getMaintenanceConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1029 $domain = $this->resolveDomainID( $domain );
1030 $role = $this->getRoleFromIndex( $i );
1032 return new MaintainableDBConnRef(
1033 $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
1037 * @param int $i Server index or DB_MASTER/DB_REPLICA
1038 * @return int One of DB_MASTER/DB_REPLICA
1040 private function getRoleFromIndex( $i ) {
1041 return ( $i === self
::DB_MASTER ||
$i === $this->getWriterIndex() )
1048 * @param string|bool $domain
1050 * @return Database|bool Live database handle or false on failure
1051 * @deprecated Since 1.34 Use getConnection() instead
1053 public function openConnection( $i, $domain = false, $flags = 0 ) {
1054 return $this->getConnection( $i, [], $domain, $flags | self
::CONN_SILENCE_ERRORS
);
1058 * Open a connection to a local DB, or return one if it is already open.
1060 * On error, returns false, and the connection which caused the
1061 * error will be available via $this->errorConnection.
1063 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
1065 * @param int $i Specific server index
1066 * @param int $flags Class CONN_* constant bitfield
1068 * @throws InvalidArgumentException When the server index is invalid
1069 * @throws UnexpectedValueException When the DB domain of the connection is corrupted
1071 private function getLocalConnection( $i, $flags = 0 ) {
1072 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
1073 // Connection handles required to be in auto-commit mode use a separate connection
1074 // pool since the main pool is effected by implicit and explicit transaction rounds
1075 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
1077 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
1078 $conn = $this->conns
[$connKey][$i][0];
1080 $conn = $this->reallyOpenConnection(
1083 [ 'autoCommitOnly' => $autoCommit ]
1085 if ( $conn->isOpen() ) {
1086 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i" );
1087 $this->conns
[$connKey][$i][0] = $conn;
1089 $this->connLogger
->warning( __METHOD__
. ": connection error for $i" );
1090 $this->errorConnection
= $conn;
1095 // Sanity check to make sure that the right domain is selected
1097 $conn instanceof IDatabase
&&
1098 !$this->localDomain
->isCompatible( $conn->getDomainID() )
1100 throw new UnexpectedValueException(
1101 "Got connection to '{$conn->getDomainID()}', " .
1102 "but expected local domain ('{$this->localDomain}')"
1110 * Open a connection to a foreign DB, or return one if it is already open.
1112 * Increments a reference count on the returned connection which locks the
1113 * connection to the requested domain. This reference count can be
1114 * decremented by calling reuseConnection().
1116 * If a connection is open to the appropriate server already, but with the wrong
1117 * database, it will be switched to the right database and returned, as long as
1118 * it has been freed first with reuseConnection().
1120 * On error, returns false, and the connection which caused the
1121 * error will be available via $this->errorConnection.
1123 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
1125 * @param int $i Specific server index
1126 * @param string $domain Domain ID to open
1127 * @param int $flags Class CONN_* constant bitfield
1128 * @return Database|bool Returns false on connection error
1129 * @throws DBError When database selection fails
1130 * @throws InvalidArgumentException When the server index is invalid
1131 * @throws UnexpectedValueException When the DB domain of the connection is corrupted
1133 private function getForeignConnection( $i, $domain, $flags = 0 ) {
1134 $domainInstance = DatabaseDomain
::newFromId( $domain );
1135 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
1136 // Connection handles required to be in auto-commit mode use a separate connection
1137 // pool since the main pool is effected by implicit and explicit transaction rounds
1138 if ( $autoCommit ) {
1139 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
1140 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
1142 $connFreeKey = self
::KEY_FOREIGN_FREE
;
1143 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
1146 /** @var Database $conn */
1149 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
1150 // Reuse an in-use connection for the same domain
1151 $conn = $this->conns
[$connInUseKey][$i][$domain];
1152 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
1153 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
1154 // Reuse a free connection for the same domain
1155 $conn = $this->conns
[$connFreeKey][$i][$domain];
1156 unset( $this->conns
[$connFreeKey][$i][$domain] );
1157 $this->conns
[$connInUseKey][$i][$domain] = $conn;
1158 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
1159 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
1160 // Reuse a free connection from another domain if possible
1161 foreach ( $this->conns
[$connFreeKey][$i] as $oldDomain => $conn ) {
1162 if ( $domainInstance->getDatabase() !== null ) {
1163 // Check if changing the database will require a new connection.
1164 // In that case, leave the connection handle alone and keep looking.
1165 // This prevents connections from being closed mid-transaction and can
1166 // also avoid overhead if the same database will later be requested.
1168 $conn->databasesAreIndependent() &&
1169 $conn->getDBname() !== $domainInstance->getDatabase()
1173 // Select the new database, schema, and prefix
1174 $conn->selectDomain( $domainInstance );
1176 // Stay on the current database, but update the schema/prefix
1177 $conn->dbSchema( $domainInstance->getSchema() );
1178 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1180 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
1181 // Note that if $domain is an empty string, getDomainID() might not match it
1182 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1183 $this->connLogger
->debug( __METHOD__
.
1184 ": reusing free connection from $oldDomain for $domain" );
1190 $conn = $this->reallyOpenConnection(
1194 'autoCommitOnly' => $autoCommit,
1196 'foreignPoolRefCount' => 0
1199 if ( $conn->isOpen() ) {
1200 // Note that if $domain is an empty string, getDomainID() might not match it
1201 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1202 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1204 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
1205 $this->errorConnection
= $conn;
1210 if ( $conn instanceof IDatabase
) {
1211 // Sanity check to make sure that the right domain is selected
1212 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1213 throw new UnexpectedValueException(
1214 "Got connection to '{$conn->getDomainID()}', but expected '$domain'" );
1216 // Increment reference count
1217 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1218 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1224 public function getServerAttributes( $i ) {
1225 return Database
::attributesFromType(
1226 $this->getServerType( $i ),
1227 $this->servers
[$i]['driver'] ??
null
1232 * Test if the specified index represents an open connection
1234 * @param int $index Server index
1237 private function isOpen( $index ) {
1238 return (bool)$this->getAnyOpenConnection( $index );
1242 * Open a new network connection to a server (uncached)
1244 * Returns a Database object whether or not the connection was successful.
1246 * @param int $i Specific server index
1247 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
1248 * @param array $lbInfo Additional information for setLBInfo()
1250 * @throws DBAccessError
1251 * @throws InvalidArgumentException
1253 protected function reallyOpenConnection( $i, DatabaseDomain
$domain, array $lbInfo ) {
1254 if ( $this->disabled
) {
1255 throw new DBAccessError();
1258 $server = $this->getServerInfoStrict( $i );
1259 $server = array_merge( $server, [
1260 // Use the database specified in $domain (null means "none or entrypoint DB");
1261 // fallback to the $server default if the RDBMs is an embedded library using a file
1262 // on disk since there would be nothing to access to without a DB/file name.
1263 'dbname' => $this->getServerAttributes( $i )[Database
::ATTR_DB_IS_FILE
]
1264 ?
( $domain->getDatabase() ??
$server['dbname'] ??
null )
1265 : $domain->getDatabase(),
1266 // Override the $server default schema with that of $domain if specified
1267 'schema' => $domain->getSchema() ??
$server['schema'] ??
null,
1268 // Use the table prefix specified in $domain
1269 'tablePrefix' => $domain->getTablePrefix(),
1270 // Participate in transaction rounds if $server does not specify otherwise
1271 'flags' => $server['flags'] ?? IDatabase
::DBO_DEFAULT
,
1272 // Inject the PHP execution mode and the agent string
1273 'cliMode' => $this->cliMode
,
1274 'agent' => $this->agent
,
1275 // Inject object and callback dependencies
1276 'srvCache' => $this->srvCache
,
1277 'connLogger' => $this->connLogger
,
1278 'queryLogger' => $this->queryLogger
,
1279 'errorLogger' => $this->errorLogger
,
1280 'deprecationLogger' => $this->deprecationLogger
,
1281 'profiler' => $this->profiler
,
1282 'trxProfiler' => $this->trxProfiler
1285 $lbInfo = array_merge( $lbInfo, [
1286 'ownerId' => $this->id
,
1287 'serverIndex' => $i,
1288 'master' => ( $i === $this->getWriterIndex() ),
1289 'replica' => ( $i !== $this->getWriterIndex() ),
1290 // Name of the master server of the relevant DB cluster (e.g. "db1052")
1291 'clusterMasterHost' => $this->getServerName( $this->getWriterIndex() )
1294 $conn = Database
::factory( $server['type'], $server, Database
::NEW_UNCONNECTED
);
1296 $conn->initConnection();
1297 ++
$this->connectionCounter
;
1298 } catch ( DBConnectionError
$e ) {
1299 // ignore; let the DB handle the logging
1302 $conn->setLBInfo( $lbInfo );
1303 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1304 if ( $this->cliMode
) {
1305 $conn->clearFlag( $conn::DBO_TRX
);
1307 $conn->setFlag( $conn::DBO_TRX
);
1310 if ( $i === $this->getWriterIndex() ) {
1311 if ( $this->trxRoundId
!== false ) {
1312 $this->applyTransactionRoundFlags( $conn );
1314 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1315 $conn->setTransactionListener( $name, $callback );
1318 $conn->setTableAliases( $this->tableAliases
);
1319 $conn->setIndexAliases( $this->indexAliases
);
1321 $conn->setLazyMasterHandle(
1322 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $conn->getDomainID() )
1325 $this->lazyLoadReplicationPositions(); // session consistency
1327 // Log when many connection are made on requests
1328 $count = $this->getCurrentConnectionCount();
1329 if ( $count >= self
::CONN_HELD_WARN_THRESHOLD
) {
1330 $this->perfLogger
->warning(
1331 __METHOD__
. ": {connections}+ connections made (master={masterdb})",
1333 'connections' => $count,
1334 'dbserver' => $conn->getServer(),
1335 'masterdb' => $conn->getLBInfo( 'clusterMasterHost' )
1344 * Make sure that any "waitForPos" positions are loaded and available to doWait()
1346 private function lazyLoadReplicationPositions() {
1347 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
1348 $this->connectionAttempted
= true;
1349 ( $this->chronologyCallback
)( $this ); // generally calls waitFor()
1350 $this->connLogger
->debug( __METHOD__
. ': executed chronology callback.' );
1355 * @throws DBConnectionError
1357 private function reportConnectionError() {
1358 $conn = $this->errorConnection
; // the connection which caused the error
1360 'method' => __METHOD__
,
1361 'last_error' => $this->lastError
,
1364 if ( $conn instanceof IDatabase
) {
1365 $context['db_server'] = $conn->getServer();
1366 $this->connLogger
->warning(
1367 __METHOD__
. ": connection error: {last_error} ({db_server})",
1371 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1373 // No last connection, probably due to all servers being too busy
1374 $this->connLogger
->error(
1376 ": LB failure with no last connection. Connection error: {last_error}",
1380 // If all servers were busy, "lastError" will contain something sensible
1381 throw new DBConnectionError( null, $this->lastError
);
1385 public function getWriterIndex() {
1390 * Returns true if the specified index is a valid server index
1394 * @deprecated Since 1.34
1396 public function haveIndex( $i ) {
1397 return array_key_exists( $i, $this->servers
);
1401 * Returns true if the specified index is valid and has non-zero load
1405 * @deprecated Since 1.34
1407 public function isNonZeroLoad( $i ) {
1408 return ( isset( $this->servers
[$i] ) && $this->groupLoads
[self
::GROUP_GENERIC
][$i] > 0 );
1411 public function getServerCount() {
1412 return count( $this->servers
);
1415 public function hasReplicaServers() {
1416 return ( $this->getServerCount() > 1 );
1419 public function hasStreamingReplicaServers() {
1420 foreach ( $this->servers
as $i => $server ) {
1421 if ( $i !== $this->getWriterIndex() && empty( $server['is static'] ) ) {
1429 public function getServerName( $i ) {
1430 $name = $this->servers
[$i]['hostName'] ??
( $this->servers
[$i]['host'] ??
'' );
1432 return ( $name != '' ) ?
$name : 'localhost';
1435 public function getServerInfo( $i ) {
1436 return $this->servers
[$i] ??
false;
1439 public function getServerType( $i ) {
1440 return $this->servers
[$i]['type'] ??
'unknown';
1443 public function getMasterPos() {
1444 $index = $this->getWriterIndex();
1446 $conn = $this->getAnyOpenConnection( $index );
1448 return $conn->getMasterPos();
1451 $conn = $this->getConnection( $index, self
::CONN_SILENCE_ERRORS
);
1453 $this->reportConnectionError();
1454 return null; // unreachable due to exception
1458 $pos = $conn->getMasterPos();
1460 $this->closeConnection( $conn );
1466 public function getReplicaResumePos() {
1467 // Get the position of any existing master server connection
1468 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1469 if ( $masterConn ) {
1470 return $masterConn->getMasterPos();
1473 // Get the highest position of any existing replica server connection
1474 $highestPos = false;
1475 $serverCount = $this->getServerCount();
1476 for ( $i = 1; $i < $serverCount; $i++
) {
1477 if ( !empty( $this->servers
[$i]['is static'] ) ) {
1478 continue; // server does not use replication
1481 $conn = $this->getAnyOpenConnection( $i );
1482 $pos = $conn ?
$conn->getReplicaPos() : false;
1484 continue; // no open connection or could not get position
1487 $highestPos = $highestPos ?
: $pos;
1488 if ( $pos->hasReached( $highestPos ) ) {
1496 public function disable() {
1498 $this->disabled
= true;
1501 public function closeAll() {
1502 $fname = __METHOD__
;
1503 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( $fname ) {
1504 $host = $conn->getServer();
1505 $this->connLogger
->debug(
1506 $fname . ": closing connection to database '$host'." );
1510 $this->conns
= self
::newTrackedConnectionsArray();
1513 public function closeConnection( IDatabase
$conn ) {
1514 if ( $conn instanceof DBConnRef
) {
1515 // Avoid calling close() but still leaving the handle in the pool
1516 throw new RuntimeException( 'Cannot close DBConnRef instance; it must be shareable' );
1519 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1520 foreach ( $this->conns
as $type => $connsByServer ) {
1521 if ( !isset( $connsByServer[$serverIndex] ) ) {
1525 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1526 if ( $conn === $trackedConn ) {
1527 $host = $this->getServerName( $i );
1528 $this->connLogger
->debug(
1529 __METHOD__
. ": closing connection to database $i at '$host'." );
1530 unset( $this->conns
[$type][$serverIndex][$i] );
1539 public function commitAll( $fname = __METHOD__
, $owner = null ) {
1540 $this->commitMasterChanges( $fname, $owner );
1541 $this->flushMasterSnapshots( $fname );
1542 $this->flushReplicaSnapshots( $fname );
1545 public function finalizeMasterChanges( $fname = __METHOD__
, $owner = null ) {
1546 $this->assertOwnership( $fname, $owner );
1547 $this->assertTransactionRoundStage( [ self
::ROUND_CURSORY
, self
::ROUND_FINALIZED
] );
1549 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1550 // Loop until callbacks stop adding callbacks on other connections
1553 $count = 0; // callbacks execution attempts
1554 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$count ) {
1555 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1556 // Any error should cause all (peer) transactions to be rolled back together.
1557 $count +
= $conn->runOnTransactionPreCommitCallbacks();
1560 } while ( $count > 0 );
1561 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1562 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1563 $conn->setTrxEndCallbackSuppression( true );
1565 $this->trxRoundStage
= self
::ROUND_FINALIZED
;
1570 public function approveMasterChanges( array $options, $fname = __METHOD__
, $owner = null ) {
1571 $this->assertOwnership( $fname, $owner );
1572 $this->assertTransactionRoundStage( self
::ROUND_FINALIZED
);
1574 $limit = $options['maxWriteDuration'] ??
0;
1576 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1577 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1578 // If atomic sections or explicit transactions are still open, some caller must have
1579 // caught an exception but failed to properly rollback any changes. Detect that and
1580 // throw and error (causing rollback).
1581 $conn->assertNoOpenTransactions();
1582 // Assert that the time to replicate the transaction will be sane.
1583 // If this fails, then all DB transactions will be rollback back together.
1584 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1585 if ( $limit > 0 && $time > $limit ) {
1586 throw new DBTransactionSizeError(
1588 "Transaction spent $time second(s) in writes, exceeding the limit of $limit",
1592 // If a connection sits idle while slow queries execute on another, that connection
1593 // may end up dropped before the commit round is reached. Ping servers to detect this.
1594 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1595 throw new DBTransactionError(
1597 "A connection to the {$conn->getDBname()} database was lost before commit"
1601 $this->trxRoundStage
= self
::ROUND_APPROVED
;
1604 public function beginMasterChanges( $fname = __METHOD__
, $owner = null ) {
1605 $this->assertOwnership( $fname, $owner );
1606 if ( $this->trxRoundId
!== false ) {
1607 throw new DBTransactionError(
1609 "$fname: Transaction round '{$this->trxRoundId}' already started"
1612 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
1614 // Clear any empty transactions (no writes/callbacks) from the implicit round
1615 $this->flushMasterSnapshots( $fname );
1617 $this->trxRoundId
= $fname;
1618 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1619 // Mark applicable handles as participating in this explicit transaction round.
1620 // For each of these handles, any writes and callbacks will be tied to a single
1621 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1622 // are part of an en masse commit or an en masse rollback.
1623 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1624 $this->applyTransactionRoundFlags( $conn );
1626 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1629 public function commitMasterChanges( $fname = __METHOD__
, $owner = null ) {
1630 $this->assertOwnership( $fname, $owner );
1631 $this->assertTransactionRoundStage( self
::ROUND_APPROVED
);
1635 /** @noinspection PhpUnusedLocalVariableInspection */
1636 $scope = ScopedCallback
::newScopedIgnoreUserAbort(); // try to ignore client aborts
1638 $restore = ( $this->trxRoundId
!== false );
1639 $this->trxRoundId
= false;
1640 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1641 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1642 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1643 $this->forEachOpenMasterConnection(
1644 function ( IDatabase
$conn ) use ( $fname, &$failures ) {
1646 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1647 } catch ( DBError
$e ) {
1648 ( $this->errorLogger
)( $e );
1649 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1654 throw new DBTransactionError(
1656 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1660 // Unmark handles as participating in this explicit transaction round
1661 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1662 $this->undoTransactionRoundFlags( $conn );
1665 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
1668 public function runMasterTransactionIdleCallbacks( $fname = __METHOD__
, $owner = null ) {
1669 $this->assertOwnership( $fname, $owner );
1670 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1671 $type = IDatabase
::TRIGGER_COMMIT
;
1672 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1673 $type = IDatabase
::TRIGGER_ROLLBACK
;
1675 throw new DBTransactionError(
1677 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1681 $oldStage = $this->trxRoundStage
;
1682 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1684 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1685 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1686 $conn->setTrxEndCallbackSuppression( false );
1689 $e = null; // first exception
1690 $fname = __METHOD__
;
1691 // Loop until callbacks stop adding callbacks on other connections
1693 // Run any pending callbacks for each connection...
1694 $count = 0; // callback execution attempts
1695 $this->forEachOpenMasterConnection(
1696 function ( Database
$conn ) use ( $type, &$e, &$count ) {
1697 if ( $conn->trxLevel() ) {
1698 return; // retry in the next iteration, after commit() is called
1701 $count +
= $conn->runOnTransactionIdleCallbacks( $type );
1702 } catch ( Exception
$ex ) {
1707 // Clear out any active transactions left over from callbacks...
1708 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$e, $fname ) {
1709 if ( $conn->writesPending() ) {
1710 // A callback from another handle wrote to this one and DBO_TRX is set
1711 $this->queryLogger
->warning( $fname . ": found writes pending." );
1712 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1713 $this->queryLogger
->warning(
1714 $fname . ": found writes pending ($fnames).",
1716 'db_server' => $conn->getServer(),
1717 'db_name' => $conn->getDBname()
1720 } elseif ( $conn->trxLevel() ) {
1721 // A callback from another handle read from this one and DBO_TRX is set,
1722 // which can easily happen if there is only one DB (no replicas)
1723 $this->queryLogger
->debug( $fname . ": found empty transaction." );
1726 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1727 } catch ( Exception
$ex ) {
1731 } while ( $count > 0 );
1733 $this->trxRoundStage
= $oldStage;
1738 public function runMasterTransactionListenerCallbacks( $fname = __METHOD__
, $owner = null ) {
1739 $this->assertOwnership( $fname, $owner );
1740 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1741 $type = IDatabase
::TRIGGER_COMMIT
;
1742 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1743 $type = IDatabase
::TRIGGER_ROLLBACK
;
1745 throw new DBTransactionError(
1747 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1753 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1754 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1756 $conn->runTransactionListenerCallbacks( $type );
1757 } catch ( Exception
$ex ) {
1761 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1766 public function rollbackMasterChanges( $fname = __METHOD__
, $owner = null ) {
1767 $this->assertOwnership( $fname, $owner );
1769 $restore = ( $this->trxRoundId
!== false );
1770 $this->trxRoundId
= false;
1771 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1772 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1773 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1776 // Unmark handles as participating in this explicit transaction round
1777 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1778 $this->undoTransactionRoundFlags( $conn );
1781 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
1785 * @param string|string[] $stage
1786 * @throws DBTransactionError
1788 private function assertTransactionRoundStage( $stage ) {
1789 $stages = (array)$stage;
1791 if ( !in_array( $this->trxRoundStage
, $stages, true ) ) {
1792 $stageList = implode(
1794 array_map( function ( $v ) {
1798 throw new DBTransactionError(
1800 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1806 * @param string $fname
1807 * @param int|null $owner Owner ID of the caller
1808 * @throws DBTransactionError
1810 private function assertOwnership( $fname, $owner ) {
1811 if ( $this->ownerId
!== null && $owner !== $this->ownerId
) {
1812 throw new DBTransactionError(
1814 "$fname: LoadBalancer is owned by LBFactory #{$this->ownerId} (got '$owner')."
1820 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1822 * Some servers may have neither flag enabled, meaning that they opt out of such
1823 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1824 * when a DB server is used for something like simple key/value storage.
1826 * @param Database $conn
1828 private function applyTransactionRoundFlags( Database
$conn ) {
1829 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1830 return; // transaction rounds do not apply to these connections
1833 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1834 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1835 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1836 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1839 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1840 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1845 * @param Database $conn
1847 private function undoTransactionRoundFlags( Database
$conn ) {
1848 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1849 return; // transaction rounds do not apply to these connections
1852 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1853 $conn->setLBInfo( 'trxRoundId', null ); // remove the round ID
1856 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1857 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1861 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1862 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) use ( $fname ) {
1863 $conn->flushSnapshot( $fname );
1867 public function flushMasterSnapshots( $fname = __METHOD__
) {
1868 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1869 $conn->flushSnapshot( $fname );
1877 public function getTransactionRoundStage() {
1878 return $this->trxRoundStage
;
1881 public function hasMasterConnection() {
1882 return $this->isOpen( $this->getWriterIndex() );
1885 public function hasMasterChanges() {
1887 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1888 $pending |
= $conn->writesOrCallbacksPending();
1891 return (bool)$pending;
1894 public function lastMasterChangeTimestamp() {
1896 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1897 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1903 public function hasOrMadeRecentMasterChanges( $age = null ) {
1904 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1906 return ( $this->hasMasterChanges()
1907 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1910 public function pendingMasterChangeCallers() {
1912 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1913 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1919 public function getLaggedReplicaMode( $domain = false ) {
1920 if ( $this->laggedReplicaMode
) {
1921 return true; // stay in lagged replica mode
1924 if ( $this->hasStreamingReplicaServers() ) {
1925 // This will set "laggedReplicaMode" as needed
1926 $this->getReaderIndex( self
::GROUP_GENERIC
, $domain );
1929 return $this->laggedReplicaMode
;
1932 public function laggedReplicaUsed() {
1933 return $this->laggedReplicaMode
;
1936 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1937 if ( $this->readOnlyReason
!== false ) {
1938 return $this->readOnlyReason
;
1939 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1940 return 'The master database server is running in read-only mode.';
1941 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1942 return ( $this->getExistingReaderIndex( self
::GROUP_GENERIC
) >= 0 )
1943 ?
'The database is read-only until replication lag decreases.'
1944 : 'The database is read-only until a replica database server becomes reachable.';
1951 * @param string $domain Domain ID, or false for the current domain
1952 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1955 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1956 $cache = $this->wanCache
;
1957 $masterServer = $this->getServerName( $this->getWriterIndex() );
1959 return (bool)$cache->getWithSetCallback(
1960 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1961 self
::TTL_CACHE_READONLY
,
1962 function () use ( $domain, $conn ) {
1963 $old = $this->trxProfiler
->setSilenced( true );
1965 $index = $this->getWriterIndex();
1966 $dbw = $conn ?
: $this->getServerConnection( $index, $domain );
1967 $readOnly = (int)$dbw->serverIsReadOnly();
1969 $this->reuseConnection( $dbw );
1971 } catch ( DBError
$e ) {
1974 $this->trxProfiler
->setSilenced( $old );
1978 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1982 public function allowLagged( $mode = null ) {
1983 if ( $mode === null ) {
1984 return $this->allowLagged
;
1986 $this->allowLagged
= $mode;
1988 return $this->allowLagged
;
1991 public function pingAll() {
1993 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1994 if ( !$conn->ping() ) {
2002 public function forEachOpenConnection( $callback, array $params = [] ) {
2003 foreach ( $this->conns
as $connsByServer ) {
2004 foreach ( $connsByServer as $serverConns ) {
2005 foreach ( $serverConns as $conn ) {
2006 $callback( $conn, ...$params );
2012 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
2013 $masterIndex = $this->getWriterIndex();
2014 foreach ( $this->conns
as $connsByServer ) {
2015 if ( isset( $connsByServer[$masterIndex] ) ) {
2016 /** @var IDatabase $conn */
2017 foreach ( $connsByServer[$masterIndex] as $conn ) {
2018 $callback( $conn, ...$params );
2024 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
2025 foreach ( $this->conns
as $connsByServer ) {
2026 foreach ( $connsByServer as $i => $serverConns ) {
2027 if ( $i === $this->getWriterIndex() ) {
2028 continue; // skip master
2030 foreach ( $serverConns as $conn ) {
2031 $callback( $conn, ...$params );
2040 private function getCurrentConnectionCount() {
2042 foreach ( $this->conns
as $connsByServer ) {
2043 foreach ( $connsByServer as $serverConns ) {
2044 $count +
= count( $serverConns );
2051 public function getMaxLag( $domain = false ) {
2056 if ( $this->hasReplicaServers() ) {
2057 $lagTimes = $this->getLagTimes( $domain );
2058 foreach ( $lagTimes as $i => $lag ) {
2059 if ( $this->groupLoads
[self
::GROUP_GENERIC
][$i] > 0 && $lag > $maxLag ) {
2061 $host = $this->getServerInfoStrict( $i, 'host' );
2067 return [ $host, $maxLag, $maxIndex ];
2070 public function getLagTimes( $domain = false ) {
2071 if ( !$this->hasReplicaServers() ) {
2072 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
2075 $knownLagTimes = []; // map of (server index => 0 seconds)
2076 $indexesWithLag = [];
2077 foreach ( $this->servers
as $i => $server ) {
2078 if ( empty( $server['is static'] ) ) {
2079 $indexesWithLag[] = $i; // DB server might have replication lag
2081 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
2085 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
2089 * Get the lag in seconds for a given connection, or zero if this load
2090 * balancer does not have replication enabled.
2092 * This should be used in preference to Database::getLag() in cases where
2093 * replication may not be in use, since there is no way to determine if
2094 * replication is in use at the connection level without running
2095 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
2096 * function instead of Database::getLag() avoids a fatal error in this
2097 * case on many installations.
2099 * @param IDatabase $conn
2100 * @return int|bool Returns false on error
2101 * @deprecated Since 1.34 Use IDatabase::getLag() instead
2103 public function safeGetLag( IDatabase
$conn ) {
2104 if ( $conn->getLBInfo( 'is static' ) ) {
2105 return 0; // static dataset
2106 } elseif ( $conn->getLBInfo( 'serverIndex' ) == $this->getWriterIndex() ) {
2107 return 0; // this is the master
2110 return $conn->getLag();
2113 public function waitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
2114 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
2116 if ( $conn->getLBInfo( 'serverIndex' ) === $this->getWriterIndex() ) {
2117 return true; // not a replica DB server
2121 // Get the current master position, opening a connection if needed
2122 $index = $this->getWriterIndex();
2123 $flags = self
::CONN_SILENCE_ERRORS
;
2124 $masterConn = $this->getAnyOpenConnection( $index, $flags );
2125 if ( $masterConn ) {
2126 $pos = $masterConn->getMasterPos();
2128 $masterConn = $this->getServerConnection( $index, self
::DOMAIN_ANY
, $flags );
2129 if ( !$masterConn ) {
2130 throw new DBReplicationWaitError(
2132 "Could not obtain a master database connection to get the position"
2135 $pos = $masterConn->getMasterPos();
2136 $this->closeConnection( $masterConn );
2140 if ( $pos instanceof DBMasterPos
) {
2141 $start = microtime( true );
2142 $result = $conn->masterPosWait( $pos, $timeout );
2143 $seconds = max( microtime( true ) - $start, 0 );
2144 if ( $result == -1 ||
is_null( $result ) ) {
2145 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos} [{seconds}s]';
2146 $this->replLogger
->warning( $msg, [
2147 'host' => $conn->getServer(),
2149 'seconds' => round( $seconds, 6 ),
2150 'trace' => ( new RuntimeException() )->getTraceAsString()
2154 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
2158 $ok = false; // something is misconfigured
2159 $this->replLogger
->error(
2160 __METHOD__
. ': could not get master pos for {host}',
2162 'host' => $conn->getServer(),
2163 'trace' => ( new RuntimeException() )->getTraceAsString()
2172 * Wait for a replica DB to reach a specified master position
2174 * This will connect to the master to get an accurate position if $pos is not given
2176 * @param IDatabase $conn Replica DB
2177 * @param DBMasterPos|bool $pos Master position; default: current position
2178 * @param int $timeout Timeout in seconds [optional]
2179 * @return bool Success
2181 * @deprecated Since 1.34 Use waitForMasterPos() instead
2183 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
2184 return $this->waitForMasterPos( $conn, $pos, $timeout );
2187 public function setTransactionListener( $name, callable
$callback = null ) {
2189 $this->trxRecurringCallbacks
[$name] = $callback;
2191 unset( $this->trxRecurringCallbacks
[$name] );
2193 $this->forEachOpenMasterConnection(
2194 function ( IDatabase
$conn ) use ( $name, $callback ) {
2195 $conn->setTransactionListener( $name, $callback );
2200 public function setTableAliases( array $aliases ) {
2201 $this->tableAliases
= $aliases;
2204 public function setIndexAliases( array $aliases ) {
2205 $this->indexAliases
= $aliases;
2208 public function setLocalDomainPrefix( $prefix ) {
2209 // Find connections to explicit foreign domains still marked as in-use...
2211 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
2212 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
2213 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
2214 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
2215 $domainsInUse[] = $conn->getDomainID();
2219 // Do not switch connections to explicit foreign domains unless marked as safe
2220 if ( $domainsInUse ) {
2221 $domains = implode( ', ', $domainsInUse );
2222 throw new DBUnexpectedError( null,
2223 "Foreign domain connections are still in use ($domains)" );
2226 $this->setLocalDomain( new DatabaseDomain(
2227 $this->localDomain
->getDatabase(),
2228 $this->localDomain
->getSchema(),
2232 // Update the prefix for all local connections...
2233 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( $prefix ) {
2234 if ( !$conn->getLBInfo( 'foreign' ) ) {
2235 $conn->tablePrefix( $prefix );
2240 public function redefineLocalDomain( $domain ) {
2243 $this->setLocalDomain( DatabaseDomain
::newFromId( $domain ) );
2246 public function setTempTablesOnlyMode( $value, $domain ) {
2247 $old = $this->tempTablesOnlyMode
[$domain] ??
false;
2249 $this->tempTablesOnlyMode
[$domain] = true;
2251 unset( $this->tempTablesOnlyMode
[$domain] );
2258 * @param DatabaseDomain $domain
2260 private function setLocalDomain( DatabaseDomain
$domain ) {
2261 $this->localDomain
= $domain;
2262 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
2263 // always true, gracefully handle the case when they fail to account for escaping.
2264 if ( $this->localDomain
->getTablePrefix() != '' ) {
2265 $this->localDomainIdAlias
=
2266 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
2268 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
2273 * @param int $i Server index
2274 * @param string|null $field Server index field [optional]
2275 * @return array|mixed
2276 * @throws InvalidArgumentException
2278 private function getServerInfoStrict( $i, $field = null ) {
2279 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
2280 throw new InvalidArgumentException( "No server with index '$i'" );
2283 if ( $field !== null ) {
2284 if ( !array_key_exists( $field, $this->servers
[$i] ) ) {
2285 throw new InvalidArgumentException( "No field '$field' in server index '$i'" );
2288 return $this->servers
[$i][$field];
2291 return $this->servers
[$i];
2294 function __destruct() {
2295 // Avoid connection leaks for sanity
2301 * @deprecated since 1.29
2303 class_alias( LoadBalancer
::class, 'LoadBalancer' );