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
;
31 use UnexpectedValueException
;
32 use InvalidArgumentException
;
37 * Database connection, tracking, load balancing, and transaction manager for a cluster
41 class LoadBalancer
implements ILoadBalancer
{
42 /** @var ILoadMonitor */
44 /** @var callable|null Callback to run before the first connection attempt */
45 private $chronologyCallback;
48 /** @var WANObjectCache */
50 /** @var mixed Class name or object With profileIn/profileOut methods */
52 /** @var TransactionProfiler */
54 /** @var LoggerInterface */
56 /** @var LoggerInterface */
58 /** @var LoggerInterface */
60 /** @var LoggerInterface */
62 /** @var callable Exception logger */
64 /** @var callable Deprecation logger */
65 private $deprecationLogger;
67 /** @var DatabaseDomain Local DB domain ID and default for selectDB() calls */
70 /** @var Database[][][] Map of (connection category => server index => IDatabase[]) */
73 /** @var array[] Map of (server index => server config array) */
75 /** @var float[] Map of (server index => weight) */
76 private $genericLoads;
77 /** @var array[] Map of (group => server index => weight) */
79 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
81 /** @var int Seconds to spend waiting on replica DB lag to resolve */
83 /** @var array The LoadMonitor configuration */
84 private $loadMonitorConfig;
85 /** @var string Alternate local DB domain instead of DatabaseDomain::getId() */
86 private $localDomainIdAlias;
90 /** @var string Current server name */
92 /** @var bool Whether this PHP instance is for a CLI script */
94 /** @var string Agent name for query profiling */
97 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
98 private $tableAliases = [];
99 /** @var string[] Map of (index alias => index) */
100 private $indexAliases = [];
101 /** @var array[] Map of (name => callable) */
102 private $trxRecurringCallbacks = [];
104 /** @var Database DB connection object that caused a problem */
105 private $errorConnection;
106 /** @var int The generic (not query grouped) replica DB index */
107 private $genericReadIndex = -1;
108 /** @var int[] The group replica DB indexes keyed by group */
109 private $readIndexByGroup = [];
110 /** @var bool|DBMasterPos Replication sync position or false if not set */
112 /** @var bool Whether the generic reader fell back to a lagged replica DB */
113 private $laggedReplicaMode = false;
114 /** @var bool Whether the generic reader fell back to a lagged replica DB */
115 private $allReplicasDownMode = false;
116 /** @var string The last DB selection or connection error */
117 private $lastError = 'Unknown error';
118 /** @var string|bool Reason the LB is read-only or false if not */
119 private $readOnlyReason = false;
120 /** @var int Total connections opened */
121 private $connsOpened = 0;
123 private $disabled = false;
124 /** @var bool Whether any connection has been attempted yet */
125 private $connectionAttempted = false;
127 /** @var int|null An integer ID of the managing LBFactory instance or null */
129 /** @var string|bool String if a requested DBO_TRX transaction round is active */
130 private $trxRoundId = false;
131 /** @var string Stage of the current transaction round in the transaction round life-cycle */
132 private $trxRoundStage = self
::ROUND_CURSORY
;
134 /** @var string|null */
135 private $defaultGroup = null;
137 /** @var int Warn when this many connection are held */
138 const CONN_HELD_WARN_THRESHOLD
= 10;
140 /** @var int Default 'maxLag' when unspecified */
141 const MAX_LAG_DEFAULT
= 6;
142 /** @var int Default 'waitTimeout' when unspecified */
143 const MAX_WAIT_DEFAULT
= 10;
144 /** @var int Seconds to cache master server read-only status */
145 const TTL_CACHE_READONLY
= 5;
147 const KEY_LOCAL
= 'local';
148 const KEY_FOREIGN_FREE
= 'foreignFree';
149 const KEY_FOREIGN_INUSE
= 'foreignInUse';
151 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
152 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
153 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
155 /** @var string Transaction round, explicit or implicit, has not finished writing */
156 const ROUND_CURSORY
= 'cursory';
157 /** @var string Transaction round writes are complete and ready for pre-commit checks */
158 const ROUND_FINALIZED
= 'finalized';
159 /** @var string Transaction round passed final pre-commit checks */
160 const ROUND_APPROVED
= 'approved';
161 /** @var string Transaction round was committed and post-commit callbacks must be run */
162 const ROUND_COMMIT_CALLBACKS
= 'commit-callbacks';
163 /** @var string Transaction round was rolled back and post-rollback callbacks must be run */
164 const ROUND_ROLLBACK_CALLBACKS
= 'rollback-callbacks';
165 /** @var string Transaction round encountered an error */
166 const ROUND_ERROR
= 'error';
168 public function __construct( array $params ) {
169 if ( !isset( $params['servers'] ) ) {
170 throw new InvalidArgumentException( __CLASS__
. ': missing "servers" parameter' );
172 $this->servers
= $params['servers'];
173 foreach ( $this->servers
as $i => $server ) {
175 $this->servers
[$i]['master'] = true;
177 $this->servers
[$i]['replica'] = true;
181 $localDomain = isset( $params['localDomain'] )
182 ? DatabaseDomain
::newFromId( $params['localDomain'] )
183 : DatabaseDomain
::newUnspecified();
184 $this->setLocalDomain( $localDomain );
186 $this->waitTimeout
= $params['waitTimeout'] ?? self
::MAX_WAIT_DEFAULT
;
189 // Connection were transaction rounds may be applied
190 self
::KEY_LOCAL
=> [],
191 self
::KEY_FOREIGN_INUSE
=> [],
192 self
::KEY_FOREIGN_FREE
=> [],
193 // Auto-committing counterpart connections that ignore transaction rounds
194 self
::KEY_LOCAL_NOROUND
=> [],
195 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
196 self
::KEY_FOREIGN_FREE_NOROUND
=> []
198 $this->genericLoads
= [];
199 $this->waitForPos
= false;
200 $this->allowLagged
= false;
202 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
203 $this->readOnlyReason
= $params['readOnlyReason'];
206 $this->maxLag
= $params['maxLag'] ?? self
::MAX_LAG_DEFAULT
;
208 $this->loadMonitorConfig
= $params['loadMonitor'] ??
[ 'class' => 'LoadMonitorNull' ];
209 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
211 foreach ( $params['servers'] as $i => $server ) {
212 $this->genericLoads
[$i] = $server['load'];
213 if ( isset( $server['groupLoads'] ) ) {
214 foreach ( $server['groupLoads'] as $group => $ratio ) {
215 if ( !isset( $this->groupLoads
[$group] ) ) {
216 $this->groupLoads
[$group] = [];
218 $this->groupLoads
[$group][$i] = $ratio;
223 $this->srvCache
= $params['srvCache'] ??
new EmptyBagOStuff();
224 $this->wanCache
= $params['wanCache'] ?? WANObjectCache
::newEmpty();
225 $this->profiler
= $params['profiler'] ??
null;
226 $this->trxProfiler
= $params['trxProfiler'] ??
new TransactionProfiler();
228 $this->errorLogger
= $params['errorLogger'] ??
function ( Exception
$e ) {
229 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
231 $this->deprecationLogger
= $params['deprecationLogger'] ??
function ( $msg ) {
232 trigger_error( $msg, E_USER_DEPRECATED
);
235 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
236 $this->$key = $params[$key] ??
new NullLogger();
239 $this->hostname
= $params['hostname'] ??
( gethostname() ?
: 'unknown' );
240 $this->cliMode
= $params['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
241 $this->agent
= $params['agent'] ??
'';
243 if ( isset( $params['chronologyCallback'] ) ) {
244 $this->chronologyCallback
= $params['chronologyCallback'];
247 if ( isset( $params['roundStage'] ) ) {
248 if ( $params['roundStage'] === self
::STAGE_POSTCOMMIT_CALLBACKS
) {
249 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
250 } elseif ( $params['roundStage'] === self
::STAGE_POSTROLLBACK_CALLBACKS
) {
251 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
255 $this->defaultGroup
= $params['defaultGroup'] ??
null;
256 $this->ownerId
= $params['ownerId'] ??
null;
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;
276 private function sanitizeConnectionFlags( $flags ) {
277 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) === self
::CONN_TRX_AUTOCOMMIT
) {
278 // Assuming all servers are of the same type (or similar), which is overwhelmingly
279 // the case, use the master server information to get the attributes. The information
280 // for $i cannot be used since it might be DB_REPLICA, which might require connection
281 // attempts in order to be resolved into a real server index.
282 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
283 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
284 // Callers sometimes want to (a) escape REPEATABLE-READ stateness without locking
285 // rows (e.g. FOR UPDATE) or (b) make small commits during a larger transactions
286 // to reduce lock contention. None of these apply for sqlite and using separate
287 // connections just causes self-deadlocks.
288 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
289 $this->connLogger
->info( __METHOD__
.
290 ': ignoring CONN_TRX_AUTOCOMMIT to avoid deadlocks.' );
298 * @param IDatabase $conn
300 * @throws DBUnexpectedError
302 private function enforceConnectionFlags( IDatabase
$conn, $flags ) {
303 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
) {
304 if ( $conn->trxLevel() ) { // sanity
305 throw new DBUnexpectedError(
307 'Handle requested with CONN_TRX_AUTOCOMMIT yet it has a transaction'
311 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
316 * Get a LoadMonitor instance
318 * @return ILoadMonitor
320 private function getLoadMonitor() {
321 if ( !isset( $this->loadMonitor
) ) {
323 'LoadMonitor' => LoadMonitor
::class,
324 'LoadMonitorNull' => LoadMonitorNull
::class,
325 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
328 $class = $this->loadMonitorConfig
['class'];
329 if ( isset( $compat[$class] ) ) {
330 $class = $compat[$class];
333 $this->loadMonitor
= new $class(
334 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
335 $this->loadMonitor
->setLogger( $this->replLogger
);
338 return $this->loadMonitor
;
342 * @param array $loads
343 * @param bool|string $domain Domain to get non-lagged for
344 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
345 * @return bool|int|string
347 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
348 $lags = $this->getLagTimes( $domain );
350 # Unset excessively lagged servers
351 foreach ( $lags as $i => $lag ) {
353 # How much lag this server nominally is allowed to have
354 $maxServerLag = $this->servers
[$i]['max lag'] ??
$this->maxLag
; // default
355 # Constrain that futher by $maxLag argument
356 $maxServerLag = min( $maxServerLag, $maxLag );
358 $host = $this->getServerName( $i );
359 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
360 $this->replLogger
->debug(
362 ": server {host} is not replicating?", [ 'host' => $host ] );
364 } elseif ( $lag > $maxServerLag ) {
365 $this->replLogger
->debug(
367 ": server {host} has {lag} seconds of lag (>= {maxlag})",
368 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
375 # Find out if all the replica DBs with non-zero load are lagged
377 foreach ( $loads as $load ) {
381 # No appropriate DB servers except maybe the master and some replica DBs with zero load
382 # Do NOT use the master
383 # Instead, this function will return false, triggering read-only mode,
384 # and a lagged replica DB will be used instead.
388 if ( count( $loads ) == 0 ) {
392 # Return a random representative of the remainder
393 return ArrayUtils
::pickRandom( $loads );
398 * @param array $groups
399 * @param string|bool $domain
400 * @return int The index of a specific server (replica DBs are checked for connectivity)
402 private function getConnectionIndex( $i, $groups, $domain ) {
403 // Check one "group" per default: the generic pool
404 $defaultGroups = $this->defaultGroup ?
[ $this->defaultGroup
] : [ false ];
406 $groups = ( $groups === false ||
$groups === [] )
410 if ( $i === self
::DB_MASTER
) {
411 $i = $this->getWriterIndex();
412 } elseif ( $i === self
::DB_REPLICA
) {
413 # Try to find an available server in any the query groups (in order)
414 foreach ( $groups as $group ) {
415 $groupIndex = $this->getReaderIndex( $group, $domain );
416 if ( $groupIndex !== false ) {
423 # Operation-based index
424 if ( $i === self
::DB_REPLICA
) {
425 $this->lastError
= 'Unknown error'; // reset error string
426 # Try the general server pool if $groups are unavailable.
427 $i = ( $groups === [ false ] )
428 ?
false // don't bother with this if that is what was tried above
429 : $this->getReaderIndex( false, $domain );
430 # Couldn't find a working server in getReaderIndex()?
431 if ( $i === false ) {
432 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
433 // Throw an exception
434 $this->reportConnectionError();
435 return null; // unreachable due to exception
442 public function getReaderIndex( $group = false, $domain = false ) {
443 if ( count( $this->servers
) == 1 ) {
444 // Skip the load balancing if there's only one server
445 return $this->getWriterIndex();
448 $index = $this->getExistingReaderIndex( $group );
450 // A reader index was already selected and "waitForPos" was handled
454 if ( $group !== false ) {
455 // Use the server weight array for this load group
456 if ( isset( $this->groupLoads
[$group] ) ) {
457 $loads = $this->groupLoads
[$group];
459 // No loads for this group, return false and the caller can use some other group
460 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
465 // Use the generic load group
466 $loads = $this->genericLoads
;
469 // Scale the configured load ratios according to each server's load and state
470 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
472 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
473 $this->lazyLoadReplicationPositions(); // optimizes server candidate selection
474 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
475 if ( $i === false ) {
476 // DB connection unsuccessful
480 // If data seen by queries is expected to reflect the transactions committed as of
481 // or after a given replication position then wait for the DB to apply those changes
482 if ( $this->waitForPos
&& $i != $this->getWriterIndex() && !$this->doWait( $i ) ) {
483 // Data will be outdated compared to what was expected
484 $laggedReplicaMode = true;
487 // Cache the reader index for future DB_REPLICA handles
488 $this->setExistingReaderIndex( $group, $i );
489 // Record whether the generic reader index is in "lagged replica DB" mode
490 if ( $group === false && $laggedReplicaMode ) {
491 $this->laggedReplicaMode
= true;
494 $serverName = $this->getServerName( $i );
495 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
501 * Get the server index chosen by the load balancer for use with the given query group
503 * @param string|bool $group Query group; use false for the generic group
504 * @return int Server index or -1 if none was chosen
506 protected function getExistingReaderIndex( $group ) {
507 if ( $group === false ) {
508 $index = $this->genericReadIndex
;
510 $index = $this->readIndexByGroup
[$group] ??
-1;
517 * Set the server index chosen by the load balancer for use with the given query group
519 * @param string|bool $group Query group; use false for the generic group
520 * @param int $index The index of a specific server
522 private function setExistingReaderIndex( $group, $index ) {
524 throw new UnexpectedValueException( "Cannot set a negative read server index" );
527 if ( $group === false ) {
528 $this->genericReadIndex
= $index;
530 $this->readIndexByGroup
[$group] = $index;
535 * @param array $loads List of server weights
536 * @param string|bool $domain
537 * @return array (reader index, lagged replica mode) or false on failure
539 private function pickReaderIndex( array $loads, $domain = false ) {
540 if ( $loads === [] ) {
541 throw new InvalidArgumentException( "Server configuration array is empty" );
544 /** @var int|bool $i Index of selected server */
546 /** @var bool $laggedReplicaMode Whether server is considered lagged */
547 $laggedReplicaMode = false;
549 // Quickly look through the available servers for a server that meets criteria...
550 $currentLoads = $loads;
551 while ( count( $currentLoads ) ) {
552 if ( $this->allowLagged ||
$laggedReplicaMode ) {
553 $i = ArrayUtils
::pickRandom( $currentLoads );
556 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
557 $this->replLogger
->debug( __METHOD__
. ": replication positions detected" );
558 // "chronologyCallback" sets "waitForPos" for session consistency.
559 // This triggers doWait() after connect, so it's especially good to
560 // avoid lagged servers so as to avoid excessive delay in that method.
561 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
562 // Aim for <= 1 second of waiting (being too picky can backfire)
563 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
565 if ( $i === false ) {
566 // Any server with less lag than it's 'max lag' param is preferable
567 $i = $this->getRandomNonLagged( $currentLoads, $domain );
569 if ( $i === false && count( $currentLoads ) != 0 ) {
570 // All replica DBs lagged. Switch to read-only mode
571 $this->replLogger
->error(
572 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
573 $i = ArrayUtils
::pickRandom( $currentLoads );
574 $laggedReplicaMode = true;
578 if ( $i === false ) {
579 // pickRandom() returned false.
580 // This is permanent and means the configuration or the load monitor
581 // wants us to return false.
582 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
584 return [ false, false ];
587 $serverName = $this->getServerName( $i );
588 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
590 $conn = $this->getConnection( $i, [], $domain, self
::CONN_SILENCE_ERRORS
);
592 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
593 unset( $currentLoads[$i] ); // avoid this server next iteration
598 // Decrement reference counter, we are finished with this connection.
599 // It will be incremented for the caller later.
600 if ( $domain !== false ) {
601 $this->reuseConnection( $conn );
604 // Return this server
608 // If all servers were down, quit now
609 if ( $currentLoads === [] ) {
610 $this->connLogger
->error( __METHOD__
. ": all servers down" );
613 return [ $i, $laggedReplicaMode ];
616 public function waitFor( $pos ) {
617 $oldPos = $this->waitForPos
;
619 $this->waitForPos
= $pos;
620 // If a generic reader connection was already established, then wait now
621 if ( $this->genericReadIndex
> 0 && !$this->doWait( $this->genericReadIndex
) ) {
622 $this->laggedReplicaMode
= true;
624 // Otherwise, wait until a connection is established in getReaderIndex()
626 // Restore the older position if it was higher since this is used for lag-protection
627 $this->setWaitForPositionIfHigher( $oldPos );
631 public function waitForOne( $pos, $timeout = null ) {
632 $oldPos = $this->waitForPos
;
634 $this->waitForPos
= $pos;
636 $i = $this->genericReadIndex
;
638 // Pick a generic replica DB if there isn't one yet
639 $readLoads = $this->genericLoads
;
640 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
641 $readLoads = array_filter( $readLoads ); // with non-zero load
642 $i = ArrayUtils
::pickRandom( $readLoads );
646 $ok = $this->doWait( $i, true, $timeout );
648 $ok = true; // no applicable loads
651 # Restore the old position, as this is not used for lag-protection but for throttling
652 $this->waitForPos
= $oldPos;
658 public function waitForAll( $pos, $timeout = null ) {
659 $timeout = $timeout ?
: $this->waitTimeout
;
661 $oldPos = $this->waitForPos
;
663 $this->waitForPos
= $pos;
664 $serverCount = count( $this->servers
);
667 for ( $i = 1; $i < $serverCount; $i++
) {
668 if ( $this->genericLoads
[$i] > 0 ) {
669 $start = microtime( true );
670 $ok = $this->doWait( $i, true, $timeout ) && $ok;
671 $timeout -= intval( microtime( true ) - $start );
672 if ( $timeout <= 0 ) {
673 break; // timeout reached
678 # Restore the old position, as this is not used for lag-protection but for throttling
679 $this->waitForPos
= $oldPos;
686 * @param DBMasterPos|bool $pos
688 private function setWaitForPositionIfHigher( $pos ) {
693 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
694 $this->waitForPos
= $pos;
698 public function getAnyOpenConnection( $i, $flags = 0 ) {
699 $i = ( $i === self
::DB_MASTER
) ?
$this->getWriterIndex() : $i;
700 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
702 foreach ( $this->conns
as $connsByServer ) {
703 if ( $i === self
::DB_REPLICA
) {
704 $indexes = array_keys( $connsByServer );
706 $indexes = isset( $connsByServer[$i] ) ?
[ $i ] : [];
709 foreach ( $indexes as $index ) {
710 foreach ( $connsByServer[$index] as $conn ) {
711 if ( !$conn->isOpen() ) {
712 continue; // some sort of error occured?
714 if ( !$autocommit ||
$conn->getLBInfo( 'autoCommitOnly' ) ) {
725 * Wait for a given replica DB to catch up to the master pos stored in $this
726 * @param int $index Server index
727 * @param bool $open Check the server even if a new connection has to be made
728 * @param int|null $timeout Max seconds to wait; default is "waitTimeout" given to __construct()
731 protected function doWait( $index, $open = false, $timeout = null ) {
732 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
734 // Check if we already know that the DB has reached this point
735 $server = $this->getServerName( $index );
736 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
737 /** @var DBMasterPos $knownReachedPos */
738 $knownReachedPos = $this->srvCache
->get( $key );
740 $knownReachedPos instanceof DBMasterPos
&&
741 $knownReachedPos->hasReached( $this->waitForPos
)
743 $this->replLogger
->debug(
745 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
746 [ 'dbserver' => $server ]
751 // Find a connection to wait on, creating one if needed and allowed
752 $close = false; // close the connection afterwards
753 $conn = $this->getAnyOpenConnection( $index );
756 $this->replLogger
->debug(
757 __METHOD__
. ': no connection open for {dbserver}',
758 [ 'dbserver' => $server ]
763 // Open a temporary new connection in order to wait for replication
764 $conn = $this->getConnection( $index, [], self
::DOMAIN_ANY
, self
::CONN_SILENCE_ERRORS
);
766 $this->replLogger
->warning(
767 __METHOD__
. ': failed to connect to {dbserver}',
768 [ 'dbserver' => $server ]
773 // Avoid connection spam in waitForAll() when connections
774 // are made just for the sake of doing this lag check.
778 $this->replLogger
->info(
780 ': waiting for replica DB {dbserver} to catch up...',
781 [ 'dbserver' => $server ]
784 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
786 if ( $result === null ) {
787 $this->replLogger
->warning(
788 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
791 'pos' => $this->waitForPos
,
792 'trace' => ( new RuntimeException() )->getTraceAsString()
796 } elseif ( $result == -1 ) {
797 $this->replLogger
->warning(
798 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
801 'pos' => $this->waitForPos
,
802 'trace' => ( new RuntimeException() )->getTraceAsString()
807 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
809 // Remember that the DB reached this point
810 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
814 $this->closeConnection( $conn );
820 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
821 if ( !is_int( $i ) ) {
822 throw new InvalidArgumentException( "Cannot connect without a server index" );
823 } elseif ( $groups && $i > 0 ) {
824 throw new InvalidArgumentException( "Got query groups with server index #$i" );
827 $domain = $this->resolveDomainID( $domain );
828 $flags = $this->sanitizeConnectionFlags( $flags );
829 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
831 // Number of connections made before getting the server index and handle
832 $priorConnectionsMade = $this->connsOpened
;
834 // Choose a server if $i is DB_MASTER/DB_REPLICA (might trigger new connections)
835 $serverIndex = $this->getConnectionIndex( $i, $groups, $domain );
836 // Get an open connection to that server (might trigger a new connection)
837 $conn = $this->localDomain
->equals( $domain )
838 ?
$this->getLocalConnection( $serverIndex, $flags )
839 : $this->getForeignConnection( $serverIndex, $domain, $flags );
840 // Throw an error or bail out if the connection attempt failed
841 if ( !( $conn instanceof IDatabase
) ) {
842 if ( ( $flags & self
::CONN_SILENCE_ERRORS
) != self
::CONN_SILENCE_ERRORS
) {
843 $this->reportConnectionError();
849 // Profile any new connections caused by this method
850 if ( $this->connsOpened
> $priorConnectionsMade ) {
851 $host = $conn->getServer();
852 $dbname = $conn->getDBname();
853 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
856 if ( !$conn->isOpen() ) {
857 // Connection was made but later unrecoverably lost for some reason.
858 // Do not return a handle that will just throw exceptions on use,
859 // but let the calling code (e.g. getReaderIndex) try another server.
860 $this->errorConnection
= $conn;
864 $this->enforceConnectionFlags( $conn, $flags );
865 if ( $serverIndex == $this->getWriterIndex() ) {
866 // If the load balancer is read-only, perhaps due to replication lag, then master
867 // DB handles will reflect that. Note that Database::assertIsWritableMaster() takes
868 // care of replica DB handles whereas getReadOnlyReason() would cause infinite loops.
869 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
875 public function reuseConnection( IDatabase
$conn ) {
876 $serverIndex = $conn->getLBInfo( 'serverIndex' );
877 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
878 if ( $serverIndex === null ||
$refCount === null ) {
880 * This can happen in code like:
881 * foreach ( $dbs as $db ) {
882 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
884 * $lb->reuseConnection( $conn );
886 * When a connection to the local DB is opened in this way, reuseConnection()
890 } elseif ( $conn instanceof DBConnRef
) {
891 // DBConnRef already handles calling reuseConnection() and only passes the live
892 // Database instance to this method. Any caller passing in a DBConnRef is broken.
893 $this->connLogger
->error(
894 __METHOD__
. ": got DBConnRef instance.\n" .
895 ( new RuntimeException() )->getTraceAsString() );
900 if ( $this->disabled
) {
901 return; // DBConnRef handle probably survived longer than the LoadBalancer
904 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
905 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
906 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
908 $connFreeKey = self
::KEY_FOREIGN_FREE
;
909 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
912 $domain = $conn->getDomainID();
913 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
914 throw new InvalidArgumentException(
915 "Connection $serverIndex/$domain not found; it may have already been freed" );
916 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
917 throw new InvalidArgumentException(
918 "Connection $serverIndex/$domain mismatched; it may have already been freed" );
921 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
922 if ( $refCount <= 0 ) {
923 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
924 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
925 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
926 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
928 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
930 $this->connLogger
->debug( __METHOD__
.
931 ": reference count for $serverIndex/$domain reduced to $refCount" );
935 public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
936 $domain = $this->resolveDomainID( $domain );
937 $role = $this->getRoleFromIndex( $i );
939 return new DBConnRef( $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
942 public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
943 $domain = $this->resolveDomainID( $domain );
944 $role = $this->getRoleFromIndex( $i );
946 return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role );
949 public function getMaintenanceConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
950 $domain = $this->resolveDomainID( $domain );
951 $role = $this->getRoleFromIndex( $i );
953 return new MaintainableDBConnRef(
954 $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
958 * @param int $i Server index or DB_MASTER/DB_REPLICA
959 * @return int One of DB_MASTER/DB_REPLICA
961 private function getRoleFromIndex( $i ) {
962 return ( $i === self
::DB_MASTER ||
$i === $this->getWriterIndex() )
969 * @param bool $domain
971 * @return Database|bool Live database handle or false on failure
972 * @deprecated Since 1.34 Use getConnection() instead
974 public function openConnection( $i, $domain = false, $flags = 0 ) {
975 return $this->getConnection( $i, [], $domain, $flags | self
::CONN_SILENCE_ERRORS
);
979 * Open a connection to a local DB, or return one if it is already open.
981 * On error, returns false, and the connection which caused the
982 * error will be available via $this->errorConnection.
984 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
986 * @param int $i Server index
987 * @param int $flags Class CONN_* constant bitfield
990 private function getLocalConnection( $i, $flags = 0 ) {
991 // Connection handles required to be in auto-commit mode use a separate connection
992 // pool since the main pool is effected by implicit and explicit transaction rounds
993 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
995 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
996 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
997 $conn = $this->conns
[$connKey][$i][0];
999 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
1000 throw new InvalidArgumentException( "No server with index '$i'" );
1002 // Open a new connection
1003 $server = $this->servers
[$i];
1004 $server['serverIndex'] = $i;
1005 $server['autoCommitOnly'] = $autoCommit;
1006 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
1007 $host = $this->getServerName( $i );
1008 if ( $conn->isOpen() ) {
1009 $this->connLogger
->debug(
1010 __METHOD__
. ": connected to database $i at '$host'." );
1011 $this->conns
[$connKey][$i][0] = $conn;
1013 $this->connLogger
->warning(
1014 __METHOD__
. ": failed to connect to database $i at '$host'." );
1015 $this->errorConnection
= $conn;
1020 // Final sanity check to make sure the right domain is selected
1022 $conn instanceof IDatabase
&&
1023 !$this->localDomain
->isCompatible( $conn->getDomainID() )
1025 throw new UnexpectedValueException(
1026 "Got connection to '{$conn->getDomainID()}', " .
1027 "but expected local domain ('{$this->localDomain}')" );
1034 * Open a connection to a foreign DB, or return one if it is already open.
1036 * Increments a reference count on the returned connection which locks the
1037 * connection to the requested domain. This reference count can be
1038 * decremented by calling reuseConnection().
1040 * If a connection is open to the appropriate server already, but with the wrong
1041 * database, it will be switched to the right database and returned, as long as
1042 * it has been freed first with reuseConnection().
1044 * On error, returns false, and the connection which caused the
1045 * error will be available via $this->errorConnection.
1047 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
1049 * @param int $i Server index
1050 * @param string $domain Domain ID to open
1051 * @param int $flags Class CONN_* constant bitfield
1052 * @return Database|bool Returns false on connection error
1053 * @throws DBError When database selection fails
1055 private function getForeignConnection( $i, $domain, $flags = 0 ) {
1056 $domainInstance = DatabaseDomain
::newFromId( $domain );
1057 // Connection handles required to be in auto-commit mode use a separate connection
1058 // pool since the main pool is effected by implicit and explicit transaction rounds
1059 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
1061 if ( $autoCommit ) {
1062 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
1063 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
1065 $connFreeKey = self
::KEY_FOREIGN_FREE
;
1066 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
1069 /** @var Database $conn */
1072 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
1073 // Reuse an in-use connection for the same domain
1074 $conn = $this->conns
[$connInUseKey][$i][$domain];
1075 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
1076 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
1077 // Reuse a free connection for the same domain
1078 $conn = $this->conns
[$connFreeKey][$i][$domain];
1079 unset( $this->conns
[$connFreeKey][$i][$domain] );
1080 $this->conns
[$connInUseKey][$i][$domain] = $conn;
1081 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
1082 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
1083 // Reuse a free connection from another domain if possible
1084 foreach ( $this->conns
[$connFreeKey][$i] as $oldDomain => $conn ) {
1085 if ( $domainInstance->getDatabase() !== null ) {
1086 // Check if changing the database will require a new connection.
1087 // In that case, leave the connection handle alone and keep looking.
1088 // This prevents connections from being closed mid-transaction and can
1089 // also avoid overhead if the same database will later be requested.
1091 $conn->databasesAreIndependent() &&
1092 $conn->getDBname() !== $domainInstance->getDatabase()
1096 // Select the new database, schema, and prefix
1097 $conn->selectDomain( $domainInstance );
1099 // Stay on the current database, but update the schema/prefix
1100 $conn->dbSchema( $domainInstance->getSchema() );
1101 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1103 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
1104 // Note that if $domain is an empty string, getDomainID() might not match it
1105 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1106 $this->connLogger
->debug( __METHOD__
.
1107 ": reusing free connection from $oldDomain for $domain" );
1113 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
1114 throw new InvalidArgumentException( "No server with index '$i'" );
1116 // Open a new connection
1117 $server = $this->servers
[$i];
1118 $server['serverIndex'] = $i;
1119 $server['foreignPoolRefCount'] = 0;
1120 $server['foreign'] = true;
1121 $server['autoCommitOnly'] = $autoCommit;
1122 $conn = $this->reallyOpenConnection( $server, $domainInstance );
1123 if ( !$conn->isOpen() ) {
1124 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
1125 $this->errorConnection
= $conn;
1128 // Note that if $domain is an empty string, getDomainID() might not match it
1129 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1130 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1134 if ( $conn instanceof IDatabase
) {
1135 // Final sanity check to make sure the right domain is selected
1136 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1137 throw new UnexpectedValueException(
1138 "Got connection to '{$conn->getDomainID()}', but expected '$domain'" );
1140 // Increment reference count
1141 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1142 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1148 public function getServerAttributes( $i ) {
1149 return Database
::attributesFromType(
1150 $this->getServerType( $i ),
1151 $this->servers
[$i]['driver'] ??
null
1156 * Test if the specified index represents an open connection
1158 * @param int $index Server index
1162 private function isOpen( $index ) {
1163 if ( !is_int( $index ) ) {
1167 return (bool)$this->getAnyOpenConnection( $index );
1171 * Open a new network connection to a server (uncached)
1173 * Returns a Database object whether or not the connection was successful.
1175 * @param array $server
1176 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
1178 * @throws DBAccessError
1179 * @throws InvalidArgumentException
1181 protected function reallyOpenConnection( array $server, DatabaseDomain
$domain ) {
1182 if ( $this->disabled
) {
1183 throw new DBAccessError();
1186 if ( $domain->getDatabase() === null ) {
1187 // The database domain does not specify a DB name and some database systems require a
1188 // valid DB specified on connection. The $server configuration array contains a default
1189 // DB name to use for connections in such cases.
1190 if ( $server['type'] === 'mysql' ) {
1191 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1192 // and the DB name in $server might not exist due to legacy reasons (the default
1193 // domain used to ignore the local LB domain, even when mismatched).
1194 $server['dbname'] = null;
1197 $server['dbname'] = $domain->getDatabase();
1200 if ( $domain->getSchema() !== null ) {
1201 $server['schema'] = $domain->getSchema();
1204 // It is always possible to connect with any prefix, even the empty string
1205 $server['tablePrefix'] = $domain->getTablePrefix();
1207 // Let the handle know what the cluster master is (e.g. "db1052")
1208 $masterName = $this->getServerName( $this->getWriterIndex() );
1209 $server['clusterMasterHost'] = $masterName;
1211 // Log when many connection are made on requests
1212 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
1213 $this->perfLogger
->warning( __METHOD__
. ": " .
1214 "{$this->connsOpened}+ connections made (master=$masterName)" );
1217 $server['srvCache'] = $this->srvCache
;
1218 // Set loggers and profilers
1219 $server['connLogger'] = $this->connLogger
;
1220 $server['queryLogger'] = $this->queryLogger
;
1221 $server['errorLogger'] = $this->errorLogger
;
1222 $server['deprecationLogger'] = $this->deprecationLogger
;
1223 $server['profiler'] = $this->profiler
;
1224 $server['trxProfiler'] = $this->trxProfiler
;
1225 // Use the same agent and PHP mode for all DB handles
1226 $server['cliMode'] = $this->cliMode
;
1227 $server['agent'] = $this->agent
;
1228 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1229 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1230 $server['flags'] = $server['flags'] ?? IDatabase
::DBO_DEFAULT
;
1232 // Create a live connection object
1234 $db = Database
::factory( $server['type'], $server );
1235 } catch ( DBConnectionError
$e ) {
1236 // FIXME: This is probably the ugliest thing I have ever done to
1237 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1241 $db->setLBInfo( $server );
1242 $db->setLazyMasterHandle(
1243 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1245 $db->setTableAliases( $this->tableAliases
);
1246 $db->setIndexAliases( $this->indexAliases
);
1248 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1249 if ( $this->trxRoundId
!== false ) {
1250 $this->applyTransactionRoundFlags( $db );
1252 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1253 $db->setTransactionListener( $name, $callback );
1257 $this->lazyLoadReplicationPositions(); // session consistency
1263 * Make sure that any "waitForPos" positions are loaded and available to doWait()
1265 private function lazyLoadReplicationPositions() {
1266 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
1267 $this->connectionAttempted
= true;
1268 ( $this->chronologyCallback
)( $this ); // generally calls waitFor()
1269 $this->connLogger
->debug( __METHOD__
. ': executed chronology callback.' );
1274 * @throws DBConnectionError
1276 private function reportConnectionError() {
1277 $conn = $this->errorConnection
; // the connection which caused the error
1279 'method' => __METHOD__
,
1280 'last_error' => $this->lastError
,
1283 if ( $conn instanceof IDatabase
) {
1284 $context['db_server'] = $conn->getServer();
1285 $this->connLogger
->warning(
1286 __METHOD__
. ": connection error: {last_error} ({db_server})",
1290 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1292 // No last connection, probably due to all servers being too busy
1293 $this->connLogger
->error(
1295 ": LB failure with no last connection. Connection error: {last_error}",
1299 // If all servers were busy, "lastError" will contain something sensible
1300 throw new DBConnectionError( null, $this->lastError
);
1304 public function getWriterIndex() {
1308 public function haveIndex( $i ) {
1309 return array_key_exists( $i, $this->servers
);
1312 public function isNonZeroLoad( $i ) {
1313 return array_key_exists( $i, $this->servers
) && $this->genericLoads
[$i] != 0;
1316 public function getServerCount() {
1317 return count( $this->servers
);
1320 public function getServerName( $i ) {
1321 $name = $this->servers
[$i]['hostName'] ??
$this->servers
[$i]['host'] ??
'';
1323 return ( $name != '' ) ?
$name : 'localhost';
1326 public function getServerInfo( $i ) {
1327 return $this->servers
[$i] ??
false;
1330 public function getServerType( $i ) {
1331 return $this->servers
[$i]['type'] ??
'unknown';
1334 public function getMasterPos() {
1335 # If this entire request was served from a replica DB without opening a connection to the
1336 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1337 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1338 if ( !$masterConn ) {
1339 $serverCount = count( $this->servers
);
1340 for ( $i = 1; $i < $serverCount; $i++
) {
1341 $conn = $this->getAnyOpenConnection( $i );
1343 return $conn->getReplicaPos();
1347 return $masterConn->getMasterPos();
1353 public function disable() {
1355 $this->disabled
= true;
1358 public function closeAll() {
1359 $fname = __METHOD__
;
1360 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( $fname ) {
1361 $host = $conn->getServer();
1362 $this->connLogger
->debug(
1363 $fname . ": closing connection to database '$host'." );
1368 self
::KEY_LOCAL
=> [],
1369 self
::KEY_FOREIGN_INUSE
=> [],
1370 self
::KEY_FOREIGN_FREE
=> [],
1371 self
::KEY_LOCAL_NOROUND
=> [],
1372 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1373 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1375 $this->connsOpened
= 0;
1378 public function closeConnection( IDatabase
$conn ) {
1379 if ( $conn instanceof DBConnRef
) {
1380 // Avoid calling close() but still leaving the handle in the pool
1381 throw new RuntimeException( 'Cannot close DBConnRef instance; it must be shareable' );
1384 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1385 foreach ( $this->conns
as $type => $connsByServer ) {
1386 if ( !isset( $connsByServer[$serverIndex] ) ) {
1390 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1391 if ( $conn === $trackedConn ) {
1392 $host = $this->getServerName( $i );
1393 $this->connLogger
->debug(
1394 __METHOD__
. ": closing connection to database $i at '$host'." );
1395 unset( $this->conns
[$type][$serverIndex][$i] );
1396 --$this->connsOpened
;
1405 public function commitAll( $fname = __METHOD__
, $owner = null ) {
1406 $this->commitMasterChanges( $fname, $owner );
1407 $this->flushMasterSnapshots( $fname );
1408 $this->flushReplicaSnapshots( $fname );
1411 public function finalizeMasterChanges( $fname = __METHOD__
, $owner = null ) {
1412 $this->assertOwnership( $fname, $owner );
1413 $this->assertTransactionRoundStage( [ self
::ROUND_CURSORY
, self
::ROUND_FINALIZED
] );
1415 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1416 // Loop until callbacks stop adding callbacks on other connections
1419 $count = 0; // callbacks execution attempts
1420 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$count ) {
1421 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1422 // Any error should cause all (peer) transactions to be rolled back together.
1423 $count +
= $conn->runOnTransactionPreCommitCallbacks();
1426 } while ( $count > 0 );
1427 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1428 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1429 $conn->setTrxEndCallbackSuppression( true );
1431 $this->trxRoundStage
= self
::ROUND_FINALIZED
;
1436 public function approveMasterChanges( array $options, $fname = __METHOD__
, $owner = null ) {
1437 $this->assertOwnership( $fname, $owner );
1438 $this->assertTransactionRoundStage( self
::ROUND_FINALIZED
);
1440 $limit = $options['maxWriteDuration'] ??
0;
1442 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1443 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1444 // If atomic sections or explicit transactions are still open, some caller must have
1445 // caught an exception but failed to properly rollback any changes. Detect that and
1446 // throw and error (causing rollback).
1447 $conn->assertNoOpenTransactions();
1448 // Assert that the time to replicate the transaction will be sane.
1449 // If this fails, then all DB transactions will be rollback back together.
1450 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1451 if ( $limit > 0 && $time > $limit ) {
1452 throw new DBTransactionSizeError(
1454 "Transaction spent $time second(s) in writes, exceeding the limit of $limit",
1458 // If a connection sits idle while slow queries execute on another, that connection
1459 // may end up dropped before the commit round is reached. Ping servers to detect this.
1460 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1461 throw new DBTransactionError(
1463 "A connection to the {$conn->getDBname()} database was lost before commit"
1467 $this->trxRoundStage
= self
::ROUND_APPROVED
;
1470 public function beginMasterChanges( $fname = __METHOD__
, $owner = null ) {
1471 $this->assertOwnership( $fname, $owner );
1472 if ( $this->trxRoundId
!== false ) {
1473 throw new DBTransactionError(
1475 "$fname: Transaction round '{$this->trxRoundId}' already started"
1478 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
1480 // Clear any empty transactions (no writes/callbacks) from the implicit round
1481 $this->flushMasterSnapshots( $fname );
1483 $this->trxRoundId
= $fname;
1484 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1485 // Mark applicable handles as participating in this explicit transaction round.
1486 // For each of these handles, any writes and callbacks will be tied to a single
1487 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1488 // are part of an en masse commit or an en masse rollback.
1489 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1490 $this->applyTransactionRoundFlags( $conn );
1492 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1495 public function commitMasterChanges( $fname = __METHOD__
, $owner = null ) {
1496 $this->assertOwnership( $fname, $owner );
1497 $this->assertTransactionRoundStage( self
::ROUND_APPROVED
);
1501 /** @noinspection PhpUnusedLocalVariableInspection */
1502 $scope = ScopedCallback
::newScopedIgnoreUserAbort(); // try to ignore client aborts
1504 $restore = ( $this->trxRoundId
!== false );
1505 $this->trxRoundId
= false;
1506 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1507 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1508 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1509 $this->forEachOpenMasterConnection(
1510 function ( IDatabase
$conn ) use ( $fname, &$failures ) {
1512 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1513 } catch ( DBError
$e ) {
1514 ( $this->errorLogger
)( $e );
1515 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1520 throw new DBTransactionError(
1522 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1526 // Unmark handles as participating in this explicit transaction round
1527 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1528 $this->undoTransactionRoundFlags( $conn );
1531 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
1534 public function runMasterTransactionIdleCallbacks( $fname = __METHOD__
, $owner = null ) {
1535 $this->assertOwnership( $fname, $owner );
1536 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1537 $type = IDatabase
::TRIGGER_COMMIT
;
1538 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1539 $type = IDatabase
::TRIGGER_ROLLBACK
;
1541 throw new DBTransactionError(
1543 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1547 $oldStage = $this->trxRoundStage
;
1548 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1550 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1551 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1552 $conn->setTrxEndCallbackSuppression( false );
1555 $e = null; // first exception
1556 $fname = __METHOD__
;
1557 // Loop until callbacks stop adding callbacks on other connections
1559 // Run any pending callbacks for each connection...
1560 $count = 0; // callback execution attempts
1561 $this->forEachOpenMasterConnection(
1562 function ( Database
$conn ) use ( $type, &$e, &$count ) {
1563 if ( $conn->trxLevel() ) {
1564 return; // retry in the next iteration, after commit() is called
1567 $count +
= $conn->runOnTransactionIdleCallbacks( $type );
1568 } catch ( Exception
$ex ) {
1573 // Clear out any active transactions left over from callbacks...
1574 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$e, $fname ) {
1575 if ( $conn->writesPending() ) {
1576 // A callback from another handle wrote to this one and DBO_TRX is set
1577 $this->queryLogger
->warning( $fname . ": found writes pending." );
1578 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1579 $this->queryLogger
->warning(
1580 $fname . ": found writes pending ($fnames).",
1582 'db_server' => $conn->getServer(),
1583 'db_name' => $conn->getDBname()
1586 } elseif ( $conn->trxLevel() ) {
1587 // A callback from another handle read from this one and DBO_TRX is set,
1588 // which can easily happen if there is only one DB (no replicas)
1589 $this->queryLogger
->debug( $fname . ": found empty transaction." );
1592 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1593 } catch ( Exception
$ex ) {
1597 } while ( $count > 0 );
1599 $this->trxRoundStage
= $oldStage;
1604 public function runMasterTransactionListenerCallbacks( $fname = __METHOD__
, $owner = null ) {
1605 $this->assertOwnership( $fname, $owner );
1606 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1607 $type = IDatabase
::TRIGGER_COMMIT
;
1608 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1609 $type = IDatabase
::TRIGGER_ROLLBACK
;
1611 throw new DBTransactionError(
1613 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1619 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1620 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1622 $conn->runTransactionListenerCallbacks( $type );
1623 } catch ( Exception
$ex ) {
1627 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1632 public function rollbackMasterChanges( $fname = __METHOD__
, $owner = null ) {
1633 $this->assertOwnership( $fname, $owner );
1635 $restore = ( $this->trxRoundId
!== false );
1636 $this->trxRoundId
= false;
1637 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1638 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1639 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1642 // Unmark handles as participating in this explicit transaction round
1643 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1644 $this->undoTransactionRoundFlags( $conn );
1647 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
1651 * @param string|string[] $stage
1652 * @throws DBTransactionError
1654 private function assertTransactionRoundStage( $stage ) {
1655 $stages = (array)$stage;
1657 if ( !in_array( $this->trxRoundStage
, $stages, true ) ) {
1658 $stageList = implode(
1660 array_map( function ( $v ) {
1664 throw new DBTransactionError(
1666 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1672 * @param string $fname
1673 * @param int|null $owner Owner ID of the caller
1674 * @throws DBTransactionError
1676 private function assertOwnership( $fname, $owner ) {
1677 if ( $this->ownerId
!== null && $owner !== $this->ownerId
) {
1678 throw new DBTransactionError(
1680 "$fname: LoadBalancer is owned by LBFactory #{$this->ownerId} (got '$owner')."
1686 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1688 * Some servers may have neither flag enabled, meaning that they opt out of such
1689 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1690 * when a DB server is used for something like simple key/value storage.
1692 * @param Database $conn
1694 private function applyTransactionRoundFlags( Database
$conn ) {
1695 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1696 return; // transaction rounds do not apply to these connections
1699 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1700 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1701 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1702 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1705 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1706 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1711 * @param Database $conn
1713 private function undoTransactionRoundFlags( Database
$conn ) {
1714 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1715 return; // transaction rounds do not apply to these connections
1718 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1719 $conn->setLBInfo( 'trxRoundId', false );
1722 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1723 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1727 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1728 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) use ( $fname ) {
1729 $conn->flushSnapshot( $fname );
1733 public function flushMasterSnapshots( $fname = __METHOD__
) {
1734 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1735 $conn->flushSnapshot( $fname );
1743 public function getTransactionRoundStage() {
1744 return $this->trxRoundStage
;
1747 public function hasMasterConnection() {
1748 return $this->isOpen( $this->getWriterIndex() );
1751 public function hasMasterChanges() {
1753 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1754 $pending |
= $conn->writesOrCallbacksPending();
1757 return (bool)$pending;
1760 public function lastMasterChangeTimestamp() {
1762 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1763 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1769 public function hasOrMadeRecentMasterChanges( $age = null ) {
1770 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1772 return ( $this->hasMasterChanges()
1773 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1776 public function pendingMasterChangeCallers() {
1778 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1779 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1785 public function getLaggedReplicaMode( $domain = false ) {
1787 // Avoid recursion if there is only one DB
1788 $this->getServerCount() > 1 &&
1789 // Avoid recursion if the (non-zero load) master DB was picked for generic reads
1790 $this->genericReadIndex
!== $this->getWriterIndex() &&
1791 // Stay in lagged replica mode during the load balancer instance lifetime
1792 !$this->laggedReplicaMode
1795 // Calling this method will set "laggedReplicaMode" as needed
1796 $this->getReaderIndex( false, $domain );
1797 } catch ( DBConnectionError
$e ) {
1798 // Avoid expensive re-connect attempts and failures
1799 $this->allReplicasDownMode
= true;
1800 $this->laggedReplicaMode
= true;
1804 return $this->laggedReplicaMode
;
1807 public function laggedReplicaUsed() {
1808 return $this->laggedReplicaMode
;
1814 * @deprecated Since 1.28; use laggedReplicaUsed()
1816 public function laggedSlaveUsed() {
1817 return $this->laggedReplicaUsed();
1820 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1821 if ( $this->readOnlyReason
!== false ) {
1822 return $this->readOnlyReason
;
1823 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1824 if ( $this->allReplicasDownMode
) {
1825 return 'The database has been automatically locked ' .
1826 'until the replica database servers become available';
1828 return 'The database has been automatically locked ' .
1829 'while the replica database servers catch up to the master.';
1831 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1832 return 'The database master is running in read-only mode.';
1839 * @param string $domain Domain ID, or false for the current domain
1840 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1843 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1844 $cache = $this->wanCache
;
1845 $masterServer = $this->getServerName( $this->getWriterIndex() );
1847 return (bool)$cache->getWithSetCallback(
1848 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1849 self
::TTL_CACHE_READONLY
,
1850 function () use ( $domain, $conn ) {
1851 $old = $this->trxProfiler
->setSilenced( true );
1853 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1854 $readOnly = (int)$dbw->serverIsReadOnly();
1856 $this->reuseConnection( $dbw );
1858 } catch ( DBError
$e ) {
1861 $this->trxProfiler
->setSilenced( $old );
1864 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1868 public function allowLagged( $mode = null ) {
1869 if ( $mode === null ) {
1870 return $this->allowLagged
;
1872 $this->allowLagged
= $mode;
1874 return $this->allowLagged
;
1877 public function pingAll() {
1879 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1880 if ( !$conn->ping() ) {
1888 public function forEachOpenConnection( $callback, array $params = [] ) {
1889 foreach ( $this->conns
as $connsByServer ) {
1890 foreach ( $connsByServer as $serverConns ) {
1891 foreach ( $serverConns as $conn ) {
1892 $callback( $conn, ...$params );
1898 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1899 $masterIndex = $this->getWriterIndex();
1900 foreach ( $this->conns
as $connsByServer ) {
1901 if ( isset( $connsByServer[$masterIndex] ) ) {
1902 /** @var IDatabase $conn */
1903 foreach ( $connsByServer[$masterIndex] as $conn ) {
1904 $callback( $conn, ...$params );
1910 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1911 foreach ( $this->conns
as $connsByServer ) {
1912 foreach ( $connsByServer as $i => $serverConns ) {
1913 if ( $i === $this->getWriterIndex() ) {
1914 continue; // skip master
1916 foreach ( $serverConns as $conn ) {
1917 $callback( $conn, ...$params );
1923 public function getMaxLag( $domain = false ) {
1928 if ( $this->getServerCount() <= 1 ) {
1929 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1932 $lagTimes = $this->getLagTimes( $domain );
1933 foreach ( $lagTimes as $i => $lag ) {
1934 if ( $this->genericLoads
[$i] > 0 && $lag > $maxLag ) {
1936 $host = $this->servers
[$i]['host'];
1941 return [ $host, $maxLag, $maxIndex ];
1944 public function getLagTimes( $domain = false ) {
1945 if ( $this->getServerCount() <= 1 ) {
1946 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1949 $knownLagTimes = []; // map of (server index => 0 seconds)
1950 $indexesWithLag = [];
1951 foreach ( $this->servers
as $i => $server ) {
1952 if ( empty( $server['is static'] ) ) {
1953 $indexesWithLag[] = $i; // DB server might have replication lag
1955 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1959 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1963 * Get the lag in seconds for a given connection, or zero if this load
1964 * balancer does not have replication enabled.
1966 * This should be used in preference to Database::getLag() in cases where
1967 * replication may not be in use, since there is no way to determine if
1968 * replication is in use at the connection level without running
1969 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1970 * function instead of Database::getLag() avoids a fatal error in this
1971 * case on many installations.
1973 * @param IDatabase $conn
1974 * @return int|bool Returns false on error
1975 * @deprecated Since 1.34 Use IDatabase::getLag() instead
1977 public function safeGetLag( IDatabase
$conn ) {
1978 if ( $this->getServerCount() <= 1 ) {
1981 return $conn->getLag();
1985 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
1986 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
1988 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1989 return true; // server is not a replica DB
1993 // Get the current master position, opening a connection if needed
1994 $index = $this->getWriterIndex();
1995 $masterConn = $this->getAnyOpenConnection( $index );
1996 if ( $masterConn ) {
1997 $pos = $masterConn->getMasterPos();
1999 $flags = self
::CONN_SILENCE_ERRORS
;
2000 $masterConn = $this->getConnection( $index, [], self
::DOMAIN_ANY
, $flags );
2001 if ( !$masterConn ) {
2002 throw new DBReplicationWaitError(
2004 "Could not obtain a master database connection to get the position"
2007 $pos = $masterConn->getMasterPos();
2008 $this->closeConnection( $masterConn );
2012 if ( $pos instanceof DBMasterPos
) {
2013 $start = microtime( true );
2014 $result = $conn->masterPosWait( $pos, $timeout );
2015 $seconds = max( microtime( true ) - $start, 0 );
2016 if ( $result == -1 ||
is_null( $result ) ) {
2017 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos} [{seconds}s]';
2018 $this->replLogger
->warning( $msg, [
2019 'host' => $conn->getServer(),
2021 'seconds' => round( $seconds, 6 ),
2022 'trace' => ( new RuntimeException() )->getTraceAsString()
2026 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
2030 $ok = false; // something is misconfigured
2031 $this->replLogger
->error(
2032 __METHOD__
. ': could not get master pos for {host}',
2034 'host' => $conn->getServer(),
2035 'trace' => ( new RuntimeException() )->getTraceAsString()
2043 public function setTransactionListener( $name, callable
$callback = null ) {
2045 $this->trxRecurringCallbacks
[$name] = $callback;
2047 unset( $this->trxRecurringCallbacks
[$name] );
2049 $this->forEachOpenMasterConnection(
2050 function ( IDatabase
$conn ) use ( $name, $callback ) {
2051 $conn->setTransactionListener( $name, $callback );
2056 public function setTableAliases( array $aliases ) {
2057 $this->tableAliases
= $aliases;
2060 public function setIndexAliases( array $aliases ) {
2061 $this->indexAliases
= $aliases;
2065 * @param string $prefix
2066 * @deprecated Since 1.33
2068 public function setDomainPrefix( $prefix ) {
2069 $this->setLocalDomainPrefix( $prefix );
2072 public function setLocalDomainPrefix( $prefix ) {
2073 // Find connections to explicit foreign domains still marked as in-use...
2075 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
2076 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
2077 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
2078 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
2079 $domainsInUse[] = $conn->getDomainID();
2083 // Do not switch connections to explicit foreign domains unless marked as safe
2084 if ( $domainsInUse ) {
2085 $domains = implode( ', ', $domainsInUse );
2086 throw new DBUnexpectedError( null,
2087 "Foreign domain connections are still in use ($domains)" );
2090 $this->setLocalDomain( new DatabaseDomain(
2091 $this->localDomain
->getDatabase(),
2092 $this->localDomain
->getSchema(),
2096 // Update the prefix for all local connections...
2097 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
2098 if ( !$db->getLBInfo( 'foreign' ) ) {
2099 $db->tablePrefix( $prefix );
2104 public function redefineLocalDomain( $domain ) {
2107 $this->setLocalDomain( DatabaseDomain
::newFromId( $domain ) );
2111 * @param DatabaseDomain $domain
2113 private function setLocalDomain( DatabaseDomain
$domain ) {
2114 $this->localDomain
= $domain;
2115 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
2116 // always true, gracefully handle the case when they fail to account for escaping.
2117 if ( $this->localDomain
->getTablePrefix() != '' ) {
2118 $this->localDomainIdAlias
=
2119 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
2121 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
2125 function __destruct() {
2126 // Avoid connection leaks for sanity
2132 * @deprecated since 1.29
2134 class_alias( LoadBalancer
::class, 'LoadBalancer' );