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 foreach ( ( $server['groupLoads'] ??
[] ) as $group => $ratio ) {
181 $this->groupLoads
[$group][$i] = $ratio;
183 $this->groupLoads
[self
::GROUP_GENERIC
][$i] = $server['load'];
186 $localDomain = isset( $params['localDomain'] )
187 ? DatabaseDomain
::newFromId( $params['localDomain'] )
188 : DatabaseDomain
::newUnspecified();
189 $this->setLocalDomain( $localDomain );
191 $this->waitTimeout
= $params['waitTimeout'] ?? self
::MAX_WAIT_DEFAULT
;
193 $this->conns
= self
::newTrackedConnectionsArray();
194 $this->waitForPos
= false;
195 $this->allowLagged
= false;
197 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
198 $this->readOnlyReason
= $params['readOnlyReason'];
201 $this->maxLag
= $params['maxLag'] ?? self
::MAX_LAG_DEFAULT
;
203 $this->loadMonitorConfig
= $params['loadMonitor'] ??
[ 'class' => 'LoadMonitorNull' ];
204 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
206 $this->srvCache
= $params['srvCache'] ??
new EmptyBagOStuff();
207 $this->wanCache
= $params['wanCache'] ?? WANObjectCache
::newEmpty();
208 $this->profiler
= $params['profiler'] ??
null;
209 $this->trxProfiler
= $params['trxProfiler'] ??
new TransactionProfiler();
211 $this->errorLogger
= $params['errorLogger'] ??
function ( Exception
$e ) {
212 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
214 $this->deprecationLogger
= $params['deprecationLogger'] ??
function ( $msg ) {
215 trigger_error( $msg, E_USER_DEPRECATED
);
218 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
219 $this->$key = $params[$key] ??
new NullLogger();
222 $this->hostname
= $params['hostname'] ??
( gethostname() ?
: 'unknown' );
223 $this->cliMode
= $params['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
224 $this->agent
= $params['agent'] ??
'';
226 if ( isset( $params['chronologyCallback'] ) ) {
227 $this->chronologyCallback
= $params['chronologyCallback'];
230 if ( isset( $params['roundStage'] ) ) {
231 if ( $params['roundStage'] === self
::STAGE_POSTCOMMIT_CALLBACKS
) {
232 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
233 } elseif ( $params['roundStage'] === self
::STAGE_POSTROLLBACK_CALLBACKS
) {
234 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
238 $group = $params['defaultGroup'] ?? self
::GROUP_GENERIC
;
239 $this->defaultGroup
= isset( $this->groupLoads
[$group] ) ?
$group : self
::GROUP_GENERIC
;
241 $this->ownerId
= $params['ownerId'] ??
null;
244 private static function newTrackedConnectionsArray() {
246 // Connection were transaction rounds may be applied
247 self
::KEY_LOCAL
=> [],
248 self
::KEY_FOREIGN_INUSE
=> [],
249 self
::KEY_FOREIGN_FREE
=> [],
250 // Auto-committing counterpart connections that ignore transaction rounds
251 self
::KEY_LOCAL_NOROUND
=> [],
252 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
253 self
::KEY_FOREIGN_FREE_NOROUND
=> []
257 public function getLocalDomainID() {
258 return $this->localDomain
->getId();
261 public function resolveDomainID( $domain ) {
262 if ( $domain === $this->localDomainIdAlias ||
$domain === false ) {
263 // Local connection requested via some backwards-compatibility domain alias
264 return $this->getLocalDomainID();
267 return (string)$domain;
271 * Resolve $groups into a list of query groups defining as having database servers
273 * @param string[]|string|bool $groups Query group(s) in preference order, [], or false
274 * @param int $i Specific server index or DB_MASTER/DB_REPLICA
275 * @return string[] Non-empty group list in preference order with the default group appended
277 private function resolveGroups( $groups, $i ) {
278 // If a specific replica server was specified, then $groups makes no sense
279 if ( $i > 0 && $groups !== [] && $groups !== false ) {
280 $list = implode( ', ', (array)$groups );
281 throw new LogicException( "Query group(s) ($list) given with server index (#$i)" );
284 if ( $groups === [] ||
$groups === false ||
$groups === $this->defaultGroup
) {
285 $resolvedGroups = [ $this->defaultGroup
]; // common case
286 } elseif ( is_string( $groups ) && isset( $this->groupLoads
[$groups] ) ) {
287 $resolvedGroups = [ $groups, $this->defaultGroup
];
288 } elseif ( is_array( $groups ) ) {
289 $resolvedGroups = array_keys( array_flip( $groups ) +
[ self
::GROUP_GENERIC
=> 1 ] );
291 $resolvedGroups = [ $this->defaultGroup
];
294 return $resolvedGroups;
298 * @param int $flags Bitfield of class CONN_* constants
299 * @param int $i Specific server index or DB_MASTER/DB_REPLICA
300 * @return int Sanitized bitfield
302 private function sanitizeConnectionFlags( $flags, $i ) {
303 // Whether an outside caller is explicitly requesting the master database server
304 if ( $i === self
::DB_MASTER ||
$i === $this->getWriterIndex() ) {
305 $flags |
= self
::CONN_INTENT_WRITABLE
;
308 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
) {
309 // Callers use CONN_TRX_AUTOCOMMIT to bypass REPEATABLE-READ staleness without
310 // resorting to row locks (e.g. FOR UPDATE) or to make small out-of-band commits
311 // during larger transactions. This is useful for avoiding lock contention.
313 // Master DB server attributes (should match those of the replica DB servers)
314 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
315 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
316 // The RDBMS does not support concurrent writes (e.g. SQLite), so attempts
317 // to use separate connections would just cause self-deadlocks. Note that
318 // REPEATABLE-READ staleness is not an issue since DB-level locking means
319 // that transactions are Strict Serializable anyway.
320 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
321 $type = $this->getServerType( $this->getWriterIndex() );
322 $this->connLogger
->info( __METHOD__
. ": CONN_TRX_AUTOCOMMIT disallowed ($type)" );
330 * @param IDatabase $conn
332 * @throws DBUnexpectedError
334 private function enforceConnectionFlags( IDatabase
$conn, $flags ) {
335 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
) {
336 if ( $conn->trxLevel() ) { // sanity
337 throw new DBUnexpectedError(
339 'Handle requested with CONN_TRX_AUTOCOMMIT yet it has a transaction'
343 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
348 * Get a LoadMonitor instance
350 * @return ILoadMonitor
352 private function getLoadMonitor() {
353 if ( !isset( $this->loadMonitor
) ) {
355 'LoadMonitor' => LoadMonitor
::class,
356 'LoadMonitorNull' => LoadMonitorNull
::class,
357 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
360 $class = $this->loadMonitorConfig
['class'];
361 if ( isset( $compat[$class] ) ) {
362 $class = $compat[$class];
365 $this->loadMonitor
= new $class(
366 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
367 $this->loadMonitor
->setLogger( $this->replLogger
);
370 return $this->loadMonitor
;
374 * @param array $loads
375 * @param bool|string $domain Domain to get non-lagged for
376 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
377 * @return bool|int|string
379 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
380 $lags = $this->getLagTimes( $domain );
382 # Unset excessively lagged servers
383 foreach ( $lags as $i => $lag ) {
384 if ( $i !== $this->getWriterIndex() ) {
385 # How much lag this server nominally is allowed to have
386 $maxServerLag = $this->servers
[$i]['max lag'] ??
$this->maxLag
; // default
387 # Constrain that futher by $maxLag argument
388 $maxServerLag = min( $maxServerLag, $maxLag );
390 $host = $this->getServerName( $i );
391 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
392 $this->replLogger
->debug(
394 ": server {host} is not replicating?", [ 'host' => $host ] );
396 } elseif ( $lag > $maxServerLag ) {
397 $this->replLogger
->debug(
399 ": server {host} has {lag} seconds of lag (>= {maxlag})",
400 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
407 # Find out if all the replica DBs with non-zero load are lagged
409 foreach ( $loads as $load ) {
413 # No appropriate DB servers except maybe the master and some replica DBs with zero load
414 # Do NOT use the master
415 # Instead, this function will return false, triggering read-only mode,
416 # and a lagged replica DB will be used instead.
420 if ( count( $loads ) == 0 ) {
424 # Return a random representative of the remainder
425 return ArrayUtils
::pickRandom( $loads );
429 * Get the server index to use for a specified server index and query group list
431 * @param int $i Specific server index or DB_MASTER/DB_REPLICA
432 * @param string[] $groups Non-empty query group list in preference order
433 * @param string|bool $domain
434 * @return int A specific server index (replica DBs are checked for connectivity)
436 private function getConnectionIndex( $i, array $groups, $domain ) {
437 if ( $i === self
::DB_MASTER
) {
438 $i = $this->getWriterIndex();
439 } elseif ( $i === self
::DB_REPLICA
) {
440 foreach ( $groups as $group ) {
441 $groupIndex = $this->getReaderIndex( $group, $domain );
442 if ( $groupIndex !== false ) {
443 $i = $groupIndex; // group connection succeeded
447 } elseif ( !isset( $this->servers
[$i] ) ) {
448 throw new UnexpectedValueException( "Invalid server index index #$i" );
451 if ( $i === self
::DB_REPLICA
) {
452 $this->lastError
= 'Unknown error'; // set here in case of worse failure
453 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
454 $this->reportConnectionError();
455 return null; // unreachable due to exception
461 public function getReaderIndex( $group = false, $domain = false ) {
462 if ( $this->getServerCount() == 1 ) {
463 // Skip the load balancing if there's only one server
464 return $this->getWriterIndex();
467 $group = is_string( $group ) ?
$group : self
::GROUP_GENERIC
;
469 $index = $this->getExistingReaderIndex( $group );
471 // A reader index was already selected and "waitForPos" was handled
475 // Use the server weight array for this load group
476 if ( isset( $this->groupLoads
[$group] ) ) {
477 $loads = $this->groupLoads
[$group];
479 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
484 // Scale the configured load ratios according to each server's load and state
485 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
487 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
488 $this->lazyLoadReplicationPositions(); // optimizes server candidate selection
489 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
490 if ( $i === false ) {
491 // DB connection unsuccessful
495 // If data seen by queries is expected to reflect the transactions committed as of
496 // or after a given replication position then wait for the DB to apply those changes
497 if ( $this->waitForPos
&& $i !== $this->getWriterIndex() && !$this->doWait( $i ) ) {
498 // Data will be outdated compared to what was expected
499 $laggedReplicaMode = true;
502 // Cache the reader index for future DB_REPLICA handles
503 $this->setExistingReaderIndex( $group, $i );
504 // Record whether the generic reader index is in "lagged replica DB" mode
505 if ( $group === self
::GROUP_GENERIC
&& $laggedReplicaMode ) {
506 $this->laggedReplicaMode
= true;
509 $serverName = $this->getServerName( $i );
510 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
516 * Get the server index chosen by the load balancer for use with the given query group
518 * @param string $group Query group; use false for the generic group
519 * @return int Server index or -1 if none was chosen
521 protected function getExistingReaderIndex( $group ) {
522 return $this->readIndexByGroup
[$group] ??
-1;
526 * Set the server index chosen by the load balancer for use with the given query group
528 * @param string $group Query group; use false for the generic group
529 * @param int $index The index of a specific server
531 private function setExistingReaderIndex( $group, $index ) {
533 throw new UnexpectedValueException( "Cannot set a negative read server index" );
535 $this->readIndexByGroup
[$group] = $index;
539 * @param array $loads List of server weights
540 * @param string|bool $domain
541 * @return array (reader index, lagged replica mode) or (false, false) on failure
543 private function pickReaderIndex( array $loads, $domain = false ) {
544 if ( $loads === [] ) {
545 throw new InvalidArgumentException( "Server configuration array is empty" );
548 /** @var int|bool $i Index of selected server */
550 /** @var bool $laggedReplicaMode Whether server is considered lagged */
551 $laggedReplicaMode = false;
553 // Quickly look through the available servers for a server that meets criteria...
554 $currentLoads = $loads;
555 while ( count( $currentLoads ) ) {
556 if ( $this->allowLagged ||
$laggedReplicaMode ) {
557 $i = ArrayUtils
::pickRandom( $currentLoads );
560 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
561 $this->replLogger
->debug( __METHOD__
. ": replication positions detected" );
562 // "chronologyCallback" sets "waitForPos" for session consistency.
563 // This triggers doWait() after connect, so it's especially good to
564 // avoid lagged servers so as to avoid excessive delay in that method.
565 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
566 // Aim for <= 1 second of waiting (being too picky can backfire)
567 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
569 if ( $i === false ) {
570 // Any server with less lag than it's 'max lag' param is preferable
571 $i = $this->getRandomNonLagged( $currentLoads, $domain );
573 if ( $i === false && count( $currentLoads ) ) {
574 // All replica DBs lagged. Switch to read-only mode
575 $this->replLogger
->error(
576 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
577 $i = ArrayUtils
::pickRandom( $currentLoads );
578 $laggedReplicaMode = true;
582 if ( $i === false ) {
583 // pickRandom() returned false.
584 // This is permanent and means the configuration or the load monitor
585 // wants us to return false.
586 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
588 return [ false, false ];
591 $serverName = $this->getServerName( $i );
592 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
594 // Get a connection to this server without triggering other server connections
595 $conn = $this->getServerConnection( $i, $domain, self
::CONN_SILENCE_ERRORS
);
597 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
598 unset( $currentLoads[$i] ); // avoid this server next iteration
603 // Decrement reference counter, we are finished with this connection.
604 // It will be incremented for the caller later.
605 if ( $domain !== false ) {
606 $this->reuseConnection( $conn );
609 // Return this server
613 // If all servers were down, quit now
614 if ( $currentLoads === [] ) {
615 $this->connLogger
->error( __METHOD__
. ": all servers down" );
618 return [ $i, $laggedReplicaMode ];
621 public function waitFor( $pos ) {
622 $oldPos = $this->waitForPos
;
624 $this->waitForPos
= $pos;
625 // If a generic reader connection was already established, then wait now
626 $i = $this->getExistingReaderIndex( self
::GROUP_GENERIC
);
627 if ( $i > 0 && !$this->doWait( $i ) ) {
628 $this->laggedReplicaMode
= true;
630 // Otherwise, wait until a connection is established in getReaderIndex()
632 // Restore the older position if it was higher since this is used for lag-protection
633 $this->setWaitForPositionIfHigher( $oldPos );
637 public function waitForOne( $pos, $timeout = null ) {
638 $oldPos = $this->waitForPos
;
640 $this->waitForPos
= $pos;
642 $i = $this->getExistingReaderIndex( self
::GROUP_GENERIC
);
644 // Pick a generic replica DB if there isn't one yet
645 $readLoads = $this->groupLoads
[self
::GROUP_GENERIC
];
646 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
647 $readLoads = array_filter( $readLoads ); // with non-zero load
648 $i = ArrayUtils
::pickRandom( $readLoads );
652 $ok = $this->doWait( $i, true, $timeout );
654 $ok = true; // no applicable loads
657 // Restore the old position; this is used for throttling, not lag-protection
658 $this->waitForPos
= $oldPos;
664 public function waitForAll( $pos, $timeout = null ) {
665 $timeout = $timeout ?
: $this->waitTimeout
;
667 $oldPos = $this->waitForPos
;
669 $this->waitForPos
= $pos;
670 $serverCount = $this->getServerCount();
673 for ( $i = 1; $i < $serverCount; $i++
) {
674 if ( $this->serverHasLoadInAnyGroup( $i ) ) {
675 $start = microtime( true );
676 $ok = $this->doWait( $i, true, $timeout ) && $ok;
677 $timeout -= intval( microtime( true ) - $start );
678 if ( $timeout <= 0 ) {
679 break; // timeout reached
684 // Restore the old position; this is used for throttling, not lag-protection
685 $this->waitForPos
= $oldPos;
692 * @param int $i Specific server index
695 private function serverHasLoadInAnyGroup( $i ) {
696 foreach ( $this->groupLoads
as $loadsByIndex ) {
697 if ( ( $loadsByIndex[$i] ??
0 ) > 0 ) {
706 * @param DBMasterPos|bool $pos
708 private function setWaitForPositionIfHigher( $pos ) {
713 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
714 $this->waitForPos
= $pos;
718 public function getAnyOpenConnection( $i, $flags = 0 ) {
719 $i = ( $i === self
::DB_MASTER
) ?
$this->getWriterIndex() : $i;
720 // Connection handles required to be in auto-commit mode use a separate connection
721 // pool since the main pool is effected by implicit and explicit transaction rounds
722 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
725 foreach ( $this->conns
as $connsByServer ) {
726 // Get the connection array server indexes to inspect
727 if ( $i === self
::DB_REPLICA
) {
728 $indexes = array_keys( $connsByServer );
730 $indexes = isset( $connsByServer[$i] ) ?
[ $i ] : [];
733 foreach ( $indexes as $index ) {
734 $conn = $this->pickAnyOpenConnection( $connsByServer[$index], $autocommit );
742 $this->enforceConnectionFlags( $conn, $flags );
749 * @param IDatabase[] $candidateConns
750 * @param bool $autocommit Whether to only look for auto-commit connections
751 * @return IDatabase|false An appropriate open connection or false if none found
753 private function pickAnyOpenConnection( $candidateConns, $autocommit ) {
756 foreach ( $candidateConns as $candidateConn ) {
757 if ( !$candidateConn->isOpen() ) {
758 continue; // some sort of error occured?
762 // Connection is transaction round aware
763 !$candidateConn->getLBInfo( 'autoCommitOnly' ) ||
764 // Some sort of error left a transaction open?
765 $candidateConn->trxLevel()
768 continue; // some sort of error left a transaction open?
771 $conn = $candidateConn;
778 * Wait for a given replica DB to catch up to the master pos stored in "waitForPos"
779 * @param int $index Specific server index
780 * @param bool $open Check the server even if a new connection has to be made
781 * @param int|null $timeout Max seconds to wait; default is "waitTimeout"
784 protected function doWait( $index, $open = false, $timeout = null ) {
785 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
787 // Check if we already know that the DB has reached this point
788 $server = $this->getServerName( $index );
789 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
790 /** @var DBMasterPos $knownReachedPos */
791 $knownReachedPos = $this->srvCache
->get( $key );
793 $knownReachedPos instanceof DBMasterPos
&&
794 $knownReachedPos->hasReached( $this->waitForPos
)
796 $this->replLogger
->debug(
798 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
799 [ 'dbserver' => $server ]
804 // Find a connection to wait on, creating one if needed and allowed
805 $close = false; // close the connection afterwards
806 $flags = self
::CONN_SILENCE_ERRORS
;
807 $conn = $this->getAnyOpenConnection( $index, $flags );
810 $this->replLogger
->debug(
811 __METHOD__
. ': no connection open for {dbserver}',
812 [ 'dbserver' => $server ]
817 // Get a connection to this server without triggering other server connections
818 $conn = $this->getServerConnection( $index, self
::DOMAIN_ANY
, $flags );
820 $this->replLogger
->warning(
821 __METHOD__
. ': failed to connect to {dbserver}',
822 [ 'dbserver' => $server ]
827 // Avoid connection spam in waitForAll() when connections
828 // are made just for the sake of doing this lag check.
832 $this->replLogger
->info(
834 ': waiting for replica DB {dbserver} to catch up...',
835 [ 'dbserver' => $server ]
838 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
840 if ( $result === null ) {
841 $this->replLogger
->warning(
842 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
845 'pos' => $this->waitForPos
,
846 'trace' => ( new RuntimeException() )->getTraceAsString()
850 } elseif ( $result == -1 ) {
851 $this->replLogger
->warning(
852 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
855 'pos' => $this->waitForPos
,
856 'trace' => ( new RuntimeException() )->getTraceAsString()
861 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
863 // Remember that the DB reached this point
864 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
868 $this->closeConnection( $conn );
874 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
875 $domain = $this->resolveDomainID( $domain );
876 $groups = $this->resolveGroups( $groups, $i );
877 $flags = $this->sanitizeConnectionFlags( $flags, $i );
878 // If given DB_MASTER/DB_REPLICA, resolve it to a specific server index. Resolving
879 // DB_REPLICA might trigger getServerConnection() calls due to the getReaderIndex()
880 // connectivity checks or LoadMonitor::scaleLoads() server state cache regeneration.
881 // The use of getServerConnection() instead of getConnection() avoids infinite loops.
882 $serverIndex = $this->getConnectionIndex( $i, $groups, $domain );
883 // Get an open connection to that server (might trigger a new connection)
884 $conn = $this->getServerConnection( $serverIndex, $domain, $flags );
885 // Set master DB handles as read-only if there is high replication lag
886 if ( $serverIndex === $this->getWriterIndex() && $this->getLaggedReplicaMode( $domain ) ) {
887 $reason = ( $this->getExistingReaderIndex( self
::GROUP_GENERIC
) >= 0 )
888 ?
'The database is read-only until replication lag decreases.'
889 : 'The database is read-only until replica database servers becomes reachable.';
890 $conn->setLBInfo( 'readOnlyReason', $reason );
897 * @param int $i Specific server index
898 * @param string $domain Resolved DB domain
899 * @param int $flags Bitfield of class CONN_* constants
900 * @return IDatabase|bool
901 * @throws InvalidArgumentException When the server index is invalid
903 public function getServerConnection( $i, $domain, $flags = 0 ) {
904 // Number of connections made before getting the server index and handle
905 $priorConnectionsMade = $this->connectionCounter
;
906 // Get an open connection to this server (might trigger a new connection)
907 $conn = $this->localDomain
->equals( $domain )
908 ?
$this->getLocalConnection( $i, $flags )
909 : $this->getForeignConnection( $i, $domain, $flags );
910 // Throw an error or otherwise bail out if the connection attempt failed
911 if ( !( $conn instanceof IDatabase
) ) {
912 if ( ( $flags & self
::CONN_SILENCE_ERRORS
) != self
::CONN_SILENCE_ERRORS
) {
913 $this->reportConnectionError();
919 // Profile any new connections caused by this method
920 if ( $this->connectionCounter
> $priorConnectionsMade ) {
921 $this->trxProfiler
->recordConnection(
924 ( ( $flags & self
::CONN_INTENT_WRITABLE
) == self
::CONN_INTENT_WRITABLE
)
928 if ( !$conn->isOpen() ) {
929 $this->errorConnection
= $conn;
930 // Connection was made but later unrecoverably lost for some reason.
931 // Do not return a handle that will just throw exceptions on use, but
932 // let the calling code, e.g. getReaderIndex(), try another server.
936 // Make sure that flags like CONN_TRX_AUTOCOMMIT are respected by this handle
937 $this->enforceConnectionFlags( $conn, $flags );
938 // Set master DB handles as read-only if the load balancer is configured as read-only
939 // or the master database server is running in server-side read-only mode. Note that
940 // replica DB handles are always read-only via Database::assertIsWritableMaster().
941 // Read-only mode due to replication lag is *avoided* here to avoid recursion.
942 if ( $conn->getLBInfo( 'serverIndex' ) === $this->getWriterIndex() ) {
943 if ( $this->readOnlyReason
!== false ) {
944 $conn->setLBInfo( 'readOnlyReason', $this->readOnlyReason
);
945 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
948 'The master database server is running in read-only mode.'
956 public function reuseConnection( IDatabase
$conn ) {
957 $serverIndex = $conn->getLBInfo( 'serverIndex' );
958 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
959 if ( $serverIndex === null ||
$refCount === null ) {
961 * This can happen in code like:
962 * foreach ( $dbs as $db ) {
963 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
965 * $lb->reuseConnection( $conn );
967 * When a connection to the local DB is opened in this way, reuseConnection()
971 } elseif ( $conn instanceof DBConnRef
) {
972 // DBConnRef already handles calling reuseConnection() and only passes the live
973 // Database instance to this method. Any caller passing in a DBConnRef is broken.
974 $this->connLogger
->error(
975 __METHOD__
. ": got DBConnRef instance.\n" .
976 ( new LogicException() )->getTraceAsString() );
981 if ( $this->disabled
) {
982 return; // DBConnRef handle probably survived longer than the LoadBalancer
985 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
986 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
987 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
989 $connFreeKey = self
::KEY_FOREIGN_FREE
;
990 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
993 $domain = $conn->getDomainID();
994 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
995 throw new InvalidArgumentException(
996 "Connection $serverIndex/$domain not found; it may have already been freed" );
997 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
998 throw new InvalidArgumentException(
999 "Connection $serverIndex/$domain mismatched; it may have already been freed" );
1002 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
1003 if ( $refCount <= 0 ) {
1004 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
1005 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
1006 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
1007 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
1009 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
1011 $this->connLogger
->debug( __METHOD__
.
1012 ": reference count for $serverIndex/$domain reduced to $refCount" );
1016 public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1017 $domain = $this->resolveDomainID( $domain );
1018 $role = $this->getRoleFromIndex( $i );
1020 return new DBConnRef( $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
1023 public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1024 $domain = $this->resolveDomainID( $domain );
1025 $role = $this->getRoleFromIndex( $i );
1027 return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role );
1030 public function getMaintenanceConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1031 $domain = $this->resolveDomainID( $domain );
1032 $role = $this->getRoleFromIndex( $i );
1034 return new MaintainableDBConnRef(
1035 $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
1039 * @param int $i Server index or DB_MASTER/DB_REPLICA
1040 * @return int One of DB_MASTER/DB_REPLICA
1042 private function getRoleFromIndex( $i ) {
1043 return ( $i === self
::DB_MASTER ||
$i === $this->getWriterIndex() )
1050 * @param string|bool $domain
1052 * @return Database|bool Live database handle or false on failure
1053 * @deprecated Since 1.34 Use getConnection() instead
1055 public function openConnection( $i, $domain = false, $flags = 0 ) {
1056 return $this->getConnection( $i, [], $domain, $flags | self
::CONN_SILENCE_ERRORS
);
1060 * Open a connection to a local DB, or return one if it is already open.
1062 * On error, returns false, and the connection which caused the
1063 * error will be available via $this->errorConnection.
1065 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
1067 * @param int $i Server index
1068 * @param int $flags Class CONN_* constant bitfield
1070 * @throws InvalidArgumentException When the server index is invalid
1071 * @throws UnexpectedValueException When the DB domain of the connection is corrupted
1073 private function getLocalConnection( $i, $flags = 0 ) {
1074 // Connection handles required to be in auto-commit mode use a separate connection
1075 // pool since the main pool is effected by implicit and explicit transaction rounds
1076 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
1078 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
1079 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
1080 $conn = $this->conns
[$connKey][$i][0];
1082 // Open a new connection
1083 $server = $this->getServerInfoStrict( $i );
1084 $server['serverIndex'] = $i;
1085 $server['autoCommitOnly'] = $autoCommit;
1086 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
1087 $host = $this->getServerName( $i );
1088 if ( $conn->isOpen() ) {
1089 $this->connLogger
->debug(
1090 __METHOD__
. ": connected to database $i at '$host'." );
1091 $this->conns
[$connKey][$i][0] = $conn;
1093 $this->connLogger
->warning(
1094 __METHOD__
. ": failed to connect to database $i at '$host'." );
1095 $this->errorConnection
= $conn;
1100 // Final sanity check to make sure the right domain is selected
1102 $conn instanceof IDatabase
&&
1103 !$this->localDomain
->isCompatible( $conn->getDomainID() )
1105 throw new UnexpectedValueException(
1106 "Got connection to '{$conn->getDomainID()}', " .
1107 "but expected local domain ('{$this->localDomain}')" );
1114 * Open a connection to a foreign DB, or return one if it is already open.
1116 * Increments a reference count on the returned connection which locks the
1117 * connection to the requested domain. This reference count can be
1118 * decremented by calling reuseConnection().
1120 * If a connection is open to the appropriate server already, but with the wrong
1121 * database, it will be switched to the right database and returned, as long as
1122 * it has been freed first with reuseConnection().
1124 * On error, returns false, and the connection which caused the
1125 * error will be available via $this->errorConnection.
1127 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
1129 * @param int $i Server index
1130 * @param string $domain Domain ID to open
1131 * @param int $flags Class CONN_* constant bitfield
1132 * @return Database|bool Returns false on connection error
1133 * @throws DBError When database selection fails
1134 * @throws InvalidArgumentException When the server index is invalid
1135 * @throws UnexpectedValueException When the DB domain of the connection is corrupted
1137 private function getForeignConnection( $i, $domain, $flags = 0 ) {
1138 $domainInstance = DatabaseDomain
::newFromId( $domain );
1139 // Connection handles required to be in auto-commit mode use a separate connection
1140 // pool since the main pool is effected by implicit and explicit transaction rounds
1141 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
1143 if ( $autoCommit ) {
1144 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
1145 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
1147 $connFreeKey = self
::KEY_FOREIGN_FREE
;
1148 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
1151 /** @var Database $conn */
1154 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
1155 // Reuse an in-use connection for the same domain
1156 $conn = $this->conns
[$connInUseKey][$i][$domain];
1157 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
1158 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
1159 // Reuse a free connection for the same domain
1160 $conn = $this->conns
[$connFreeKey][$i][$domain];
1161 unset( $this->conns
[$connFreeKey][$i][$domain] );
1162 $this->conns
[$connInUseKey][$i][$domain] = $conn;
1163 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
1164 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
1165 // Reuse a free connection from another domain if possible
1166 foreach ( $this->conns
[$connFreeKey][$i] as $oldDomain => $conn ) {
1167 if ( $domainInstance->getDatabase() !== null ) {
1168 // Check if changing the database will require a new connection.
1169 // In that case, leave the connection handle alone and keep looking.
1170 // This prevents connections from being closed mid-transaction and can
1171 // also avoid overhead if the same database will later be requested.
1173 $conn->databasesAreIndependent() &&
1174 $conn->getDBname() !== $domainInstance->getDatabase()
1178 // Select the new database, schema, and prefix
1179 $conn->selectDomain( $domainInstance );
1181 // Stay on the current database, but update the schema/prefix
1182 $conn->dbSchema( $domainInstance->getSchema() );
1183 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1185 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
1186 // Note that if $domain is an empty string, getDomainID() might not match it
1187 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1188 $this->connLogger
->debug( __METHOD__
.
1189 ": reusing free connection from $oldDomain for $domain" );
1195 // Open a new connection
1196 $server = $this->getServerInfoStrict( $i );
1197 $server['serverIndex'] = $i;
1198 $server['foreignPoolRefCount'] = 0;
1199 $server['foreign'] = true;
1200 $server['autoCommitOnly'] = $autoCommit;
1201 $conn = $this->reallyOpenConnection( $server, $domainInstance );
1202 if ( !$conn->isOpen() ) {
1203 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
1204 $this->errorConnection
= $conn;
1207 // Note that if $domain is an empty string, getDomainID() might not match it
1208 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1209 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1213 if ( $conn instanceof IDatabase
) {
1214 // Final sanity check to make sure the right domain is selected
1215 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1216 throw new UnexpectedValueException(
1217 "Got connection to '{$conn->getDomainID()}', but expected '$domain'" );
1219 // Increment reference count
1220 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1221 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1227 public function getServerAttributes( $i ) {
1228 return Database
::attributesFromType(
1229 $this->getServerType( $i ),
1230 $this->servers
[$i]['driver'] ??
null
1235 * Test if the specified index represents an open connection
1237 * @param int $index Server index
1240 private function isOpen( $index ) {
1241 return (bool)$this->getAnyOpenConnection( $index );
1245 * Open a new network connection to a server (uncached)
1247 * Returns a Database object whether or not the connection was successful.
1249 * @param array $server
1250 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
1252 * @throws DBAccessError
1253 * @throws InvalidArgumentException
1255 protected function reallyOpenConnection( array $server, DatabaseDomain
$domain ) {
1256 if ( $this->disabled
) {
1257 throw new DBAccessError();
1260 if ( $domain->getDatabase() === null ) {
1261 // The database domain does not specify a DB name and some database systems require a
1262 // valid DB specified on connection. The $server configuration array contains a default
1263 // DB name to use for connections in such cases.
1264 if ( $server['type'] === 'mysql' ) {
1265 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1266 // and the DB name in $server might not exist due to legacy reasons (the default
1267 // domain used to ignore the local LB domain, even when mismatched).
1268 $server['dbname'] = null;
1271 $server['dbname'] = $domain->getDatabase();
1274 if ( $domain->getSchema() !== null ) {
1275 $server['schema'] = $domain->getSchema();
1278 // It is always possible to connect with any prefix, even the empty string
1279 $server['tablePrefix'] = $domain->getTablePrefix();
1281 // Let the handle know what the cluster master is (e.g. "db1052")
1282 $masterName = $this->getServerName( $this->getWriterIndex() );
1283 $server['clusterMasterHost'] = $masterName;
1285 $server['srvCache'] = $this->srvCache
;
1286 // Set loggers and profilers
1287 $server['connLogger'] = $this->connLogger
;
1288 $server['queryLogger'] = $this->queryLogger
;
1289 $server['errorLogger'] = $this->errorLogger
;
1290 $server['deprecationLogger'] = $this->deprecationLogger
;
1291 $server['profiler'] = $this->profiler
;
1292 $server['trxProfiler'] = $this->trxProfiler
;
1293 // Use the same agent and PHP mode for all DB handles
1294 $server['cliMode'] = $this->cliMode
;
1295 $server['agent'] = $this->agent
;
1296 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1297 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1298 $server['flags'] = $server['flags'] ?? IDatabase
::DBO_DEFAULT
;
1300 // Create a live connection object
1302 $db = Database
::factory( $server['type'], $server );
1303 // Log when many connection are made on requests
1304 ++
$this->connectionCounter
;
1305 $currentConnCount = $this->getCurrentConnectionCount();
1306 if ( $currentConnCount >= self
::CONN_HELD_WARN_THRESHOLD
) {
1307 $this->perfLogger
->warning(
1308 __METHOD__
. ": {connections}+ connections made (master={masterdb})",
1309 [ 'connections' => $currentConnCount, 'masterdb' => $masterName ]
1312 } catch ( DBConnectionError
$e ) {
1313 // FIXME: This is probably the ugliest thing I have ever done to
1314 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1318 $db->setLBInfo( $server );
1319 $db->setLazyMasterHandle(
1320 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1322 $db->setTableAliases( $this->tableAliases
);
1323 $db->setIndexAliases( $this->indexAliases
);
1325 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1326 if ( $this->trxRoundId
!== false ) {
1327 $this->applyTransactionRoundFlags( $db );
1329 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1330 $db->setTransactionListener( $name, $callback );
1334 $this->lazyLoadReplicationPositions(); // session consistency
1340 * Make sure that any "waitForPos" positions are loaded and available to doWait()
1342 private function lazyLoadReplicationPositions() {
1343 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
1344 $this->connectionAttempted
= true;
1345 ( $this->chronologyCallback
)( $this ); // generally calls waitFor()
1346 $this->connLogger
->debug( __METHOD__
. ': executed chronology callback.' );
1351 * @throws DBConnectionError
1353 private function reportConnectionError() {
1354 $conn = $this->errorConnection
; // the connection which caused the error
1356 'method' => __METHOD__
,
1357 'last_error' => $this->lastError
,
1360 if ( $conn instanceof IDatabase
) {
1361 $context['db_server'] = $conn->getServer();
1362 $this->connLogger
->warning(
1363 __METHOD__
. ": connection error: {last_error} ({db_server})",
1367 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1369 // No last connection, probably due to all servers being too busy
1370 $this->connLogger
->error(
1372 ": LB failure with no last connection. Connection error: {last_error}",
1376 // If all servers were busy, "lastError" will contain something sensible
1377 throw new DBConnectionError( null, $this->lastError
);
1381 public function getWriterIndex() {
1386 * Returns true if the specified index is a valid server index
1390 * @deprecated Since 1.34
1392 public function haveIndex( $i ) {
1393 return array_key_exists( $i, $this->servers
);
1397 * Returns true if the specified index is valid and has non-zero load
1401 * @deprecated Since 1.34
1403 public function isNonZeroLoad( $i ) {
1404 return ( isset( $this->servers
[$i] ) && $this->groupLoads
[self
::GROUP_GENERIC
][$i] > 0 );
1407 public function getServerCount() {
1408 return count( $this->servers
);
1411 public function hasReplicaServers() {
1412 return ( $this->getServerCount() > 1 );
1415 public function hasStreamingReplicaServers() {
1416 foreach ( $this->servers
as $i => $server ) {
1417 if ( $i !== $this->getWriterIndex() && empty( $server['is static'] ) ) {
1425 public function getServerName( $i ) {
1426 $name = $this->servers
[$i]['hostName'] ??
( $this->servers
[$i]['host'] ??
'' );
1428 return ( $name != '' ) ?
$name : 'localhost';
1431 public function getServerInfo( $i ) {
1432 return $this->servers
[$i] ??
false;
1435 public function getServerType( $i ) {
1436 return $this->servers
[$i]['type'] ??
'unknown';
1439 public function getMasterPos() {
1440 $index = $this->getWriterIndex();
1442 $conn = $this->getAnyOpenConnection( $index );
1444 return $conn->getMasterPos();
1447 $conn = $this->getConnection( $index, self
::CONN_SILENCE_ERRORS
);
1449 $this->reportConnectionError();
1450 return null; // unreachable due to exception
1454 $pos = $conn->getMasterPos();
1456 $this->closeConnection( $conn );
1462 public function getReplicaResumePos() {
1463 // Get the position of any existing master server connection
1464 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1465 if ( $masterConn ) {
1466 return $masterConn->getMasterPos();
1469 // Get the highest position of any existing replica server connection
1470 $highestPos = false;
1471 $serverCount = $this->getServerCount();
1472 for ( $i = 1; $i < $serverCount; $i++
) {
1473 if ( !empty( $this->servers
[$i]['is static'] ) ) {
1474 continue; // server does not use replication
1477 $conn = $this->getAnyOpenConnection( $i );
1478 $pos = $conn ?
$conn->getReplicaPos() : false;
1480 continue; // no open connection or could not get position
1483 $highestPos = $highestPos ?
: $pos;
1484 if ( $pos->hasReached( $highestPos ) ) {
1492 public function disable() {
1494 $this->disabled
= true;
1497 public function closeAll() {
1498 $fname = __METHOD__
;
1499 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( $fname ) {
1500 $host = $conn->getServer();
1501 $this->connLogger
->debug(
1502 $fname . ": closing connection to database '$host'." );
1506 $this->conns
= self
::newTrackedConnectionsArray();
1509 public function closeConnection( IDatabase
$conn ) {
1510 if ( $conn instanceof DBConnRef
) {
1511 // Avoid calling close() but still leaving the handle in the pool
1512 throw new RuntimeException( 'Cannot close DBConnRef instance; it must be shareable' );
1515 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1516 foreach ( $this->conns
as $type => $connsByServer ) {
1517 if ( !isset( $connsByServer[$serverIndex] ) ) {
1521 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1522 if ( $conn === $trackedConn ) {
1523 $host = $this->getServerName( $i );
1524 $this->connLogger
->debug(
1525 __METHOD__
. ": closing connection to database $i at '$host'." );
1526 unset( $this->conns
[$type][$serverIndex][$i] );
1535 public function commitAll( $fname = __METHOD__
, $owner = null ) {
1536 $this->commitMasterChanges( $fname, $owner );
1537 $this->flushMasterSnapshots( $fname );
1538 $this->flushReplicaSnapshots( $fname );
1541 public function finalizeMasterChanges( $fname = __METHOD__
, $owner = null ) {
1542 $this->assertOwnership( $fname, $owner );
1543 $this->assertTransactionRoundStage( [ self
::ROUND_CURSORY
, self
::ROUND_FINALIZED
] );
1545 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1546 // Loop until callbacks stop adding callbacks on other connections
1549 $count = 0; // callbacks execution attempts
1550 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$count ) {
1551 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1552 // Any error should cause all (peer) transactions to be rolled back together.
1553 $count +
= $conn->runOnTransactionPreCommitCallbacks();
1556 } while ( $count > 0 );
1557 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1558 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1559 $conn->setTrxEndCallbackSuppression( true );
1561 $this->trxRoundStage
= self
::ROUND_FINALIZED
;
1566 public function approveMasterChanges( array $options, $fname = __METHOD__
, $owner = null ) {
1567 $this->assertOwnership( $fname, $owner );
1568 $this->assertTransactionRoundStage( self
::ROUND_FINALIZED
);
1570 $limit = $options['maxWriteDuration'] ??
0;
1572 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1573 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1574 // If atomic sections or explicit transactions are still open, some caller must have
1575 // caught an exception but failed to properly rollback any changes. Detect that and
1576 // throw and error (causing rollback).
1577 $conn->assertNoOpenTransactions();
1578 // Assert that the time to replicate the transaction will be sane.
1579 // If this fails, then all DB transactions will be rollback back together.
1580 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1581 if ( $limit > 0 && $time > $limit ) {
1582 throw new DBTransactionSizeError(
1584 "Transaction spent $time second(s) in writes, exceeding the limit of $limit",
1588 // If a connection sits idle while slow queries execute on another, that connection
1589 // may end up dropped before the commit round is reached. Ping servers to detect this.
1590 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1591 throw new DBTransactionError(
1593 "A connection to the {$conn->getDBname()} database was lost before commit"
1597 $this->trxRoundStage
= self
::ROUND_APPROVED
;
1600 public function beginMasterChanges( $fname = __METHOD__
, $owner = null ) {
1601 $this->assertOwnership( $fname, $owner );
1602 if ( $this->trxRoundId
!== false ) {
1603 throw new DBTransactionError(
1605 "$fname: Transaction round '{$this->trxRoundId}' already started"
1608 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
1610 // Clear any empty transactions (no writes/callbacks) from the implicit round
1611 $this->flushMasterSnapshots( $fname );
1613 $this->trxRoundId
= $fname;
1614 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1615 // Mark applicable handles as participating in this explicit transaction round.
1616 // For each of these handles, any writes and callbacks will be tied to a single
1617 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1618 // are part of an en masse commit or an en masse rollback.
1619 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1620 $this->applyTransactionRoundFlags( $conn );
1622 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1625 public function commitMasterChanges( $fname = __METHOD__
, $owner = null ) {
1626 $this->assertOwnership( $fname, $owner );
1627 $this->assertTransactionRoundStage( self
::ROUND_APPROVED
);
1631 /** @noinspection PhpUnusedLocalVariableInspection */
1632 $scope = ScopedCallback
::newScopedIgnoreUserAbort(); // try to ignore client aborts
1634 $restore = ( $this->trxRoundId
!== false );
1635 $this->trxRoundId
= false;
1636 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1637 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1638 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1639 $this->forEachOpenMasterConnection(
1640 function ( IDatabase
$conn ) use ( $fname, &$failures ) {
1642 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1643 } catch ( DBError
$e ) {
1644 ( $this->errorLogger
)( $e );
1645 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1650 throw new DBTransactionError(
1652 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1656 // Unmark handles as participating in this explicit transaction round
1657 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1658 $this->undoTransactionRoundFlags( $conn );
1661 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
1664 public function runMasterTransactionIdleCallbacks( $fname = __METHOD__
, $owner = null ) {
1665 $this->assertOwnership( $fname, $owner );
1666 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1667 $type = IDatabase
::TRIGGER_COMMIT
;
1668 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1669 $type = IDatabase
::TRIGGER_ROLLBACK
;
1671 throw new DBTransactionError(
1673 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1677 $oldStage = $this->trxRoundStage
;
1678 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1680 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1681 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1682 $conn->setTrxEndCallbackSuppression( false );
1685 $e = null; // first exception
1686 $fname = __METHOD__
;
1687 // Loop until callbacks stop adding callbacks on other connections
1689 // Run any pending callbacks for each connection...
1690 $count = 0; // callback execution attempts
1691 $this->forEachOpenMasterConnection(
1692 function ( Database
$conn ) use ( $type, &$e, &$count ) {
1693 if ( $conn->trxLevel() ) {
1694 return; // retry in the next iteration, after commit() is called
1697 $count +
= $conn->runOnTransactionIdleCallbacks( $type );
1698 } catch ( Exception
$ex ) {
1703 // Clear out any active transactions left over from callbacks...
1704 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$e, $fname ) {
1705 if ( $conn->writesPending() ) {
1706 // A callback from another handle wrote to this one and DBO_TRX is set
1707 $this->queryLogger
->warning( $fname . ": found writes pending." );
1708 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1709 $this->queryLogger
->warning(
1710 $fname . ": found writes pending ($fnames).",
1712 'db_server' => $conn->getServer(),
1713 'db_name' => $conn->getDBname()
1716 } elseif ( $conn->trxLevel() ) {
1717 // A callback from another handle read from this one and DBO_TRX is set,
1718 // which can easily happen if there is only one DB (no replicas)
1719 $this->queryLogger
->debug( $fname . ": found empty transaction." );
1722 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1723 } catch ( Exception
$ex ) {
1727 } while ( $count > 0 );
1729 $this->trxRoundStage
= $oldStage;
1734 public function runMasterTransactionListenerCallbacks( $fname = __METHOD__
, $owner = null ) {
1735 $this->assertOwnership( $fname, $owner );
1736 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1737 $type = IDatabase
::TRIGGER_COMMIT
;
1738 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1739 $type = IDatabase
::TRIGGER_ROLLBACK
;
1741 throw new DBTransactionError(
1743 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1749 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1750 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1752 $conn->runTransactionListenerCallbacks( $type );
1753 } catch ( Exception
$ex ) {
1757 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1762 public function rollbackMasterChanges( $fname = __METHOD__
, $owner = null ) {
1763 $this->assertOwnership( $fname, $owner );
1765 $restore = ( $this->trxRoundId
!== false );
1766 $this->trxRoundId
= false;
1767 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1768 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1769 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1772 // Unmark handles as participating in this explicit transaction round
1773 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1774 $this->undoTransactionRoundFlags( $conn );
1777 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
1781 * @param string|string[] $stage
1782 * @throws DBTransactionError
1784 private function assertTransactionRoundStage( $stage ) {
1785 $stages = (array)$stage;
1787 if ( !in_array( $this->trxRoundStage
, $stages, true ) ) {
1788 $stageList = implode(
1790 array_map( function ( $v ) {
1794 throw new DBTransactionError(
1796 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1802 * @param string $fname
1803 * @param int|null $owner Owner ID of the caller
1804 * @throws DBTransactionError
1806 private function assertOwnership( $fname, $owner ) {
1807 if ( $this->ownerId
!== null && $owner !== $this->ownerId
) {
1808 throw new DBTransactionError(
1810 "$fname: LoadBalancer is owned by LBFactory #{$this->ownerId} (got '$owner')."
1816 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1818 * Some servers may have neither flag enabled, meaning that they opt out of such
1819 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1820 * when a DB server is used for something like simple key/value storage.
1822 * @param Database $conn
1824 private function applyTransactionRoundFlags( Database
$conn ) {
1825 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1826 return; // transaction rounds do not apply to these connections
1829 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1830 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1831 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1832 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1835 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1836 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1841 * @param Database $conn
1843 private function undoTransactionRoundFlags( Database
$conn ) {
1844 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1845 return; // transaction rounds do not apply to these connections
1848 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1849 $conn->setLBInfo( 'trxRoundId', null ); // remove the round ID
1852 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1853 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1857 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1858 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) use ( $fname ) {
1859 $conn->flushSnapshot( $fname );
1863 public function flushMasterSnapshots( $fname = __METHOD__
) {
1864 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1865 $conn->flushSnapshot( $fname );
1873 public function getTransactionRoundStage() {
1874 return $this->trxRoundStage
;
1877 public function hasMasterConnection() {
1878 return $this->isOpen( $this->getWriterIndex() );
1881 public function hasMasterChanges() {
1883 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1884 $pending |
= $conn->writesOrCallbacksPending();
1887 return (bool)$pending;
1890 public function lastMasterChangeTimestamp() {
1892 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1893 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1899 public function hasOrMadeRecentMasterChanges( $age = null ) {
1900 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1902 return ( $this->hasMasterChanges()
1903 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1906 public function pendingMasterChangeCallers() {
1908 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1909 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1915 public function getLaggedReplicaMode( $domain = false ) {
1916 if ( $this->laggedReplicaMode
) {
1917 return true; // stay in lagged replica mode
1920 if ( $this->hasStreamingReplicaServers() ) {
1921 // This will set "laggedReplicaMode" as needed
1922 $this->getReaderIndex( self
::GROUP_GENERIC
, $domain );
1925 return $this->laggedReplicaMode
;
1928 public function laggedReplicaUsed() {
1929 return $this->laggedReplicaMode
;
1932 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1933 if ( $this->readOnlyReason
!== false ) {
1934 return $this->readOnlyReason
;
1935 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1936 return 'The master database server is running in read-only mode.';
1937 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1938 return ( $this->getExistingReaderIndex( self
::GROUP_GENERIC
) >= 0 )
1939 ?
'The database is read-only until replication lag decreases.'
1940 : 'The database is read-only until a replica database server becomes reachable.';
1947 * @param string $domain Domain ID, or false for the current domain
1948 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1951 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1952 $cache = $this->wanCache
;
1953 $masterServer = $this->getServerName( $this->getWriterIndex() );
1955 return (bool)$cache->getWithSetCallback(
1956 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1957 self
::TTL_CACHE_READONLY
,
1958 function () use ( $domain, $conn ) {
1959 $old = $this->trxProfiler
->setSilenced( true );
1961 $index = $this->getWriterIndex();
1962 $dbw = $conn ?
: $this->getServerConnection( $index, $domain );
1963 $readOnly = (int)$dbw->serverIsReadOnly();
1965 $this->reuseConnection( $dbw );
1967 } catch ( DBError
$e ) {
1970 $this->trxProfiler
->setSilenced( $old );
1974 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1978 public function allowLagged( $mode = null ) {
1979 if ( $mode === null ) {
1980 return $this->allowLagged
;
1982 $this->allowLagged
= $mode;
1984 return $this->allowLagged
;
1987 public function pingAll() {
1989 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1990 if ( !$conn->ping() ) {
1998 public function forEachOpenConnection( $callback, array $params = [] ) {
1999 foreach ( $this->conns
as $connsByServer ) {
2000 foreach ( $connsByServer as $serverConns ) {
2001 foreach ( $serverConns as $conn ) {
2002 $callback( $conn, ...$params );
2008 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
2009 $masterIndex = $this->getWriterIndex();
2010 foreach ( $this->conns
as $connsByServer ) {
2011 if ( isset( $connsByServer[$masterIndex] ) ) {
2012 /** @var IDatabase $conn */
2013 foreach ( $connsByServer[$masterIndex] as $conn ) {
2014 $callback( $conn, ...$params );
2020 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
2021 foreach ( $this->conns
as $connsByServer ) {
2022 foreach ( $connsByServer as $i => $serverConns ) {
2023 if ( $i === $this->getWriterIndex() ) {
2024 continue; // skip master
2026 foreach ( $serverConns as $conn ) {
2027 $callback( $conn, ...$params );
2036 private function getCurrentConnectionCount() {
2038 foreach ( $this->conns
as $connsByServer ) {
2039 foreach ( $connsByServer as $serverConns ) {
2040 $count +
= count( $serverConns );
2047 public function getMaxLag( $domain = false ) {
2052 if ( $this->hasReplicaServers() ) {
2053 $lagTimes = $this->getLagTimes( $domain );
2054 foreach ( $lagTimes as $i => $lag ) {
2055 if ( $this->groupLoads
[self
::GROUP_GENERIC
][$i] > 0 && $lag > $maxLag ) {
2057 $host = $this->getServerInfoStrict( $i, 'host' );
2063 return [ $host, $maxLag, $maxIndex ];
2066 public function getLagTimes( $domain = false ) {
2067 if ( !$this->hasReplicaServers() ) {
2068 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
2071 $knownLagTimes = []; // map of (server index => 0 seconds)
2072 $indexesWithLag = [];
2073 foreach ( $this->servers
as $i => $server ) {
2074 if ( empty( $server['is static'] ) ) {
2075 $indexesWithLag[] = $i; // DB server might have replication lag
2077 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
2081 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
2085 * Get the lag in seconds for a given connection, or zero if this load
2086 * balancer does not have replication enabled.
2088 * This should be used in preference to Database::getLag() in cases where
2089 * replication may not be in use, since there is no way to determine if
2090 * replication is in use at the connection level without running
2091 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
2092 * function instead of Database::getLag() avoids a fatal error in this
2093 * case on many installations.
2095 * @param IDatabase $conn
2096 * @return int|bool Returns false on error
2097 * @deprecated Since 1.34 Use IDatabase::getLag() instead
2099 public function safeGetLag( IDatabase
$conn ) {
2100 if ( $conn->getLBInfo( 'is static' ) ) {
2101 return 0; // static dataset
2102 } elseif ( $conn->getLBInfo( 'serverIndex' ) == $this->getWriterIndex() ) {
2103 return 0; // this is the master
2106 return $conn->getLag();
2109 public function waitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
2110 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
2112 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
2113 return true; // server is not a replica DB
2117 // Get the current master position, opening a connection if needed
2118 $index = $this->getWriterIndex();
2119 $flags = self
::CONN_SILENCE_ERRORS
;
2120 $masterConn = $this->getAnyOpenConnection( $index, $flags );
2121 if ( $masterConn ) {
2122 $pos = $masterConn->getMasterPos();
2124 $masterConn = $this->getServerConnection( $index, self
::DOMAIN_ANY
, $flags );
2125 if ( !$masterConn ) {
2126 throw new DBReplicationWaitError(
2128 "Could not obtain a master database connection to get the position"
2131 $pos = $masterConn->getMasterPos();
2132 $this->closeConnection( $masterConn );
2136 if ( $pos instanceof DBMasterPos
) {
2137 $start = microtime( true );
2138 $result = $conn->masterPosWait( $pos, $timeout );
2139 $seconds = max( microtime( true ) - $start, 0 );
2140 if ( $result == -1 ||
is_null( $result ) ) {
2141 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos} [{seconds}s]';
2142 $this->replLogger
->warning( $msg, [
2143 'host' => $conn->getServer(),
2145 'seconds' => round( $seconds, 6 ),
2146 'trace' => ( new RuntimeException() )->getTraceAsString()
2150 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
2154 $ok = false; // something is misconfigured
2155 $this->replLogger
->error(
2156 __METHOD__
. ': could not get master pos for {host}',
2158 'host' => $conn->getServer(),
2159 'trace' => ( new RuntimeException() )->getTraceAsString()
2168 * Wait for a replica DB to reach a specified master position
2170 * This will connect to the master to get an accurate position if $pos is not given
2172 * @param IDatabase $conn Replica DB
2173 * @param DBMasterPos|bool $pos Master position; default: current position
2174 * @param int $timeout Timeout in seconds [optional]
2175 * @return bool Success
2177 * @deprecated Since 1.34 Use waitForMasterPos() instead
2179 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
2180 return $this->waitForMasterPos( $conn, $pos, $timeout );
2183 public function setTransactionListener( $name, callable
$callback = null ) {
2185 $this->trxRecurringCallbacks
[$name] = $callback;
2187 unset( $this->trxRecurringCallbacks
[$name] );
2189 $this->forEachOpenMasterConnection(
2190 function ( IDatabase
$conn ) use ( $name, $callback ) {
2191 $conn->setTransactionListener( $name, $callback );
2196 public function setTableAliases( array $aliases ) {
2197 $this->tableAliases
= $aliases;
2200 public function setIndexAliases( array $aliases ) {
2201 $this->indexAliases
= $aliases;
2204 public function setLocalDomainPrefix( $prefix ) {
2205 // Find connections to explicit foreign domains still marked as in-use...
2207 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
2208 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
2209 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
2210 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
2211 $domainsInUse[] = $conn->getDomainID();
2215 // Do not switch connections to explicit foreign domains unless marked as safe
2216 if ( $domainsInUse ) {
2217 $domains = implode( ', ', $domainsInUse );
2218 throw new DBUnexpectedError( null,
2219 "Foreign domain connections are still in use ($domains)" );
2222 $this->setLocalDomain( new DatabaseDomain(
2223 $this->localDomain
->getDatabase(),
2224 $this->localDomain
->getSchema(),
2228 // Update the prefix for all local connections...
2229 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
2230 if ( !$db->getLBInfo( 'foreign' ) ) {
2231 $db->tablePrefix( $prefix );
2236 public function redefineLocalDomain( $domain ) {
2239 $this->setLocalDomain( DatabaseDomain
::newFromId( $domain ) );
2243 * @param DatabaseDomain $domain
2245 private function setLocalDomain( DatabaseDomain
$domain ) {
2246 $this->localDomain
= $domain;
2247 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
2248 // always true, gracefully handle the case when they fail to account for escaping.
2249 if ( $this->localDomain
->getTablePrefix() != '' ) {
2250 $this->localDomainIdAlias
=
2251 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
2253 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
2258 * @param int $i Server index
2259 * @param string|null $field Server index field [optional]
2260 * @return array|mixed
2261 * @throws InvalidArgumentException
2263 private function getServerInfoStrict( $i, $field = null ) {
2264 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
2265 throw new InvalidArgumentException( "No server with index '$i'" );
2268 if ( $field !== null ) {
2269 if ( !array_key_exists( $field, $this->servers
[$i] ) ) {
2270 throw new InvalidArgumentException( "No field '$field' in server index '$i'" );
2273 return $this->servers
[$i][$field];
2276 return $this->servers
[$i];
2279 function __destruct() {
2280 // Avoid connection leaks for sanity
2286 * @deprecated since 1.29
2288 class_alias( LoadBalancer
::class, 'LoadBalancer' );