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|null Integer ID of the managing LBFactory instance or null if none */
128 /** @var string|bool Explicit DBO_TRX transaction round active or false if none */
129 private $trxRoundId = false;
130 /** @var string Stage of the current transaction round in the transaction round life-cycle */
131 private $trxRoundStage = self
::ROUND_CURSORY
;
133 /** @var int Warn when this many connection are held */
134 const CONN_HELD_WARN_THRESHOLD
= 10;
136 /** @var int Default 'maxLag' when unspecified */
137 const MAX_LAG_DEFAULT
= 6;
138 /** @var int Default 'waitTimeout' when unspecified */
139 const MAX_WAIT_DEFAULT
= 10;
140 /** @var int Seconds to cache master DB server read-only status */
141 const TTL_CACHE_READONLY
= 5;
143 const KEY_LOCAL
= 'local';
144 const KEY_FOREIGN_FREE
= 'foreignFree';
145 const KEY_FOREIGN_INUSE
= 'foreignInUse';
147 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
148 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
149 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
151 /** @var string Transaction round, explicit or implicit, has not finished writing */
152 const ROUND_CURSORY
= 'cursory';
153 /** @var string Transaction round writes are complete and ready for pre-commit checks */
154 const ROUND_FINALIZED
= 'finalized';
155 /** @var string Transaction round passed final pre-commit checks */
156 const ROUND_APPROVED
= 'approved';
157 /** @var string Transaction round was committed and post-commit callbacks must be run */
158 const ROUND_COMMIT_CALLBACKS
= 'commit-callbacks';
159 /** @var string Transaction round was rolled back and post-rollback callbacks must be run */
160 const ROUND_ROLLBACK_CALLBACKS
= 'rollback-callbacks';
161 /** @var string Transaction round encountered an error */
162 const ROUND_ERROR
= 'error';
164 public function __construct( array $params ) {
165 if ( !isset( $params['servers'] ) ||
!count( $params['servers'] ) ) {
166 throw new InvalidArgumentException( 'Missing or empty "servers" parameter' );
171 $this->groupLoads
= [ self
::GROUP_GENERIC
=> [] ];
172 foreach ( $params['servers'] as $i => $server ) {
173 if ( ++
$listKey !== $i ) {
174 throw new UnexpectedValueException( 'List expected for "servers" parameter' );
177 $server['master'] = true;
179 $server['replica'] = true;
181 $this->servers
[$i] = $server;
182 foreach ( ( $server['groupLoads'] ??
[] ) as $group => $ratio ) {
183 $this->groupLoads
[$group][$i] = $ratio;
185 $this->groupLoads
[self
::GROUP_GENERIC
][$i] = $server['load'];
188 $localDomain = isset( $params['localDomain'] )
189 ? DatabaseDomain
::newFromId( $params['localDomain'] )
190 : DatabaseDomain
::newUnspecified();
191 $this->setLocalDomain( $localDomain );
193 $this->waitTimeout
= $params['waitTimeout'] ?? self
::MAX_WAIT_DEFAULT
;
195 $this->conns
= self
::newTrackedConnectionsArray();
196 $this->waitForPos
= false;
197 $this->allowLagged
= false;
199 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
200 $this->readOnlyReason
= $params['readOnlyReason'];
203 $this->maxLag
= $params['maxLag'] ?? self
::MAX_LAG_DEFAULT
;
205 $this->loadMonitorConfig
= $params['loadMonitor'] ??
[ 'class' => 'LoadMonitorNull' ];
206 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
208 $this->srvCache
= $params['srvCache'] ??
new EmptyBagOStuff();
209 $this->wanCache
= $params['wanCache'] ?? WANObjectCache
::newEmpty();
210 $this->profiler
= $params['profiler'] ??
null;
211 $this->trxProfiler
= $params['trxProfiler'] ??
new TransactionProfiler();
213 $this->errorLogger
= $params['errorLogger'] ??
function ( Exception
$e ) {
214 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
216 $this->deprecationLogger
= $params['deprecationLogger'] ??
function ( $msg ) {
217 trigger_error( $msg, E_USER_DEPRECATED
);
220 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
221 $this->$key = $params[$key] ??
new NullLogger();
224 $this->hostname
= $params['hostname'] ??
( gethostname() ?
: 'unknown' );
225 $this->cliMode
= $params['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
226 $this->agent
= $params['agent'] ??
'';
228 if ( isset( $params['chronologyCallback'] ) ) {
229 $this->chronologyCallback
= $params['chronologyCallback'];
232 if ( isset( $params['roundStage'] ) ) {
233 if ( $params['roundStage'] === self
::STAGE_POSTCOMMIT_CALLBACKS
) {
234 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
235 } elseif ( $params['roundStage'] === self
::STAGE_POSTROLLBACK_CALLBACKS
) {
236 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
240 $group = $params['defaultGroup'] ?? self
::GROUP_GENERIC
;
241 $this->defaultGroup
= isset( $this->groupLoads
[$group] ) ?
$group : self
::GROUP_GENERIC
;
243 $this->ownerId
= $params['ownerId'] ??
null;
246 private static function newTrackedConnectionsArray() {
248 // Connection were transaction rounds may be applied
249 self
::KEY_LOCAL
=> [],
250 self
::KEY_FOREIGN_INUSE
=> [],
251 self
::KEY_FOREIGN_FREE
=> [],
252 // Auto-committing counterpart connections that ignore transaction rounds
253 self
::KEY_LOCAL_NOROUND
=> [],
254 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
255 self
::KEY_FOREIGN_FREE_NOROUND
=> []
259 public function getLocalDomainID() {
260 return $this->localDomain
->getId();
263 public function resolveDomainID( $domain ) {
264 if ( $domain === $this->localDomainIdAlias ||
$domain === false ) {
265 // Local connection requested via some backwards-compatibility domain alias
266 return $this->getLocalDomainID();
269 return (string)$domain;
273 * Resolve $groups into a list of query groups defining as having database servers
275 * @param string[]|string|bool $groups Query group(s) in preference order, [], or false
276 * @param int $i Specific server index or DB_MASTER/DB_REPLICA
277 * @return string[] Non-empty group list in preference order with the default group appended
279 private function resolveGroups( $groups, $i ) {
280 // If a specific replica server was specified, then $groups makes no sense
281 if ( $i > 0 && $groups !== [] && $groups !== false ) {
282 $list = implode( ', ', (array)$groups );
283 throw new LogicException( "Query group(s) ($list) given with server index (#$i)" );
286 if ( $groups === [] ||
$groups === false ||
$groups === $this->defaultGroup
) {
287 $resolvedGroups = [ $this->defaultGroup
]; // common case
288 } elseif ( is_string( $groups ) && isset( $this->groupLoads
[$groups] ) ) {
289 $resolvedGroups = [ $groups, $this->defaultGroup
];
290 } elseif ( is_array( $groups ) ) {
291 $resolvedGroups = array_keys( array_flip( $groups ) +
[ self
::GROUP_GENERIC
=> 1 ] );
293 $resolvedGroups = [ $this->defaultGroup
];
296 return $resolvedGroups;
300 * @param int $flags Bitfield of class CONN_* constants
301 * @param int $i Specific server index or DB_MASTER/DB_REPLICA
302 * @param string $domain Database domain
303 * @return int Sanitized bitfield
305 private function sanitizeConnectionFlags( $flags, $i, $domain ) {
306 // Whether an outside caller is explicitly requesting the master database server
307 if ( $i === self
::DB_MASTER ||
$i === $this->getWriterIndex() ) {
308 $flags |
= self
::CONN_INTENT_WRITABLE
;
311 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
) {
312 // Callers use CONN_TRX_AUTOCOMMIT to bypass REPEATABLE-READ staleness without
313 // resorting to row locks (e.g. FOR UPDATE) or to make small out-of-band commits
314 // during larger transactions. This is useful for avoiding lock contention.
316 // Master DB server attributes (should match those of the replica DB servers)
317 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
318 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
319 // The RDBMS does not support concurrent writes (e.g. SQLite), so attempts
320 // to use separate connections would just cause self-deadlocks. Note that
321 // REPEATABLE-READ staleness is not an issue since DB-level locking means
322 // that transactions are Strict Serializable anyway.
323 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
324 $type = $this->getServerType( $this->getWriterIndex() );
325 $this->connLogger
->info( __METHOD__
. ": CONN_TRX_AUTOCOMMIT disallowed ($type)" );
326 } elseif ( isset( $this->tempTablesOnlyMode
[$domain] ) ) {
327 // T202116: integration tests are active and queries should be all be using
328 // temporary clone tables (via prefix). Such tables are not visible accross
329 // different connections nor can there be REPEATABLE-READ snapshot staleness,
330 // so use the same connection for everything.
331 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
339 * @param IDatabase $conn
341 * @throws DBUnexpectedError
343 private function enforceConnectionFlags( IDatabase
$conn, $flags ) {
344 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
) {
345 if ( $conn->trxLevel() ) { // sanity
346 throw new DBUnexpectedError(
348 'Handle requested with CONN_TRX_AUTOCOMMIT yet it has a transaction'
352 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
357 * Get a LoadMonitor instance
359 * @return ILoadMonitor
361 private function getLoadMonitor() {
362 if ( !isset( $this->loadMonitor
) ) {
364 'LoadMonitor' => LoadMonitor
::class,
365 'LoadMonitorNull' => LoadMonitorNull
::class,
366 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
369 $class = $this->loadMonitorConfig
['class'];
370 if ( isset( $compat[$class] ) ) {
371 $class = $compat[$class];
374 $this->loadMonitor
= new $class(
375 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
376 $this->loadMonitor
->setLogger( $this->replLogger
);
379 return $this->loadMonitor
;
383 * @param array $loads
384 * @param bool|string $domain Domain to get non-lagged for
385 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
386 * @return bool|int|string
388 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
389 $lags = $this->getLagTimes( $domain );
391 # Unset excessively lagged servers
392 foreach ( $lags as $i => $lag ) {
393 if ( $i !== $this->getWriterIndex() ) {
394 # How much lag this server nominally is allowed to have
395 $maxServerLag = $this->servers
[$i]['max lag'] ??
$this->maxLag
; // default
396 # Constrain that futher by $maxLag argument
397 $maxServerLag = min( $maxServerLag, $maxLag );
399 $host = $this->getServerName( $i );
400 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
401 $this->replLogger
->debug(
403 ": server {host} is not replicating?", [ 'host' => $host ] );
405 } elseif ( $lag > $maxServerLag ) {
406 $this->replLogger
->debug(
408 ": server {host} has {lag} seconds of lag (>= {maxlag})",
409 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
416 # Find out if all the replica DBs with non-zero load are lagged
418 foreach ( $loads as $load ) {
422 # No appropriate DB servers except maybe the master and some replica DBs with zero load
423 # Do NOT use the master
424 # Instead, this function will return false, triggering read-only mode,
425 # and a lagged replica DB will be used instead.
429 if ( count( $loads ) == 0 ) {
433 # Return a random representative of the remainder
434 return ArrayUtils
::pickRandom( $loads );
438 * Get the server index to use for a specified server index and query group list
440 * @param int $i Specific server index or DB_MASTER/DB_REPLICA
441 * @param string[] $groups Non-empty query group list in preference order
442 * @param string|bool $domain
443 * @return int A specific server index (replica DBs are checked for connectivity)
445 private function getConnectionIndex( $i, array $groups, $domain ) {
446 if ( $i === self
::DB_MASTER
) {
447 $i = $this->getWriterIndex();
448 } elseif ( $i === self
::DB_REPLICA
) {
449 foreach ( $groups as $group ) {
450 $groupIndex = $this->getReaderIndex( $group, $domain );
451 if ( $groupIndex !== false ) {
452 $i = $groupIndex; // group connection succeeded
456 } elseif ( !isset( $this->servers
[$i] ) ) {
457 throw new UnexpectedValueException( "Invalid server index index #$i" );
460 if ( $i === self
::DB_REPLICA
) {
461 $this->lastError
= 'Unknown error'; // set here in case of worse failure
462 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
463 $this->reportConnectionError();
464 return null; // unreachable due to exception
470 public function getReaderIndex( $group = false, $domain = false ) {
471 if ( $this->getServerCount() == 1 ) {
472 // Skip the load balancing if there's only one server
473 return $this->getWriterIndex();
476 $group = is_string( $group ) ?
$group : self
::GROUP_GENERIC
;
478 $index = $this->getExistingReaderIndex( $group );
480 // A reader index was already selected and "waitForPos" was handled
484 // Use the server weight array for this load group
485 if ( isset( $this->groupLoads
[$group] ) ) {
486 $loads = $this->groupLoads
[$group];
488 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
493 // Scale the configured load ratios according to each server's load and state
494 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
496 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
497 $this->lazyLoadReplicationPositions(); // optimizes server candidate selection
498 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
499 if ( $i === false ) {
500 // DB connection unsuccessful
504 // If data seen by queries is expected to reflect the transactions committed as of
505 // or after a given replication position then wait for the DB to apply those changes
506 if ( $this->waitForPos
&& $i !== $this->getWriterIndex() && !$this->doWait( $i ) ) {
507 // Data will be outdated compared to what was expected
508 $laggedReplicaMode = true;
511 // Cache the reader index for future DB_REPLICA handles
512 $this->setExistingReaderIndex( $group, $i );
513 // Record whether the generic reader index is in "lagged replica DB" mode
514 if ( $group === self
::GROUP_GENERIC
&& $laggedReplicaMode ) {
515 $this->laggedReplicaMode
= true;
518 $serverName = $this->getServerName( $i );
519 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
525 * Get the server index chosen by the load balancer for use with the given query group
527 * @param string $group Query group; use false for the generic group
528 * @return int Server index or -1 if none was chosen
530 protected function getExistingReaderIndex( $group ) {
531 return $this->readIndexByGroup
[$group] ??
-1;
535 * Set the server index chosen by the load balancer for use with the given query group
537 * @param string $group Query group; use false for the generic group
538 * @param int $index The index of a specific server
540 private function setExistingReaderIndex( $group, $index ) {
542 throw new UnexpectedValueException( "Cannot set a negative read server index" );
544 $this->readIndexByGroup
[$group] = $index;
548 * @param array $loads List of server weights
549 * @param string|bool $domain
550 * @return array (reader index, lagged replica mode) or (false, false) on failure
552 private function pickReaderIndex( array $loads, $domain = false ) {
553 if ( $loads === [] ) {
554 throw new InvalidArgumentException( "Server configuration array is empty" );
557 /** @var int|bool $i Index of selected server */
559 /** @var bool $laggedReplicaMode Whether server is considered lagged */
560 $laggedReplicaMode = false;
562 // Quickly look through the available servers for a server that meets criteria...
563 $currentLoads = $loads;
564 while ( count( $currentLoads ) ) {
565 if ( $this->allowLagged ||
$laggedReplicaMode ) {
566 $i = ArrayUtils
::pickRandom( $currentLoads );
569 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
570 $this->replLogger
->debug( __METHOD__
. ": replication positions detected" );
571 // "chronologyCallback" sets "waitForPos" for session consistency.
572 // This triggers doWait() after connect, so it's especially good to
573 // avoid lagged servers so as to avoid excessive delay in that method.
574 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
575 // Aim for <= 1 second of waiting (being too picky can backfire)
576 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
578 if ( $i === false ) {
579 // Any server with less lag than it's 'max lag' param is preferable
580 $i = $this->getRandomNonLagged( $currentLoads, $domain );
582 if ( $i === false && count( $currentLoads ) ) {
583 // All replica DBs lagged. Switch to read-only mode
584 $this->replLogger
->error(
585 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
586 $i = ArrayUtils
::pickRandom( $currentLoads );
587 $laggedReplicaMode = true;
591 if ( $i === false ) {
592 // pickRandom() returned false.
593 // This is permanent and means the configuration or the load monitor
594 // wants us to return false.
595 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
597 return [ false, false ];
600 $serverName = $this->getServerName( $i );
601 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
603 // Get a connection to this server without triggering other server connections
604 $conn = $this->getServerConnection( $i, $domain, self
::CONN_SILENCE_ERRORS
);
606 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
607 unset( $currentLoads[$i] ); // avoid this server next iteration
612 // Decrement reference counter, we are finished with this connection.
613 // It will be incremented for the caller later.
614 if ( $domain !== false ) {
615 $this->reuseConnection( $conn );
618 // Return this server
622 // If all servers were down, quit now
623 if ( $currentLoads === [] ) {
624 $this->connLogger
->error( __METHOD__
. ": all servers down" );
627 return [ $i, $laggedReplicaMode ];
630 public function waitFor( $pos ) {
631 $oldPos = $this->waitForPos
;
633 $this->waitForPos
= $pos;
634 // If a generic reader connection was already established, then wait now
635 $i = $this->getExistingReaderIndex( self
::GROUP_GENERIC
);
636 if ( $i > 0 && !$this->doWait( $i ) ) {
637 $this->laggedReplicaMode
= true;
639 // Otherwise, wait until a connection is established in getReaderIndex()
641 // Restore the older position if it was higher since this is used for lag-protection
642 $this->setWaitForPositionIfHigher( $oldPos );
646 public function waitForOne( $pos, $timeout = null ) {
647 $oldPos = $this->waitForPos
;
649 $this->waitForPos
= $pos;
651 $i = $this->getExistingReaderIndex( self
::GROUP_GENERIC
);
653 // Pick a generic replica DB if there isn't one yet
654 $readLoads = $this->groupLoads
[self
::GROUP_GENERIC
];
655 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
656 $readLoads = array_filter( $readLoads ); // with non-zero load
657 $i = ArrayUtils
::pickRandom( $readLoads );
661 $ok = $this->doWait( $i, true, $timeout );
663 $ok = true; // no applicable loads
666 // Restore the old position; this is used for throttling, not lag-protection
667 $this->waitForPos
= $oldPos;
673 public function waitForAll( $pos, $timeout = null ) {
674 $timeout = $timeout ?
: $this->waitTimeout
;
676 $oldPos = $this->waitForPos
;
678 $this->waitForPos
= $pos;
679 $serverCount = $this->getServerCount();
682 for ( $i = 1; $i < $serverCount; $i++
) {
683 if ( $this->serverHasLoadInAnyGroup( $i ) ) {
684 $start = microtime( true );
685 $ok = $this->doWait( $i, true, $timeout ) && $ok;
686 $timeout -= intval( microtime( true ) - $start );
687 if ( $timeout <= 0 ) {
688 break; // timeout reached
693 // Restore the old position; this is used for throttling, not lag-protection
694 $this->waitForPos
= $oldPos;
701 * @param int $i Specific server index
704 private function serverHasLoadInAnyGroup( $i ) {
705 foreach ( $this->groupLoads
as $loadsByIndex ) {
706 if ( ( $loadsByIndex[$i] ??
0 ) > 0 ) {
715 * @param DBMasterPos|bool $pos
717 private function setWaitForPositionIfHigher( $pos ) {
722 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
723 $this->waitForPos
= $pos;
727 public function getAnyOpenConnection( $i, $flags = 0 ) {
728 $i = ( $i === self
::DB_MASTER
) ?
$this->getWriterIndex() : $i;
729 // Connection handles required to be in auto-commit mode use a separate connection
730 // pool since the main pool is effected by implicit and explicit transaction rounds
731 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
734 foreach ( $this->conns
as $connsByServer ) {
735 // Get the connection array server indexes to inspect
736 if ( $i === self
::DB_REPLICA
) {
737 $indexes = array_keys( $connsByServer );
739 $indexes = isset( $connsByServer[$i] ) ?
[ $i ] : [];
742 foreach ( $indexes as $index ) {
743 $conn = $this->pickAnyOpenConnection( $connsByServer[$index], $autocommit );
751 $this->enforceConnectionFlags( $conn, $flags );
758 * @param IDatabase[] $candidateConns
759 * @param bool $autocommit Whether to only look for auto-commit connections
760 * @return IDatabase|false An appropriate open connection or false if none found
762 private function pickAnyOpenConnection( $candidateConns, $autocommit ) {
765 foreach ( $candidateConns as $candidateConn ) {
766 if ( !$candidateConn->isOpen() ) {
767 continue; // some sort of error occured?
771 // Connection is transaction round aware
772 !$candidateConn->getLBInfo( 'autoCommitOnly' ) ||
773 // Some sort of error left a transaction open?
774 $candidateConn->trxLevel()
777 continue; // some sort of error left a transaction open?
780 $conn = $candidateConn;
787 * Wait for a given replica DB to catch up to the master pos stored in "waitForPos"
788 * @param int $index Specific server index
789 * @param bool $open Check the server even if a new connection has to be made
790 * @param int|null $timeout Max seconds to wait; default is "waitTimeout"
793 protected function doWait( $index, $open = false, $timeout = null ) {
794 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
796 // Check if we already know that the DB has reached this point
797 $server = $this->getServerName( $index );
798 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
799 /** @var DBMasterPos $knownReachedPos */
800 $knownReachedPos = $this->srvCache
->get( $key );
802 $knownReachedPos instanceof DBMasterPos
&&
803 $knownReachedPos->hasReached( $this->waitForPos
)
805 $this->replLogger
->debug(
807 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
808 [ 'dbserver' => $server ]
813 // Find a connection to wait on, creating one if needed and allowed
814 $close = false; // close the connection afterwards
815 $flags = self
::CONN_SILENCE_ERRORS
;
816 $conn = $this->getAnyOpenConnection( $index, $flags );
819 $this->replLogger
->debug(
820 __METHOD__
. ': no connection open for {dbserver}',
821 [ 'dbserver' => $server ]
826 // Get a connection to this server without triggering other server connections
827 $conn = $this->getServerConnection( $index, self
::DOMAIN_ANY
, $flags );
829 $this->replLogger
->warning(
830 __METHOD__
. ': failed to connect to {dbserver}',
831 [ 'dbserver' => $server ]
836 // Avoid connection spam in waitForAll() when connections
837 // are made just for the sake of doing this lag check.
841 $this->replLogger
->info(
843 ': waiting for replica DB {dbserver} to catch up...',
844 [ 'dbserver' => $server ]
847 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
849 if ( $result === null ) {
850 $this->replLogger
->warning(
851 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
854 'pos' => $this->waitForPos
,
855 'trace' => ( new RuntimeException() )->getTraceAsString()
859 } elseif ( $result == -1 ) {
860 $this->replLogger
->warning(
861 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
864 'pos' => $this->waitForPos
,
865 'trace' => ( new RuntimeException() )->getTraceAsString()
870 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
872 // Remember that the DB reached this point
873 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
877 $this->closeConnection( $conn );
883 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
884 $domain = $this->resolveDomainID( $domain );
885 $groups = $this->resolveGroups( $groups, $i );
886 $flags = $this->sanitizeConnectionFlags( $flags, $i, $domain );
887 // If given DB_MASTER/DB_REPLICA, resolve it to a specific server index. Resolving
888 // DB_REPLICA might trigger getServerConnection() calls due to the getReaderIndex()
889 // connectivity checks or LoadMonitor::scaleLoads() server state cache regeneration.
890 // The use of getServerConnection() instead of getConnection() avoids infinite loops.
891 $serverIndex = $this->getConnectionIndex( $i, $groups, $domain );
892 // Get an open connection to that server (might trigger a new connection)
893 $conn = $this->getServerConnection( $serverIndex, $domain, $flags );
894 // Set master DB handles as read-only if there is high replication lag
895 if ( $serverIndex === $this->getWriterIndex() && $this->getLaggedReplicaMode( $domain ) ) {
896 $reason = ( $this->getExistingReaderIndex( self
::GROUP_GENERIC
) >= 0 )
897 ?
'The database is read-only until replication lag decreases.'
898 : 'The database is read-only until replica database servers becomes reachable.';
899 $conn->setLBInfo( 'readOnlyReason', $reason );
906 * @param int $i Specific server index
907 * @param string $domain Resolved DB domain
908 * @param int $flags Bitfield of class CONN_* constants
909 * @return IDatabase|bool
910 * @throws InvalidArgumentException When the server index is invalid
912 public function getServerConnection( $i, $domain, $flags = 0 ) {
913 // Number of connections made before getting the server index and handle
914 $priorConnectionsMade = $this->connectionCounter
;
915 // Get an open connection to this server (might trigger a new connection)
916 $conn = $this->localDomain
->equals( $domain )
917 ?
$this->getLocalConnection( $i, $flags )
918 : $this->getForeignConnection( $i, $domain, $flags );
919 // Throw an error or otherwise bail out if the connection attempt failed
920 if ( !( $conn instanceof IDatabase
) ) {
921 if ( ( $flags & self
::CONN_SILENCE_ERRORS
) != self
::CONN_SILENCE_ERRORS
) {
922 $this->reportConnectionError();
928 // Profile any new connections caused by this method
929 if ( $this->connectionCounter
> $priorConnectionsMade ) {
930 $this->trxProfiler
->recordConnection(
933 ( ( $flags & self
::CONN_INTENT_WRITABLE
) == self
::CONN_INTENT_WRITABLE
)
937 if ( !$conn->isOpen() ) {
938 $this->errorConnection
= $conn;
939 // Connection was made but later unrecoverably lost for some reason.
940 // Do not return a handle that will just throw exceptions on use, but
941 // let the calling code, e.g. getReaderIndex(), try another server.
945 // Make sure that flags like CONN_TRX_AUTOCOMMIT are respected by this handle
946 $this->enforceConnectionFlags( $conn, $flags );
947 // Set master DB handles as read-only if the load balancer is configured as read-only
948 // or the master database server is running in server-side read-only mode. Note that
949 // replica DB handles are always read-only via Database::assertIsWritableMaster().
950 // Read-only mode due to replication lag is *avoided* here to avoid recursion.
951 if ( $conn->getLBInfo( 'serverIndex' ) === $this->getWriterIndex() ) {
952 if ( $this->readOnlyReason
!== false ) {
953 $conn->setLBInfo( 'readOnlyReason', $this->readOnlyReason
);
954 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
957 'The master database server is running in read-only mode.'
965 public function reuseConnection( IDatabase
$conn ) {
966 $serverIndex = $conn->getLBInfo( 'serverIndex' );
967 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
968 if ( $serverIndex === null ||
$refCount === null ) {
970 * This can happen in code like:
971 * foreach ( $dbs as $db ) {
972 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
974 * $lb->reuseConnection( $conn );
976 * When a connection to the local DB is opened in this way, reuseConnection()
980 } elseif ( $conn instanceof DBConnRef
) {
981 // DBConnRef already handles calling reuseConnection() and only passes the live
982 // Database instance to this method. Any caller passing in a DBConnRef is broken.
983 $this->connLogger
->error(
984 __METHOD__
. ": got DBConnRef instance.\n" .
985 ( new LogicException() )->getTraceAsString() );
990 if ( $this->disabled
) {
991 return; // DBConnRef handle probably survived longer than the LoadBalancer
994 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
995 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
996 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
998 $connFreeKey = self
::KEY_FOREIGN_FREE
;
999 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
1002 $domain = $conn->getDomainID();
1003 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
1004 throw new InvalidArgumentException(
1005 "Connection $serverIndex/$domain not found; it may have already been freed" );
1006 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
1007 throw new InvalidArgumentException(
1008 "Connection $serverIndex/$domain mismatched; it may have already been freed" );
1011 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
1012 if ( $refCount <= 0 ) {
1013 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
1014 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
1015 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
1016 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
1018 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
1020 $this->connLogger
->debug( __METHOD__
.
1021 ": reference count for $serverIndex/$domain reduced to $refCount" );
1025 public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1026 $domain = $this->resolveDomainID( $domain );
1027 $role = $this->getRoleFromIndex( $i );
1029 return new DBConnRef( $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
1032 public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1033 $domain = $this->resolveDomainID( $domain );
1034 $role = $this->getRoleFromIndex( $i );
1036 return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role );
1039 public function getMaintenanceConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1040 $domain = $this->resolveDomainID( $domain );
1041 $role = $this->getRoleFromIndex( $i );
1043 return new MaintainableDBConnRef(
1044 $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
1048 * @param int $i Server index or DB_MASTER/DB_REPLICA
1049 * @return int One of DB_MASTER/DB_REPLICA
1051 private function getRoleFromIndex( $i ) {
1052 return ( $i === self
::DB_MASTER ||
$i === $this->getWriterIndex() )
1059 * @param string|bool $domain
1061 * @return Database|bool Live database handle or false on failure
1062 * @deprecated Since 1.34 Use getConnection() instead
1064 public function openConnection( $i, $domain = false, $flags = 0 ) {
1065 return $this->getConnection( $i, [], $domain, $flags | self
::CONN_SILENCE_ERRORS
);
1069 * Open a connection to a local DB, or return one if it is already open.
1071 * On error, returns false, and the connection which caused the
1072 * error will be available via $this->errorConnection.
1074 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
1076 * @param int $i Server index
1077 * @param int $flags Class CONN_* constant bitfield
1079 * @throws InvalidArgumentException When the server index is invalid
1080 * @throws UnexpectedValueException When the DB domain of the connection is corrupted
1082 private function getLocalConnection( $i, $flags = 0 ) {
1083 // Connection handles required to be in auto-commit mode use a separate connection
1084 // pool since the main pool is effected by implicit and explicit transaction rounds
1085 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
1087 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
1088 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
1089 $conn = $this->conns
[$connKey][$i][0];
1091 // Open a new connection
1092 $server = $this->getServerInfoStrict( $i );
1093 $server['serverIndex'] = $i;
1094 $server['autoCommitOnly'] = $autoCommit;
1095 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
1096 $host = $this->getServerName( $i );
1097 if ( $conn->isOpen() ) {
1098 $this->connLogger
->debug(
1099 __METHOD__
. ": connected to database $i at '$host'." );
1100 $this->conns
[$connKey][$i][0] = $conn;
1102 $this->connLogger
->warning(
1103 __METHOD__
. ": failed to connect to database $i at '$host'." );
1104 $this->errorConnection
= $conn;
1109 // Final sanity check to make sure the right domain is selected
1111 $conn instanceof IDatabase
&&
1112 !$this->localDomain
->isCompatible( $conn->getDomainID() )
1114 throw new UnexpectedValueException(
1115 "Got connection to '{$conn->getDomainID()}', " .
1116 "but expected local domain ('{$this->localDomain}')" );
1123 * Open a connection to a foreign DB, or return one if it is already open.
1125 * Increments a reference count on the returned connection which locks the
1126 * connection to the requested domain. This reference count can be
1127 * decremented by calling reuseConnection().
1129 * If a connection is open to the appropriate server already, but with the wrong
1130 * database, it will be switched to the right database and returned, as long as
1131 * it has been freed first with reuseConnection().
1133 * On error, returns false, and the connection which caused the
1134 * error will be available via $this->errorConnection.
1136 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
1138 * @param int $i Server index
1139 * @param string $domain Domain ID to open
1140 * @param int $flags Class CONN_* constant bitfield
1141 * @return Database|bool Returns false on connection error
1142 * @throws DBError When database selection fails
1143 * @throws InvalidArgumentException When the server index is invalid
1144 * @throws UnexpectedValueException When the DB domain of the connection is corrupted
1146 private function getForeignConnection( $i, $domain, $flags = 0 ) {
1147 $domainInstance = DatabaseDomain
::newFromId( $domain );
1148 // Connection handles required to be in auto-commit mode use a separate connection
1149 // pool since the main pool is effected by implicit and explicit transaction rounds
1150 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
1152 if ( $autoCommit ) {
1153 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
1154 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
1156 $connFreeKey = self
::KEY_FOREIGN_FREE
;
1157 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
1160 /** @var Database $conn */
1163 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
1164 // Reuse an in-use connection for the same domain
1165 $conn = $this->conns
[$connInUseKey][$i][$domain];
1166 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
1167 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
1168 // Reuse a free connection for the same domain
1169 $conn = $this->conns
[$connFreeKey][$i][$domain];
1170 unset( $this->conns
[$connFreeKey][$i][$domain] );
1171 $this->conns
[$connInUseKey][$i][$domain] = $conn;
1172 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
1173 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
1174 // Reuse a free connection from another domain if possible
1175 foreach ( $this->conns
[$connFreeKey][$i] as $oldDomain => $conn ) {
1176 if ( $domainInstance->getDatabase() !== null ) {
1177 // Check if changing the database will require a new connection.
1178 // In that case, leave the connection handle alone and keep looking.
1179 // This prevents connections from being closed mid-transaction and can
1180 // also avoid overhead if the same database will later be requested.
1182 $conn->databasesAreIndependent() &&
1183 $conn->getDBname() !== $domainInstance->getDatabase()
1187 // Select the new database, schema, and prefix
1188 $conn->selectDomain( $domainInstance );
1190 // Stay on the current database, but update the schema/prefix
1191 $conn->dbSchema( $domainInstance->getSchema() );
1192 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1194 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
1195 // Note that if $domain is an empty string, getDomainID() might not match it
1196 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1197 $this->connLogger
->debug( __METHOD__
.
1198 ": reusing free connection from $oldDomain for $domain" );
1204 // Open a new connection
1205 $server = $this->getServerInfoStrict( $i );
1206 $server['serverIndex'] = $i;
1207 $server['foreignPoolRefCount'] = 0;
1208 $server['foreign'] = true;
1209 $server['autoCommitOnly'] = $autoCommit;
1210 $conn = $this->reallyOpenConnection( $server, $domainInstance );
1211 if ( !$conn->isOpen() ) {
1212 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
1213 $this->errorConnection
= $conn;
1216 // Note that if $domain is an empty string, getDomainID() might not match it
1217 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1218 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1222 if ( $conn instanceof IDatabase
) {
1223 // Final sanity check to make sure the right domain is selected
1224 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1225 throw new UnexpectedValueException(
1226 "Got connection to '{$conn->getDomainID()}', but expected '$domain'" );
1228 // Increment reference count
1229 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1230 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1236 public function getServerAttributes( $i ) {
1237 return Database
::attributesFromType(
1238 $this->getServerType( $i ),
1239 $this->servers
[$i]['driver'] ??
null
1244 * Test if the specified index represents an open connection
1246 * @param int $index Server index
1249 private function isOpen( $index ) {
1250 return (bool)$this->getAnyOpenConnection( $index );
1254 * Open a new network connection to a server (uncached)
1256 * Returns a Database object whether or not the connection was successful.
1258 * @param array $server
1259 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
1261 * @throws DBAccessError
1262 * @throws InvalidArgumentException
1264 protected function reallyOpenConnection( array $server, DatabaseDomain
$domain ) {
1265 if ( $this->disabled
) {
1266 throw new DBAccessError();
1269 if ( $domain->getDatabase() === null ) {
1270 // The database domain does not specify a DB name and some database systems require a
1271 // valid DB specified on connection. The $server configuration array contains a default
1272 // DB name to use for connections in such cases.
1273 if ( $server['type'] === 'mysql' ) {
1274 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1275 // and the DB name in $server might not exist due to legacy reasons (the default
1276 // domain used to ignore the local LB domain, even when mismatched).
1277 $server['dbname'] = null;
1280 $server['dbname'] = $domain->getDatabase();
1283 if ( $domain->getSchema() !== null ) {
1284 $server['schema'] = $domain->getSchema();
1287 // It is always possible to connect with any prefix, even the empty string
1288 $server['tablePrefix'] = $domain->getTablePrefix();
1290 // Let the handle know what the cluster master is (e.g. "db1052")
1291 $masterName = $this->getServerName( $this->getWriterIndex() );
1292 $server['clusterMasterHost'] = $masterName;
1294 $server['srvCache'] = $this->srvCache
;
1295 // Set loggers and profilers
1296 $server['connLogger'] = $this->connLogger
;
1297 $server['queryLogger'] = $this->queryLogger
;
1298 $server['errorLogger'] = $this->errorLogger
;
1299 $server['deprecationLogger'] = $this->deprecationLogger
;
1300 $server['profiler'] = $this->profiler
;
1301 $server['trxProfiler'] = $this->trxProfiler
;
1302 // Use the same agent and PHP mode for all DB handles
1303 $server['cliMode'] = $this->cliMode
;
1304 $server['agent'] = $this->agent
;
1305 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1306 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1307 $server['flags'] = $server['flags'] ?? IDatabase
::DBO_DEFAULT
;
1309 // Create a live connection object
1311 $db = Database
::factory( $server['type'], $server );
1312 // Log when many connection are made on requests
1313 ++
$this->connectionCounter
;
1314 $currentConnCount = $this->getCurrentConnectionCount();
1315 if ( $currentConnCount >= self
::CONN_HELD_WARN_THRESHOLD
) {
1316 $this->perfLogger
->warning(
1317 __METHOD__
. ": {connections}+ connections made (master={masterdb})",
1318 [ 'connections' => $currentConnCount, 'masterdb' => $masterName ]
1321 } catch ( DBConnectionError
$e ) {
1322 // FIXME: This is probably the ugliest thing I have ever done to
1323 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1327 $db->setLBInfo( $server );
1328 $db->setLazyMasterHandle(
1329 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1331 $db->setTableAliases( $this->tableAliases
);
1332 $db->setIndexAliases( $this->indexAliases
);
1334 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1335 if ( $this->trxRoundId
!== false ) {
1336 $this->applyTransactionRoundFlags( $db );
1338 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1339 $db->setTransactionListener( $name, $callback );
1343 $this->lazyLoadReplicationPositions(); // session consistency
1349 * Make sure that any "waitForPos" positions are loaded and available to doWait()
1351 private function lazyLoadReplicationPositions() {
1352 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
1353 $this->connectionAttempted
= true;
1354 ( $this->chronologyCallback
)( $this ); // generally calls waitFor()
1355 $this->connLogger
->debug( __METHOD__
. ': executed chronology callback.' );
1360 * @throws DBConnectionError
1362 private function reportConnectionError() {
1363 $conn = $this->errorConnection
; // the connection which caused the error
1365 'method' => __METHOD__
,
1366 'last_error' => $this->lastError
,
1369 if ( $conn instanceof IDatabase
) {
1370 $context['db_server'] = $conn->getServer();
1371 $this->connLogger
->warning(
1372 __METHOD__
. ": connection error: {last_error} ({db_server})",
1376 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1378 // No last connection, probably due to all servers being too busy
1379 $this->connLogger
->error(
1381 ": LB failure with no last connection. Connection error: {last_error}",
1385 // If all servers were busy, "lastError" will contain something sensible
1386 throw new DBConnectionError( null, $this->lastError
);
1390 public function getWriterIndex() {
1395 * Returns true if the specified index is a valid server index
1399 * @deprecated Since 1.34
1401 public function haveIndex( $i ) {
1402 return array_key_exists( $i, $this->servers
);
1406 * Returns true if the specified index is valid and has non-zero load
1410 * @deprecated Since 1.34
1412 public function isNonZeroLoad( $i ) {
1413 return ( isset( $this->servers
[$i] ) && $this->groupLoads
[self
::GROUP_GENERIC
][$i] > 0 );
1416 public function getServerCount() {
1417 return count( $this->servers
);
1420 public function hasReplicaServers() {
1421 return ( $this->getServerCount() > 1 );
1424 public function hasStreamingReplicaServers() {
1425 foreach ( $this->servers
as $i => $server ) {
1426 if ( $i !== $this->getWriterIndex() && empty( $server['is static'] ) ) {
1434 public function getServerName( $i ) {
1435 $name = $this->servers
[$i]['hostName'] ??
( $this->servers
[$i]['host'] ??
'' );
1437 return ( $name != '' ) ?
$name : 'localhost';
1440 public function getServerInfo( $i ) {
1441 return $this->servers
[$i] ??
false;
1444 public function getServerType( $i ) {
1445 return $this->servers
[$i]['type'] ??
'unknown';
1448 public function getMasterPos() {
1449 $index = $this->getWriterIndex();
1451 $conn = $this->getAnyOpenConnection( $index );
1453 return $conn->getMasterPos();
1456 $conn = $this->getConnection( $index, self
::CONN_SILENCE_ERRORS
);
1458 $this->reportConnectionError();
1459 return null; // unreachable due to exception
1463 $pos = $conn->getMasterPos();
1465 $this->closeConnection( $conn );
1471 public function getReplicaResumePos() {
1472 // Get the position of any existing master server connection
1473 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1474 if ( $masterConn ) {
1475 return $masterConn->getMasterPos();
1478 // Get the highest position of any existing replica server connection
1479 $highestPos = false;
1480 $serverCount = $this->getServerCount();
1481 for ( $i = 1; $i < $serverCount; $i++
) {
1482 if ( !empty( $this->servers
[$i]['is static'] ) ) {
1483 continue; // server does not use replication
1486 $conn = $this->getAnyOpenConnection( $i );
1487 $pos = $conn ?
$conn->getReplicaPos() : false;
1489 continue; // no open connection or could not get position
1492 $highestPos = $highestPos ?
: $pos;
1493 if ( $pos->hasReached( $highestPos ) ) {
1501 public function disable() {
1503 $this->disabled
= true;
1506 public function closeAll() {
1507 $fname = __METHOD__
;
1508 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( $fname ) {
1509 $host = $conn->getServer();
1510 $this->connLogger
->debug(
1511 $fname . ": closing connection to database '$host'." );
1515 $this->conns
= self
::newTrackedConnectionsArray();
1518 public function closeConnection( IDatabase
$conn ) {
1519 if ( $conn instanceof DBConnRef
) {
1520 // Avoid calling close() but still leaving the handle in the pool
1521 throw new RuntimeException( 'Cannot close DBConnRef instance; it must be shareable' );
1524 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1525 foreach ( $this->conns
as $type => $connsByServer ) {
1526 if ( !isset( $connsByServer[$serverIndex] ) ) {
1530 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1531 if ( $conn === $trackedConn ) {
1532 $host = $this->getServerName( $i );
1533 $this->connLogger
->debug(
1534 __METHOD__
. ": closing connection to database $i at '$host'." );
1535 unset( $this->conns
[$type][$serverIndex][$i] );
1544 public function commitAll( $fname = __METHOD__
, $owner = null ) {
1545 $this->commitMasterChanges( $fname, $owner );
1546 $this->flushMasterSnapshots( $fname );
1547 $this->flushReplicaSnapshots( $fname );
1550 public function finalizeMasterChanges( $fname = __METHOD__
, $owner = null ) {
1551 $this->assertOwnership( $fname, $owner );
1552 $this->assertTransactionRoundStage( [ self
::ROUND_CURSORY
, self
::ROUND_FINALIZED
] );
1554 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1555 // Loop until callbacks stop adding callbacks on other connections
1558 $count = 0; // callbacks execution attempts
1559 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$count ) {
1560 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1561 // Any error should cause all (peer) transactions to be rolled back together.
1562 $count +
= $conn->runOnTransactionPreCommitCallbacks();
1565 } while ( $count > 0 );
1566 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1567 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1568 $conn->setTrxEndCallbackSuppression( true );
1570 $this->trxRoundStage
= self
::ROUND_FINALIZED
;
1575 public function approveMasterChanges( array $options, $fname = __METHOD__
, $owner = null ) {
1576 $this->assertOwnership( $fname, $owner );
1577 $this->assertTransactionRoundStage( self
::ROUND_FINALIZED
);
1579 $limit = $options['maxWriteDuration'] ??
0;
1581 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1582 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1583 // If atomic sections or explicit transactions are still open, some caller must have
1584 // caught an exception but failed to properly rollback any changes. Detect that and
1585 // throw and error (causing rollback).
1586 $conn->assertNoOpenTransactions();
1587 // Assert that the time to replicate the transaction will be sane.
1588 // If this fails, then all DB transactions will be rollback back together.
1589 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1590 if ( $limit > 0 && $time > $limit ) {
1591 throw new DBTransactionSizeError(
1593 "Transaction spent $time second(s) in writes, exceeding the limit of $limit",
1597 // If a connection sits idle while slow queries execute on another, that connection
1598 // may end up dropped before the commit round is reached. Ping servers to detect this.
1599 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1600 throw new DBTransactionError(
1602 "A connection to the {$conn->getDBname()} database was lost before commit"
1606 $this->trxRoundStage
= self
::ROUND_APPROVED
;
1609 public function beginMasterChanges( $fname = __METHOD__
, $owner = null ) {
1610 $this->assertOwnership( $fname, $owner );
1611 if ( $this->trxRoundId
!== false ) {
1612 throw new DBTransactionError(
1614 "$fname: Transaction round '{$this->trxRoundId}' already started"
1617 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
1619 // Clear any empty transactions (no writes/callbacks) from the implicit round
1620 $this->flushMasterSnapshots( $fname );
1622 $this->trxRoundId
= $fname;
1623 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1624 // Mark applicable handles as participating in this explicit transaction round.
1625 // For each of these handles, any writes and callbacks will be tied to a single
1626 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1627 // are part of an en masse commit or an en masse rollback.
1628 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1629 $this->applyTransactionRoundFlags( $conn );
1631 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1634 public function commitMasterChanges( $fname = __METHOD__
, $owner = null ) {
1635 $this->assertOwnership( $fname, $owner );
1636 $this->assertTransactionRoundStage( self
::ROUND_APPROVED
);
1640 /** @noinspection PhpUnusedLocalVariableInspection */
1641 $scope = ScopedCallback
::newScopedIgnoreUserAbort(); // try to ignore client aborts
1643 $restore = ( $this->trxRoundId
!== false );
1644 $this->trxRoundId
= false;
1645 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1646 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1647 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1648 $this->forEachOpenMasterConnection(
1649 function ( IDatabase
$conn ) use ( $fname, &$failures ) {
1651 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1652 } catch ( DBError
$e ) {
1653 ( $this->errorLogger
)( $e );
1654 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1659 throw new DBTransactionError(
1661 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1665 // Unmark handles as participating in this explicit transaction round
1666 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1667 $this->undoTransactionRoundFlags( $conn );
1670 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
1673 public function runMasterTransactionIdleCallbacks( $fname = __METHOD__
, $owner = null ) {
1674 $this->assertOwnership( $fname, $owner );
1675 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1676 $type = IDatabase
::TRIGGER_COMMIT
;
1677 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1678 $type = IDatabase
::TRIGGER_ROLLBACK
;
1680 throw new DBTransactionError(
1682 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1686 $oldStage = $this->trxRoundStage
;
1687 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1689 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1690 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1691 $conn->setTrxEndCallbackSuppression( false );
1694 $e = null; // first exception
1695 $fname = __METHOD__
;
1696 // Loop until callbacks stop adding callbacks on other connections
1698 // Run any pending callbacks for each connection...
1699 $count = 0; // callback execution attempts
1700 $this->forEachOpenMasterConnection(
1701 function ( Database
$conn ) use ( $type, &$e, &$count ) {
1702 if ( $conn->trxLevel() ) {
1703 return; // retry in the next iteration, after commit() is called
1706 $count +
= $conn->runOnTransactionIdleCallbacks( $type );
1707 } catch ( Exception
$ex ) {
1712 // Clear out any active transactions left over from callbacks...
1713 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$e, $fname ) {
1714 if ( $conn->writesPending() ) {
1715 // A callback from another handle wrote to this one and DBO_TRX is set
1716 $this->queryLogger
->warning( $fname . ": found writes pending." );
1717 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1718 $this->queryLogger
->warning(
1719 $fname . ": found writes pending ($fnames).",
1721 'db_server' => $conn->getServer(),
1722 'db_name' => $conn->getDBname()
1725 } elseif ( $conn->trxLevel() ) {
1726 // A callback from another handle read from this one and DBO_TRX is set,
1727 // which can easily happen if there is only one DB (no replicas)
1728 $this->queryLogger
->debug( $fname . ": found empty transaction." );
1731 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1732 } catch ( Exception
$ex ) {
1736 } while ( $count > 0 );
1738 $this->trxRoundStage
= $oldStage;
1743 public function runMasterTransactionListenerCallbacks( $fname = __METHOD__
, $owner = null ) {
1744 $this->assertOwnership( $fname, $owner );
1745 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1746 $type = IDatabase
::TRIGGER_COMMIT
;
1747 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1748 $type = IDatabase
::TRIGGER_ROLLBACK
;
1750 throw new DBTransactionError(
1752 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1758 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1759 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1761 $conn->runTransactionListenerCallbacks( $type );
1762 } catch ( Exception
$ex ) {
1766 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1771 public function rollbackMasterChanges( $fname = __METHOD__
, $owner = null ) {
1772 $this->assertOwnership( $fname, $owner );
1774 $restore = ( $this->trxRoundId
!== false );
1775 $this->trxRoundId
= false;
1776 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1777 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1778 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1781 // Unmark handles as participating in this explicit transaction round
1782 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1783 $this->undoTransactionRoundFlags( $conn );
1786 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
1790 * @param string|string[] $stage
1791 * @throws DBTransactionError
1793 private function assertTransactionRoundStage( $stage ) {
1794 $stages = (array)$stage;
1796 if ( !in_array( $this->trxRoundStage
, $stages, true ) ) {
1797 $stageList = implode(
1799 array_map( function ( $v ) {
1803 throw new DBTransactionError(
1805 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1811 * @param string $fname
1812 * @param int|null $owner Owner ID of the caller
1813 * @throws DBTransactionError
1815 private function assertOwnership( $fname, $owner ) {
1816 if ( $this->ownerId
!== null && $owner !== $this->ownerId
) {
1817 throw new DBTransactionError(
1819 "$fname: LoadBalancer is owned by LBFactory #{$this->ownerId} (got '$owner')."
1825 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1827 * Some servers may have neither flag enabled, meaning that they opt out of such
1828 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1829 * when a DB server is used for something like simple key/value storage.
1831 * @param Database $conn
1833 private function applyTransactionRoundFlags( Database
$conn ) {
1834 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1835 return; // transaction rounds do not apply to these connections
1838 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1839 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1840 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1841 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1844 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1845 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1850 * @param Database $conn
1852 private function undoTransactionRoundFlags( Database
$conn ) {
1853 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1854 return; // transaction rounds do not apply to these connections
1857 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1858 $conn->setLBInfo( 'trxRoundId', null ); // remove the round ID
1861 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1862 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1866 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1867 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) use ( $fname ) {
1868 $conn->flushSnapshot( $fname );
1872 public function flushMasterSnapshots( $fname = __METHOD__
) {
1873 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1874 $conn->flushSnapshot( $fname );
1882 public function getTransactionRoundStage() {
1883 return $this->trxRoundStage
;
1886 public function hasMasterConnection() {
1887 return $this->isOpen( $this->getWriterIndex() );
1890 public function hasMasterChanges() {
1892 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1893 $pending |
= $conn->writesOrCallbacksPending();
1896 return (bool)$pending;
1899 public function lastMasterChangeTimestamp() {
1901 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1902 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1908 public function hasOrMadeRecentMasterChanges( $age = null ) {
1909 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1911 return ( $this->hasMasterChanges()
1912 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1915 public function pendingMasterChangeCallers() {
1917 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1918 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1924 public function getLaggedReplicaMode( $domain = false ) {
1925 if ( $this->laggedReplicaMode
) {
1926 return true; // stay in lagged replica mode
1929 if ( $this->hasStreamingReplicaServers() ) {
1930 // This will set "laggedReplicaMode" as needed
1931 $this->getReaderIndex( self
::GROUP_GENERIC
, $domain );
1934 return $this->laggedReplicaMode
;
1937 public function laggedReplicaUsed() {
1938 return $this->laggedReplicaMode
;
1941 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1942 if ( $this->readOnlyReason
!== false ) {
1943 return $this->readOnlyReason
;
1944 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1945 return 'The master database server is running in read-only mode.';
1946 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1947 return ( $this->getExistingReaderIndex( self
::GROUP_GENERIC
) >= 0 )
1948 ?
'The database is read-only until replication lag decreases.'
1949 : 'The database is read-only until a replica database server becomes reachable.';
1956 * @param string $domain Domain ID, or false for the current domain
1957 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1960 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1961 $cache = $this->wanCache
;
1962 $masterServer = $this->getServerName( $this->getWriterIndex() );
1964 return (bool)$cache->getWithSetCallback(
1965 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1966 self
::TTL_CACHE_READONLY
,
1967 function () use ( $domain, $conn ) {
1968 $old = $this->trxProfiler
->setSilenced( true );
1970 $index = $this->getWriterIndex();
1971 $dbw = $conn ?
: $this->getServerConnection( $index, $domain );
1972 $readOnly = (int)$dbw->serverIsReadOnly();
1974 $this->reuseConnection( $dbw );
1976 } catch ( DBError
$e ) {
1979 $this->trxProfiler
->setSilenced( $old );
1983 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1987 public function allowLagged( $mode = null ) {
1988 if ( $mode === null ) {
1989 return $this->allowLagged
;
1991 $this->allowLagged
= $mode;
1993 return $this->allowLagged
;
1996 public function pingAll() {
1998 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1999 if ( !$conn->ping() ) {
2007 public function forEachOpenConnection( $callback, array $params = [] ) {
2008 foreach ( $this->conns
as $connsByServer ) {
2009 foreach ( $connsByServer as $serverConns ) {
2010 foreach ( $serverConns as $conn ) {
2011 $callback( $conn, ...$params );
2017 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
2018 $masterIndex = $this->getWriterIndex();
2019 foreach ( $this->conns
as $connsByServer ) {
2020 if ( isset( $connsByServer[$masterIndex] ) ) {
2021 /** @var IDatabase $conn */
2022 foreach ( $connsByServer[$masterIndex] as $conn ) {
2023 $callback( $conn, ...$params );
2029 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
2030 foreach ( $this->conns
as $connsByServer ) {
2031 foreach ( $connsByServer as $i => $serverConns ) {
2032 if ( $i === $this->getWriterIndex() ) {
2033 continue; // skip master
2035 foreach ( $serverConns as $conn ) {
2036 $callback( $conn, ...$params );
2045 private function getCurrentConnectionCount() {
2047 foreach ( $this->conns
as $connsByServer ) {
2048 foreach ( $connsByServer as $serverConns ) {
2049 $count +
= count( $serverConns );
2056 public function getMaxLag( $domain = false ) {
2061 if ( $this->hasReplicaServers() ) {
2062 $lagTimes = $this->getLagTimes( $domain );
2063 foreach ( $lagTimes as $i => $lag ) {
2064 if ( $this->groupLoads
[self
::GROUP_GENERIC
][$i] > 0 && $lag > $maxLag ) {
2066 $host = $this->getServerInfoStrict( $i, 'host' );
2072 return [ $host, $maxLag, $maxIndex ];
2075 public function getLagTimes( $domain = false ) {
2076 if ( !$this->hasReplicaServers() ) {
2077 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
2080 $knownLagTimes = []; // map of (server index => 0 seconds)
2081 $indexesWithLag = [];
2082 foreach ( $this->servers
as $i => $server ) {
2083 if ( empty( $server['is static'] ) ) {
2084 $indexesWithLag[] = $i; // DB server might have replication lag
2086 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
2090 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
2094 * Get the lag in seconds for a given connection, or zero if this load
2095 * balancer does not have replication enabled.
2097 * This should be used in preference to Database::getLag() in cases where
2098 * replication may not be in use, since there is no way to determine if
2099 * replication is in use at the connection level without running
2100 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
2101 * function instead of Database::getLag() avoids a fatal error in this
2102 * case on many installations.
2104 * @param IDatabase $conn
2105 * @return int|bool Returns false on error
2106 * @deprecated Since 1.34 Use IDatabase::getLag() instead
2108 public function safeGetLag( IDatabase
$conn ) {
2109 if ( $conn->getLBInfo( 'is static' ) ) {
2110 return 0; // static dataset
2111 } elseif ( $conn->getLBInfo( 'serverIndex' ) == $this->getWriterIndex() ) {
2112 return 0; // this is the master
2115 return $conn->getLag();
2118 public function waitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
2119 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
2121 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
2122 return true; // server is not a replica DB
2126 // Get the current master position, opening a connection if needed
2127 $index = $this->getWriterIndex();
2128 $flags = self
::CONN_SILENCE_ERRORS
;
2129 $masterConn = $this->getAnyOpenConnection( $index, $flags );
2130 if ( $masterConn ) {
2131 $pos = $masterConn->getMasterPos();
2133 $masterConn = $this->getServerConnection( $index, self
::DOMAIN_ANY
, $flags );
2134 if ( !$masterConn ) {
2135 throw new DBReplicationWaitError(
2137 "Could not obtain a master database connection to get the position"
2140 $pos = $masterConn->getMasterPos();
2141 $this->closeConnection( $masterConn );
2145 if ( $pos instanceof DBMasterPos
) {
2146 $start = microtime( true );
2147 $result = $conn->masterPosWait( $pos, $timeout );
2148 $seconds = max( microtime( true ) - $start, 0 );
2149 if ( $result == -1 ||
is_null( $result ) ) {
2150 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos} [{seconds}s]';
2151 $this->replLogger
->warning( $msg, [
2152 'host' => $conn->getServer(),
2154 'seconds' => round( $seconds, 6 ),
2155 'trace' => ( new RuntimeException() )->getTraceAsString()
2159 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
2163 $ok = false; // something is misconfigured
2164 $this->replLogger
->error(
2165 __METHOD__
. ': could not get master pos for {host}',
2167 'host' => $conn->getServer(),
2168 'trace' => ( new RuntimeException() )->getTraceAsString()
2177 * Wait for a replica DB to reach a specified master position
2179 * This will connect to the master to get an accurate position if $pos is not given
2181 * @param IDatabase $conn Replica DB
2182 * @param DBMasterPos|bool $pos Master position; default: current position
2183 * @param int $timeout Timeout in seconds [optional]
2184 * @return bool Success
2186 * @deprecated Since 1.34 Use waitForMasterPos() instead
2188 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
2189 return $this->waitForMasterPos( $conn, $pos, $timeout );
2192 public function setTransactionListener( $name, callable
$callback = null ) {
2194 $this->trxRecurringCallbacks
[$name] = $callback;
2196 unset( $this->trxRecurringCallbacks
[$name] );
2198 $this->forEachOpenMasterConnection(
2199 function ( IDatabase
$conn ) use ( $name, $callback ) {
2200 $conn->setTransactionListener( $name, $callback );
2205 public function setTableAliases( array $aliases ) {
2206 $this->tableAliases
= $aliases;
2209 public function setIndexAliases( array $aliases ) {
2210 $this->indexAliases
= $aliases;
2213 public function setLocalDomainPrefix( $prefix ) {
2214 // Find connections to explicit foreign domains still marked as in-use...
2216 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
2217 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
2218 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
2219 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
2220 $domainsInUse[] = $conn->getDomainID();
2224 // Do not switch connections to explicit foreign domains unless marked as safe
2225 if ( $domainsInUse ) {
2226 $domains = implode( ', ', $domainsInUse );
2227 throw new DBUnexpectedError( null,
2228 "Foreign domain connections are still in use ($domains)" );
2231 $this->setLocalDomain( new DatabaseDomain(
2232 $this->localDomain
->getDatabase(),
2233 $this->localDomain
->getSchema(),
2237 // Update the prefix for all local connections...
2238 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
2239 if ( !$db->getLBInfo( 'foreign' ) ) {
2240 $db->tablePrefix( $prefix );
2245 public function redefineLocalDomain( $domain ) {
2248 $this->setLocalDomain( DatabaseDomain
::newFromId( $domain ) );
2251 public function setTempTablesOnlyMode( $value, $domain ) {
2252 $old = $this->tempTablesOnlyMode
[$domain] ??
false;
2254 $this->tempTablesOnlyMode
[$domain] = true;
2256 unset( $this->tempTablesOnlyMode
[$domain] );
2263 * @param DatabaseDomain $domain
2265 private function setLocalDomain( DatabaseDomain
$domain ) {
2266 $this->localDomain
= $domain;
2267 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
2268 // always true, gracefully handle the case when they fail to account for escaping.
2269 if ( $this->localDomain
->getTablePrefix() != '' ) {
2270 $this->localDomainIdAlias
=
2271 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
2273 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
2278 * @param int $i Server index
2279 * @param string|null $field Server index field [optional]
2280 * @return array|mixed
2281 * @throws InvalidArgumentException
2283 private function getServerInfoStrict( $i, $field = null ) {
2284 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
2285 throw new InvalidArgumentException( "No server with index '$i'" );
2288 if ( $field !== null ) {
2289 if ( !array_key_exists( $field, $this->servers
[$i] ) ) {
2290 throw new InvalidArgumentException( "No field '$field' in server index '$i'" );
2293 return $this->servers
[$i][$field];
2296 return $this->servers
[$i];
2299 function __destruct() {
2300 // Avoid connection leaks for sanity
2306 * @deprecated since 1.29
2308 class_alias( LoadBalancer
::class, 'LoadBalancer' );