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) */
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 (of $mServers) */
108 /** @var bool|DBMasterPos False if not set */
110 /** @var bool Whether the generic reader fell back to a lagged replica DB */
111 private $laggedReplicaMode = false;
112 /** @var bool Whether the generic reader fell back to a lagged replica DB */
113 private $allReplicasDownMode = false;
114 /** @var string The last DB selection or connection error */
115 private $lastError = 'Unknown error';
116 /** @var string|bool Reason the LB is read-only or false if not */
117 private $readOnlyReason = false;
118 /** @var int Total connections opened */
119 private $connsOpened = 0;
121 private $disabled = false;
122 /** @var bool Whether any connection has been attempted yet */
123 private $connectionAttempted = false;
125 /** @var string|bool String if a requested DBO_TRX transaction round is active */
126 private $trxRoundId = false;
127 /** @var string Stage of the current transaction round in the transaction round life-cycle */
128 private $trxRoundStage = self
::ROUND_CURSORY
;
130 /** @var string|null */
131 private $defaultGroup = null;
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 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'] ) ) {
166 throw new InvalidArgumentException( __CLASS__
. ': missing "servers" parameter' );
168 $this->servers
= $params['servers'];
169 foreach ( $this->servers
as $i => $server ) {
171 $this->servers
[$i]['master'] = true;
173 $this->servers
[$i]['replica'] = true;
177 $localDomain = isset( $params['localDomain'] )
178 ? DatabaseDomain
::newFromId( $params['localDomain'] )
179 : DatabaseDomain
::newUnspecified();
180 $this->setLocalDomain( $localDomain );
182 $this->waitTimeout
= $params['waitTimeout'] ?? self
::MAX_WAIT_DEFAULT
;
184 $this->readIndex
= -1;
186 // Connection were transaction rounds may be applied
187 self
::KEY_LOCAL
=> [],
188 self
::KEY_FOREIGN_INUSE
=> [],
189 self
::KEY_FOREIGN_FREE
=> [],
190 // Auto-committing counterpart connections that ignore transaction rounds
191 self
::KEY_LOCAL_NOROUND
=> [],
192 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
193 self
::KEY_FOREIGN_FREE_NOROUND
=> []
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 foreach ( $params['servers'] as $i => $server ) {
209 $this->loads
[$i] = $server['load'];
210 if ( isset( $server['groupLoads'] ) ) {
211 foreach ( $server['groupLoads'] as $group => $ratio ) {
212 if ( !isset( $this->groupLoads
[$group] ) ) {
213 $this->groupLoads
[$group] = [];
215 $this->groupLoads
[$group][$i] = $ratio;
220 $this->srvCache
= $params['srvCache'] ??
new EmptyBagOStuff();
221 $this->wanCache
= $params['wanCache'] ?? WANObjectCache
::newEmpty();
222 $this->profiler
= $params['profiler'] ??
null;
223 $this->trxProfiler
= $params['trxProfiler'] ??
new TransactionProfiler();
225 $this->errorLogger
= $params['errorLogger'] ??
function ( Exception
$e ) {
226 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
228 $this->deprecationLogger
= $params['deprecationLogger'] ??
function ( $msg ) {
229 trigger_error( $msg, E_USER_DEPRECATED
);
232 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
233 $this->$key = $params[$key] ??
new NullLogger();
236 $this->hostname
= $params['hostname'] ??
( gethostname() ?
: 'unknown' );
237 $this->cliMode
= $params['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
238 $this->agent
= $params['agent'] ??
'';
240 if ( isset( $params['chronologyCallback'] ) ) {
241 $this->chronologyCallback
= $params['chronologyCallback'];
244 if ( isset( $params['roundStage'] ) ) {
245 if ( $params['roundStage'] === self
::STAGE_POSTCOMMIT_CALLBACKS
) {
246 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
247 } elseif ( $params['roundStage'] === self
::STAGE_POSTROLLBACK_CALLBACKS
) {
248 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
252 $this->defaultGroup
= $params['defaultGroup'] ??
null;
255 public function getLocalDomainID() {
256 return $this->localDomain
->getId();
259 public function resolveDomainID( $domain ) {
260 if ( $domain === $this->localDomainIdAlias ||
$domain === false ) {
261 // Local connection requested via some backwards-compatibility domain alias
262 return $this->getLocalDomainID();
265 return (string)$domain;
269 * Get a LoadMonitor instance
271 * @return ILoadMonitor
273 private function getLoadMonitor() {
274 if ( !isset( $this->loadMonitor
) ) {
276 'LoadMonitor' => LoadMonitor
::class,
277 'LoadMonitorNull' => LoadMonitorNull
::class,
278 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
281 $class = $this->loadMonitorConfig
['class'];
282 if ( isset( $compat[$class] ) ) {
283 $class = $compat[$class];
286 $this->loadMonitor
= new $class(
287 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
288 $this->loadMonitor
->setLogger( $this->replLogger
);
291 return $this->loadMonitor
;
295 * @param array $loads
296 * @param bool|string $domain Domain to get non-lagged for
297 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
298 * @return bool|int|string
300 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
301 $lags = $this->getLagTimes( $domain );
303 # Unset excessively lagged servers
304 foreach ( $lags as $i => $lag ) {
306 # How much lag this server nominally is allowed to have
307 $maxServerLag = $this->servers
[$i]['max lag'] ??
$this->maxLag
; // default
308 # Constrain that futher by $maxLag argument
309 $maxServerLag = min( $maxServerLag, $maxLag );
311 $host = $this->getServerName( $i );
312 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
313 $this->replLogger
->debug(
315 ": server {host} is not replicating?", [ 'host' => $host ] );
317 } elseif ( $lag > $maxServerLag ) {
318 $this->replLogger
->debug(
320 ": server {host} has {lag} seconds of lag (>= {maxlag})",
321 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
328 # Find out if all the replica DBs with non-zero load are lagged
330 foreach ( $loads as $load ) {
334 # No appropriate DB servers except maybe the master and some replica DBs with zero load
335 # Do NOT use the master
336 # Instead, this function will return false, triggering read-only mode,
337 # and a lagged replica DB will be used instead.
341 if ( count( $loads ) == 0 ) {
345 # Return a random representative of the remainder
346 return ArrayUtils
::pickRandom( $loads );
351 * @param array $groups
352 * @param string|bool $domain
355 private function getConnectionIndex( $i, $groups, $domain ) {
356 // Check one "group" per default: the generic pool
357 $defaultGroups = $this->defaultGroup ?
[ $this->defaultGroup
] : [ false ];
359 $groups = ( $groups === false ||
$groups === [] )
363 if ( $i == self
::DB_MASTER
) {
364 $i = $this->getWriterIndex();
365 } elseif ( $i == self
::DB_REPLICA
) {
366 # Try to find an available server in any the query groups (in order)
367 foreach ( $groups as $group ) {
368 $groupIndex = $this->getReaderIndex( $group, $domain );
369 if ( $groupIndex !== false ) {
376 # Operation-based index
377 if ( $i == self
::DB_REPLICA
) {
378 $this->lastError
= 'Unknown error'; // reset error string
379 # Try the general server pool if $groups are unavailable.
380 $i = ( $groups === [ false ] )
381 ?
false // don't bother with this if that is what was tried above
382 : $this->getReaderIndex( false, $domain );
383 # Couldn't find a working server in getReaderIndex()?
384 if ( $i === false ) {
385 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
386 // Throw an exception
387 $this->reportConnectionError();
388 return null; // not reached
395 public function getReaderIndex( $group = false, $domain = false ) {
396 if ( count( $this->servers
) == 1 ) {
397 // Skip the load balancing if there's only one server
398 return $this->getWriterIndex();
399 } elseif ( $group === false && $this->readIndex
>= 0 ) {
400 // Shortcut if the generic reader index was already cached
401 return $this->readIndex
;
404 if ( $group !== false ) {
405 // Use the server weight array for this load group
406 if ( isset( $this->groupLoads
[$group] ) ) {
407 $loads = $this->groupLoads
[$group];
409 // No loads for this group, return false and the caller can use some other group
410 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
415 // Use the generic load group
416 $loads = $this->loads
;
419 // Scale the configured load ratios according to each server's load and state
420 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
422 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
423 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
424 if ( $i === false ) {
425 // Replica DB connection unsuccessful
429 if ( $this->waitForPos
&& $i != $this->getWriterIndex() ) {
430 // Before any data queries are run, wait for the server to catch up to the
431 // specified position. This is used to improve session consistency. Note that
432 // when LoadBalancer::waitFor() sets "waitForPos", the waiting triggers here,
433 // so update laggedReplicaMode as needed for consistency.
434 if ( !$this->doWait( $i ) ) {
435 $laggedReplicaMode = true;
439 if ( $this->readIndex
<= 0 && $this->loads
[$i] > 0 && $group === false ) {
440 // Cache the generic reader index for future ungrouped DB_REPLICA handles
441 $this->readIndex
= $i;
442 // Record if the generic reader index is in "lagged replica DB" mode
443 if ( $laggedReplicaMode ) {
444 $this->laggedReplicaMode
= true;
448 $serverName = $this->getServerName( $i );
449 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
455 * @param array $loads List of server weights
456 * @param string|bool $domain
457 * @return array (reader index, lagged replica mode) or false on failure
459 private function pickReaderIndex( array $loads, $domain = false ) {
460 if ( $loads === [] ) {
461 throw new InvalidArgumentException( "Server configuration array is empty" );
464 /** @var int|bool $i Index of selected server */
466 /** @var bool $laggedReplicaMode Whether server is considered lagged */
467 $laggedReplicaMode = false;
469 // Quickly look through the available servers for a server that meets criteria...
470 $currentLoads = $loads;
471 while ( count( $currentLoads ) ) {
472 if ( $this->allowLagged ||
$laggedReplicaMode ) {
473 $i = ArrayUtils
::pickRandom( $currentLoads );
476 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
477 // "chronologyCallback" sets "waitForPos" for session consistency.
478 // This triggers doWait() after connect, so it's especially good to
479 // avoid lagged servers so as to avoid excessive delay in that method.
480 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
481 // Aim for <= 1 second of waiting (being too picky can backfire)
482 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
484 if ( $i === false ) {
485 // Any server with less lag than it's 'max lag' param is preferable
486 $i = $this->getRandomNonLagged( $currentLoads, $domain );
488 if ( $i === false && count( $currentLoads ) != 0 ) {
489 // All replica DBs lagged. Switch to read-only mode
490 $this->replLogger
->error(
491 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
492 $i = ArrayUtils
::pickRandom( $currentLoads );
493 $laggedReplicaMode = true;
497 if ( $i === false ) {
498 // pickRandom() returned false.
499 // This is permanent and means the configuration or the load monitor
500 // wants us to return false.
501 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
503 return [ false, false ];
506 $serverName = $this->getServerName( $i );
507 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
509 $conn = $this->openConnection( $i, $domain );
511 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
512 unset( $currentLoads[$i] ); // avoid this server next iteration
517 // Decrement reference counter, we are finished with this connection.
518 // It will be incremented for the caller later.
519 if ( $domain !== false ) {
520 $this->reuseConnection( $conn );
523 // Return this server
527 // If all servers were down, quit now
528 if ( $currentLoads === [] ) {
529 $this->connLogger
->error( __METHOD__
. ": all servers down" );
532 return [ $i, $laggedReplicaMode ];
535 public function waitFor( $pos ) {
536 $oldPos = $this->waitForPos
;
538 $this->waitForPos
= $pos;
539 // If a generic reader connection was already established, then wait now
540 $i = $this->readIndex
;
541 if ( ( $i > 0 ) && !$this->doWait( $i ) ) {
542 $this->laggedReplicaMode
= true;
545 // Restore the older position if it was higher since this is used for lag-protection
546 $this->setWaitForPositionIfHigher( $oldPos );
550 public function waitForOne( $pos, $timeout = null ) {
551 $oldPos = $this->waitForPos
;
553 $this->waitForPos
= $pos;
555 $i = $this->readIndex
;
557 // Pick a generic replica DB if there isn't one yet
558 $readLoads = $this->loads
;
559 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
560 $readLoads = array_filter( $readLoads ); // with non-zero load
561 $i = ArrayUtils
::pickRandom( $readLoads );
565 $ok = $this->doWait( $i, true, $timeout );
567 $ok = true; // no applicable loads
570 # Restore the old position, as this is not used for lag-protection but for throttling
571 $this->waitForPos
= $oldPos;
577 public function waitForAll( $pos, $timeout = null ) {
578 $timeout = $timeout ?
: $this->waitTimeout
;
580 $oldPos = $this->waitForPos
;
582 $this->waitForPos
= $pos;
583 $serverCount = count( $this->servers
);
586 for ( $i = 1; $i < $serverCount; $i++
) {
587 if ( $this->loads
[$i] > 0 ) {
588 $start = microtime( true );
589 $ok = $this->doWait( $i, true, $timeout ) && $ok;
590 $timeout -= intval( microtime( true ) - $start );
591 if ( $timeout <= 0 ) {
592 break; // timeout reached
597 # Restore the old position, as this is not used for lag-protection but for throttling
598 $this->waitForPos
= $oldPos;
605 * @param DBMasterPos|bool $pos
607 private function setWaitForPositionIfHigher( $pos ) {
612 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
613 $this->waitForPos
= $pos;
617 public function getAnyOpenConnection( $i, $flags = 0 ) {
618 $i = ( $i === self
::DB_MASTER
) ?
$this->getWriterIndex() : $i;
619 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
621 foreach ( $this->conns
as $connsByServer ) {
622 if ( $i === self
::DB_REPLICA
) {
623 $indexes = array_keys( $connsByServer );
625 $indexes = isset( $connsByServer[$i] ) ?
[ $i ] : [];
628 foreach ( $indexes as $index ) {
629 foreach ( $connsByServer[$index] as $conn ) {
630 if ( !$conn->isOpen() ) {
631 continue; // some sort of error occured?
633 if ( !$autocommit ||
$conn->getLBInfo( 'autoCommitOnly' ) ) {
644 * Wait for a given replica DB to catch up to the master pos stored in $this
645 * @param int $index Server index
646 * @param bool $open Check the server even if a new connection has to be made
647 * @param int|null $timeout Max seconds to wait; default is "waitTimeout" given to __construct()
650 protected function doWait( $index, $open = false, $timeout = null ) {
651 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
653 // Check if we already know that the DB has reached this point
654 $server = $this->getServerName( $index );
655 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
656 /** @var DBMasterPos $knownReachedPos */
657 $knownReachedPos = $this->srvCache
->get( $key );
659 $knownReachedPos instanceof DBMasterPos
&&
660 $knownReachedPos->hasReached( $this->waitForPos
)
662 $this->replLogger
->debug(
664 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
665 [ 'dbserver' => $server ]
670 // Find a connection to wait on, creating one if needed and allowed
671 $close = false; // close the connection afterwards
672 $conn = $this->getAnyOpenConnection( $index );
675 $this->replLogger
->debug(
676 __METHOD__
. ': no connection open for {dbserver}',
677 [ 'dbserver' => $server ]
682 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
684 $this->replLogger
->warning(
685 __METHOD__
. ': failed to connect to {dbserver}',
686 [ 'dbserver' => $server ]
691 // Avoid connection spam in waitForAll() when connections
692 // are made just for the sake of doing this lag check.
697 $this->replLogger
->info(
699 ': waiting for replica DB {dbserver} to catch up...',
700 [ 'dbserver' => $server ]
703 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
705 if ( $result === null ) {
706 $this->replLogger
->warning(
707 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
710 'pos' => $this->waitForPos
,
711 'trace' => ( new RuntimeException() )->getTraceAsString()
715 } elseif ( $result == -1 ) {
716 $this->replLogger
->warning(
717 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
720 'pos' => $this->waitForPos
,
721 'trace' => ( new RuntimeException() )->getTraceAsString()
726 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
728 // Remember that the DB reached this point
729 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
733 $this->closeConnection( $conn );
739 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
740 if ( $i === null ||
$i === false ) {
741 throw new InvalidArgumentException( "Cannot connect without a server index" );
744 $domain = $this->resolveDomainID( $domain );
745 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
747 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) === self
::CONN_TRX_AUTOCOMMIT
) {
748 // Assuming all servers are of the same type (or similar), which is overwhelmingly
749 // the case, use the master server information to get the attributes. The information
750 // for $i cannot be used since it might be DB_REPLICA, which might require connection
751 // attempts in order to be resolved into a real server index.
752 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
753 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
754 // Callers sometimes want to (a) escape REPEATABLE-READ stateness without locking
755 // rows (e.g. FOR UPDATE) or (b) make small commits during a larger transactions
756 // to reduce lock contention. None of these apply for sqlite and using separate
757 // connections just causes self-deadlocks.
758 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
759 $this->connLogger
->info( __METHOD__
.
760 ': ignoring CONN_TRX_AUTOCOMMIT to avoid deadlocks.' );
764 // Number of connections made before getting the server index and handle
765 $priorConnectionsMade = $this->connsOpened
;
766 // Decide which server to use (might trigger new connections)
767 $serverIndex = $this->getConnectionIndex( $i, $groups, $domain );
768 // Get an open connection to that server (might trigger a new connection)
769 $conn = $this->openConnection( $serverIndex, $domain, $flags );
771 $this->reportConnectionError();
772 return null; // unreachable due to exception
775 // Profile any new connections caused by this method
776 if ( $this->connsOpened
> $priorConnectionsMade ) {
777 $host = $conn->getServer();
778 $dbname = $conn->getDBname();
779 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
783 // If the load balancer is read-only, perhaps due to replication lag, then master
784 // DB handles will reflect that. Note that Database::assertIsWritableMaster() takes
785 // care of replica DB handles whereas getReadOnlyReason() would cause infinite loops.
786 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
792 public function reuseConnection( IDatabase
$conn ) {
793 $serverIndex = $conn->getLBInfo( 'serverIndex' );
794 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
795 if ( $serverIndex === null ||
$refCount === null ) {
797 * This can happen in code like:
798 * foreach ( $dbs as $db ) {
799 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
801 * $lb->reuseConnection( $conn );
803 * When a connection to the local DB is opened in this way, reuseConnection()
807 } elseif ( $conn instanceof DBConnRef
) {
808 // DBConnRef already handles calling reuseConnection() and only passes the live
809 // Database instance to this method. Any caller passing in a DBConnRef is broken.
810 $this->connLogger
->error(
811 __METHOD__
. ": got DBConnRef instance.\n" .
812 ( new RuntimeException() )->getTraceAsString() );
817 if ( $this->disabled
) {
818 return; // DBConnRef handle probably survived longer than the LoadBalancer
821 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
822 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
823 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
825 $connFreeKey = self
::KEY_FOREIGN_FREE
;
826 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
829 $domain = $conn->getDomainID();
830 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
831 throw new InvalidArgumentException(
832 "Connection $serverIndex/$domain not found; it may have already been freed" );
833 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
834 throw new InvalidArgumentException(
835 "Connection $serverIndex/$domain mismatched; it may have already been freed" );
838 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
839 if ( $refCount <= 0 ) {
840 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
841 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
842 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
843 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
845 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
847 $this->connLogger
->debug( __METHOD__
.
848 ": reference count for $serverIndex/$domain reduced to $refCount" );
852 public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
853 $domain = $this->resolveDomainID( $domain );
854 $role = $this->getRoleFromIndex( $i );
856 return new DBConnRef( $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
859 public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
860 $domain = $this->resolveDomainID( $domain );
861 $role = $this->getRoleFromIndex( $i );
863 return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role );
866 public function getMaintenanceConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
867 $domain = $this->resolveDomainID( $domain );
868 $role = $this->getRoleFromIndex( $i );
870 return new MaintainableDBConnRef(
871 $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
875 * @param int $i Server index or DB_MASTER/DB_REPLICA
876 * @return int One of DB_MASTER/DB_REPLICA
878 private function getRoleFromIndex( $i ) {
879 return ( $i === self
::DB_MASTER ||
$i === $this->getWriterIndex() )
884 public function openConnection( $i, $domain = false, $flags = 0 ) {
885 $domain = $this->resolveDomainID( $domain );
887 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
888 // Load any "waitFor" positions before connecting so that doWait() is triggered
889 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
890 $this->connectionAttempted
= true;
891 ( $this->chronologyCallback
)( $this );
894 $conn = $this->localDomain
->equals( $domain )
895 ?
$this->openLocalConnection( $i, $flags )
896 : $this->openForeignConnection( $i, $domain, $flags );
898 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
899 // Connection was made but later unrecoverably lost for some reason.
900 // Do not return a handle that will just throw exceptions on use,
901 // but let the calling code (e.g. getReaderIndex) try another server.
902 $this->errorConnection
= $conn;
907 $conn instanceof IDatabase
&&
908 ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
)
910 if ( $conn->trxLevel() ) { // sanity
911 throw new DBUnexpectedError(
913 'Handle requested with CONN_TRX_AUTOCOMMIT yet it has a transaction'
917 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
924 * Open a connection to a local DB, or return one if it is already open.
926 * On error, returns false, and the connection which caused the
927 * error will be available via $this->errorConnection.
929 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
931 * @param int $i Server index
932 * @param int $flags Class CONN_* constant bitfield
935 private function openLocalConnection( $i, $flags = 0 ) {
936 // Connection handles required to be in auto-commit mode use a separate connection
937 // pool since the main pool is effected by implicit and explicit transaction rounds
938 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
940 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
941 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
942 $conn = $this->conns
[$connKey][$i][0];
944 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
945 throw new InvalidArgumentException( "No server with index '$i'" );
947 // Open a new connection
948 $server = $this->servers
[$i];
949 $server['serverIndex'] = $i;
950 $server['autoCommitOnly'] = $autoCommit;
951 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
952 $host = $this->getServerName( $i );
953 if ( $conn->isOpen() ) {
954 $this->connLogger
->debug(
955 __METHOD__
. ": connected to database $i at '$host'." );
956 $this->conns
[$connKey][$i][0] = $conn;
958 $this->connLogger
->warning(
959 __METHOD__
. ": failed to connect to database $i at '$host'." );
960 $this->errorConnection
= $conn;
965 // Final sanity check to make sure the right domain is selected
967 $conn instanceof IDatabase
&&
968 !$this->localDomain
->isCompatible( $conn->getDomainID() )
970 throw new UnexpectedValueException(
971 "Got connection to '{$conn->getDomainID()}', " .
972 "but expected local domain ('{$this->localDomain}')" );
979 * Open a connection to a foreign DB, or return one if it is already open.
981 * Increments a reference count on the returned connection which locks the
982 * connection to the requested domain. This reference count can be
983 * decremented by calling reuseConnection().
985 * If a connection is open to the appropriate server already, but with the wrong
986 * database, it will be switched to the right database and returned, as long as
987 * it has been freed first with reuseConnection().
989 * On error, returns false, and the connection which caused the
990 * error will be available via $this->errorConnection.
992 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
994 * @param int $i Server index
995 * @param string $domain Domain ID to open
996 * @param int $flags Class CONN_* constant bitfield
997 * @return Database|bool Returns false on connection error
998 * @throws DBError When database selection fails
1000 private function openForeignConnection( $i, $domain, $flags = 0 ) {
1001 $domainInstance = DatabaseDomain
::newFromId( $domain );
1002 // Connection handles required to be in auto-commit mode use a separate connection
1003 // pool since the main pool is effected by implicit and explicit transaction rounds
1004 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
1006 if ( $autoCommit ) {
1007 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
1008 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
1010 $connFreeKey = self
::KEY_FOREIGN_FREE
;
1011 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
1014 /** @var Database $conn */
1017 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
1018 // Reuse an in-use connection for the same domain
1019 $conn = $this->conns
[$connInUseKey][$i][$domain];
1020 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
1021 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
1022 // Reuse a free connection for the same domain
1023 $conn = $this->conns
[$connFreeKey][$i][$domain];
1024 unset( $this->conns
[$connFreeKey][$i][$domain] );
1025 $this->conns
[$connInUseKey][$i][$domain] = $conn;
1026 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
1027 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
1028 // Reuse a free connection from another domain if possible
1029 foreach ( $this->conns
[$connFreeKey][$i] as $oldDomain => $conn ) {
1030 if ( $domainInstance->getDatabase() !== null ) {
1031 // Check if changing the database will require a new connection.
1032 // In that case, leave the connection handle alone and keep looking.
1033 // This prevents connections from being closed mid-transaction and can
1034 // also avoid overhead if the same database will later be requested.
1036 $conn->databasesAreIndependent() &&
1037 $conn->getDBname() !== $domainInstance->getDatabase()
1041 // Select the new database, schema, and prefix
1042 $conn->selectDomain( $domainInstance );
1044 // Stay on the current database, but update the schema/prefix
1045 $conn->dbSchema( $domainInstance->getSchema() );
1046 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1048 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
1049 // Note that if $domain is an empty string, getDomainID() might not match it
1050 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1051 $this->connLogger
->debug( __METHOD__
.
1052 ": reusing free connection from $oldDomain for $domain" );
1058 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
1059 throw new InvalidArgumentException( "No server with index '$i'" );
1061 // Open a new connection
1062 $server = $this->servers
[$i];
1063 $server['serverIndex'] = $i;
1064 $server['foreignPoolRefCount'] = 0;
1065 $server['foreign'] = true;
1066 $server['autoCommitOnly'] = $autoCommit;
1067 $conn = $this->reallyOpenConnection( $server, $domainInstance );
1068 if ( !$conn->isOpen() ) {
1069 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
1070 $this->errorConnection
= $conn;
1073 // Note that if $domain is an empty string, getDomainID() might not match it
1074 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1075 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1079 if ( $conn instanceof IDatabase
) {
1080 // Final sanity check to make sure the right domain is selected
1081 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1082 throw new UnexpectedValueException(
1083 "Got connection to '{$conn->getDomainID()}', but expected '$domain'" );
1085 // Increment reference count
1086 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1087 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1093 public function getServerAttributes( $i ) {
1094 return Database
::attributesFromType(
1095 $this->getServerType( $i ),
1096 $this->servers
[$i]['driver'] ??
null
1101 * Test if the specified index represents an open connection
1103 * @param int $index Server index
1107 private function isOpen( $index ) {
1108 if ( !is_int( $index ) ) {
1112 return (bool)$this->getAnyOpenConnection( $index );
1116 * Open a new network connection to a server (uncached)
1118 * Returns a Database object whether or not the connection was successful.
1120 * @param array $server
1121 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
1123 * @throws DBAccessError
1124 * @throws InvalidArgumentException
1126 protected function reallyOpenConnection( array $server, DatabaseDomain
$domain ) {
1127 if ( $this->disabled
) {
1128 throw new DBAccessError();
1131 if ( $domain->getDatabase() === null ) {
1132 // The database domain does not specify a DB name and some database systems require a
1133 // valid DB specified on connection. The $server configuration array contains a default
1134 // DB name to use for connections in such cases.
1135 if ( $server['type'] === 'mysql' ) {
1136 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1137 // and the DB name in $server might not exist due to legacy reasons (the default
1138 // domain used to ignore the local LB domain, even when mismatched).
1139 $server['dbname'] = null;
1142 $server['dbname'] = $domain->getDatabase();
1145 if ( $domain->getSchema() !== null ) {
1146 $server['schema'] = $domain->getSchema();
1149 // It is always possible to connect with any prefix, even the empty string
1150 $server['tablePrefix'] = $domain->getTablePrefix();
1152 // Let the handle know what the cluster master is (e.g. "db1052")
1153 $masterName = $this->getServerName( $this->getWriterIndex() );
1154 $server['clusterMasterHost'] = $masterName;
1156 // Log when many connection are made on requests
1157 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
1158 $this->perfLogger
->warning( __METHOD__
. ": " .
1159 "{$this->connsOpened}+ connections made (master=$masterName)" );
1162 $server['srvCache'] = $this->srvCache
;
1163 // Set loggers and profilers
1164 $server['connLogger'] = $this->connLogger
;
1165 $server['queryLogger'] = $this->queryLogger
;
1166 $server['errorLogger'] = $this->errorLogger
;
1167 $server['deprecationLogger'] = $this->deprecationLogger
;
1168 $server['profiler'] = $this->profiler
;
1169 $server['trxProfiler'] = $this->trxProfiler
;
1170 // Use the same agent and PHP mode for all DB handles
1171 $server['cliMode'] = $this->cliMode
;
1172 $server['agent'] = $this->agent
;
1173 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1174 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1175 $server['flags'] = $server['flags'] ?? IDatabase
::DBO_DEFAULT
;
1177 // Create a live connection object
1179 $db = Database
::factory( $server['type'], $server );
1180 } catch ( DBConnectionError
$e ) {
1181 // FIXME: This is probably the ugliest thing I have ever done to
1182 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1186 $db->setLBInfo( $server );
1187 $db->setLazyMasterHandle(
1188 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1190 $db->setTableAliases( $this->tableAliases
);
1191 $db->setIndexAliases( $this->indexAliases
);
1193 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1194 if ( $this->trxRoundId
!== false ) {
1195 $this->applyTransactionRoundFlags( $db );
1197 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1198 $db->setTransactionListener( $name, $callback );
1206 * @throws DBConnectionError
1208 private function reportConnectionError() {
1209 $conn = $this->errorConnection
; // the connection which caused the error
1211 'method' => __METHOD__
,
1212 'last_error' => $this->lastError
,
1215 if ( $conn instanceof IDatabase
) {
1216 $context['db_server'] = $conn->getServer();
1217 $this->connLogger
->warning(
1218 __METHOD__
. ": connection error: {last_error} ({db_server})",
1222 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1224 // No last connection, probably due to all servers being too busy
1225 $this->connLogger
->error(
1227 ": LB failure with no last connection. Connection error: {last_error}",
1231 // If all servers were busy, "lastError" will contain something sensible
1232 throw new DBConnectionError( null, $this->lastError
);
1236 public function getWriterIndex() {
1240 public function haveIndex( $i ) {
1241 return array_key_exists( $i, $this->servers
);
1244 public function isNonZeroLoad( $i ) {
1245 return array_key_exists( $i, $this->servers
) && $this->loads
[$i] != 0;
1248 public function getServerCount() {
1249 return count( $this->servers
);
1252 public function getServerName( $i ) {
1253 $name = $this->servers
[$i]['hostName'] ??
$this->servers
[$i]['host'] ??
'';
1255 return ( $name != '' ) ?
$name : 'localhost';
1258 public function getServerInfo( $i ) {
1259 return $this->servers
[$i] ??
false;
1262 public function getServerType( $i ) {
1263 return $this->servers
[$i]['type'] ??
'unknown';
1266 public function getMasterPos() {
1267 # If this entire request was served from a replica DB without opening a connection to the
1268 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1269 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1270 if ( !$masterConn ) {
1271 $serverCount = count( $this->servers
);
1272 for ( $i = 1; $i < $serverCount; $i++
) {
1273 $conn = $this->getAnyOpenConnection( $i );
1275 return $conn->getReplicaPos();
1279 return $masterConn->getMasterPos();
1285 public function disable() {
1287 $this->disabled
= true;
1290 public function closeAll() {
1291 $fname = __METHOD__
;
1292 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( $fname ) {
1293 $host = $conn->getServer();
1294 $this->connLogger
->debug(
1295 $fname . ": closing connection to database '$host'." );
1300 self
::KEY_LOCAL
=> [],
1301 self
::KEY_FOREIGN_INUSE
=> [],
1302 self
::KEY_FOREIGN_FREE
=> [],
1303 self
::KEY_LOCAL_NOROUND
=> [],
1304 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1305 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1307 $this->connsOpened
= 0;
1310 public function closeConnection( IDatabase
$conn ) {
1311 if ( $conn instanceof DBConnRef
) {
1312 // Avoid calling close() but still leaving the handle in the pool
1313 throw new RuntimeException( 'Cannot close DBConnRef instance; it must be shareable' );
1316 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1317 foreach ( $this->conns
as $type => $connsByServer ) {
1318 if ( !isset( $connsByServer[$serverIndex] ) ) {
1322 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1323 if ( $conn === $trackedConn ) {
1324 $host = $this->getServerName( $i );
1325 $this->connLogger
->debug(
1326 __METHOD__
. ": closing connection to database $i at '$host'." );
1327 unset( $this->conns
[$type][$serverIndex][$i] );
1328 --$this->connsOpened
;
1337 public function commitAll( $fname = __METHOD__
) {
1338 $this->commitMasterChanges( $fname );
1339 $this->flushMasterSnapshots( $fname );
1340 $this->flushReplicaSnapshots( $fname );
1343 public function finalizeMasterChanges() {
1344 $this->assertTransactionRoundStage( [ self
::ROUND_CURSORY
, self
::ROUND_FINALIZED
] );
1346 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1347 // Loop until callbacks stop adding callbacks on other connections
1350 $count = 0; // callbacks execution attempts
1351 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$count ) {
1352 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1353 // Any error should cause all (peer) transactions to be rolled back together.
1354 $count +
= $conn->runOnTransactionPreCommitCallbacks();
1357 } while ( $count > 0 );
1358 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1359 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1360 $conn->setTrxEndCallbackSuppression( true );
1362 $this->trxRoundStage
= self
::ROUND_FINALIZED
;
1367 public function approveMasterChanges( array $options ) {
1368 $this->assertTransactionRoundStage( self
::ROUND_FINALIZED
);
1370 $limit = $options['maxWriteDuration'] ??
0;
1372 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1373 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1374 // If atomic sections or explicit transactions are still open, some caller must have
1375 // caught an exception but failed to properly rollback any changes. Detect that and
1376 // throw and error (causing rollback).
1377 $conn->assertNoOpenTransactions();
1378 // Assert that the time to replicate the transaction will be sane.
1379 // If this fails, then all DB transactions will be rollback back together.
1380 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1381 if ( $limit > 0 && $time > $limit ) {
1382 throw new DBTransactionSizeError(
1384 "Transaction spent $time second(s) in writes, exceeding the limit of $limit",
1388 // If a connection sits idle while slow queries execute on another, that connection
1389 // may end up dropped before the commit round is reached. Ping servers to detect this.
1390 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1391 throw new DBTransactionError(
1393 "A connection to the {$conn->getDBname()} database was lost before commit"
1397 $this->trxRoundStage
= self
::ROUND_APPROVED
;
1400 public function beginMasterChanges( $fname = __METHOD__
) {
1401 if ( $this->trxRoundId
!== false ) {
1402 throw new DBTransactionError(
1404 "$fname: Transaction round '{$this->trxRoundId}' already started"
1407 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
1409 // Clear any empty transactions (no writes/callbacks) from the implicit round
1410 $this->flushMasterSnapshots( $fname );
1412 $this->trxRoundId
= $fname;
1413 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1414 // Mark applicable handles as participating in this explicit transaction round.
1415 // For each of these handles, any writes and callbacks will be tied to a single
1416 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1417 // are part of an en masse commit or an en masse rollback.
1418 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1419 $this->applyTransactionRoundFlags( $conn );
1421 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1424 public function commitMasterChanges( $fname = __METHOD__
) {
1425 $this->assertTransactionRoundStage( self
::ROUND_APPROVED
);
1429 /** @noinspection PhpUnusedLocalVariableInspection */
1430 $scope = ScopedCallback
::newScopedIgnoreUserAbort(); // try to ignore client aborts
1432 $restore = ( $this->trxRoundId
!== false );
1433 $this->trxRoundId
= false;
1434 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1435 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1436 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1437 $this->forEachOpenMasterConnection(
1438 function ( IDatabase
$conn ) use ( $fname, &$failures ) {
1440 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1441 } catch ( DBError
$e ) {
1442 ( $this->errorLogger
)( $e );
1443 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1448 throw new DBTransactionError(
1450 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1454 // Unmark handles as participating in this explicit transaction round
1455 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1456 $this->undoTransactionRoundFlags( $conn );
1459 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
1462 public function runMasterTransactionIdleCallbacks() {
1463 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1464 $type = IDatabase
::TRIGGER_COMMIT
;
1465 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1466 $type = IDatabase
::TRIGGER_ROLLBACK
;
1468 throw new DBTransactionError(
1470 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1474 $oldStage = $this->trxRoundStage
;
1475 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1477 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1478 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1479 $conn->setTrxEndCallbackSuppression( false );
1482 $e = null; // first exception
1483 $fname = __METHOD__
;
1484 // Loop until callbacks stop adding callbacks on other connections
1486 // Run any pending callbacks for each connection...
1487 $count = 0; // callback execution attempts
1488 $this->forEachOpenMasterConnection(
1489 function ( Database
$conn ) use ( $type, &$e, &$count ) {
1490 if ( $conn->trxLevel() ) {
1491 return; // retry in the next iteration, after commit() is called
1494 $count +
= $conn->runOnTransactionIdleCallbacks( $type );
1495 } catch ( Exception
$ex ) {
1500 // Clear out any active transactions left over from callbacks...
1501 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$e, $fname ) {
1502 if ( $conn->writesPending() ) {
1503 // A callback from another handle wrote to this one and DBO_TRX is set
1504 $this->queryLogger
->warning( $fname . ": found writes pending." );
1505 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1506 $this->queryLogger
->warning(
1507 $fname . ": found writes pending ($fnames).",
1509 'db_server' => $conn->getServer(),
1510 'db_name' => $conn->getDBname()
1513 } elseif ( $conn->trxLevel() ) {
1514 // A callback from another handle read from this one and DBO_TRX is set,
1515 // which can easily happen if there is only one DB (no replicas)
1516 $this->queryLogger
->debug( $fname . ": found empty transaction." );
1519 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1520 } catch ( Exception
$ex ) {
1524 } while ( $count > 0 );
1526 $this->trxRoundStage
= $oldStage;
1531 public function runMasterTransactionListenerCallbacks() {
1532 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1533 $type = IDatabase
::TRIGGER_COMMIT
;
1534 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1535 $type = IDatabase
::TRIGGER_ROLLBACK
;
1537 throw new DBTransactionError(
1539 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1545 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1546 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1548 $conn->runTransactionListenerCallbacks( $type );
1549 } catch ( Exception
$ex ) {
1553 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1558 public function rollbackMasterChanges( $fname = __METHOD__
) {
1559 $restore = ( $this->trxRoundId
!== false );
1560 $this->trxRoundId
= false;
1561 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1562 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1563 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1566 // Unmark handles as participating in this explicit transaction round
1567 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1568 $this->undoTransactionRoundFlags( $conn );
1571 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
1575 * @param string|string[] $stage
1577 private function assertTransactionRoundStage( $stage ) {
1578 $stages = (array)$stage;
1580 if ( !in_array( $this->trxRoundStage
, $stages, true ) ) {
1581 $stageList = implode(
1583 array_map( function ( $v ) {
1587 throw new DBTransactionError(
1589 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1595 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1597 * Some servers may have neither flag enabled, meaning that they opt out of such
1598 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1599 * when a DB server is used for something like simple key/value storage.
1601 * @param Database $conn
1603 private function applyTransactionRoundFlags( Database
$conn ) {
1604 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1605 return; // transaction rounds do not apply to these connections
1608 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1609 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1610 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1611 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1614 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1615 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1620 * @param Database $conn
1622 private function undoTransactionRoundFlags( Database
$conn ) {
1623 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1624 return; // transaction rounds do not apply to these connections
1627 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1628 $conn->setLBInfo( 'trxRoundId', false );
1631 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1632 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1636 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1637 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) use ( $fname ) {
1638 $conn->flushSnapshot( $fname );
1642 public function flushMasterSnapshots( $fname = __METHOD__
) {
1643 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1644 $conn->flushSnapshot( $fname );
1652 public function getTransactionRoundStage() {
1653 return $this->trxRoundStage
;
1656 public function hasMasterConnection() {
1657 return $this->isOpen( $this->getWriterIndex() );
1660 public function hasMasterChanges() {
1662 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1663 $pending |
= $conn->writesOrCallbacksPending();
1666 return (bool)$pending;
1669 public function lastMasterChangeTimestamp() {
1671 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1672 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1678 public function hasOrMadeRecentMasterChanges( $age = null ) {
1679 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1681 return ( $this->hasMasterChanges()
1682 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1685 public function pendingMasterChangeCallers() {
1687 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1688 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1694 public function getLaggedReplicaMode( $domain = false ) {
1696 // Avoid recursion if there is only one DB
1697 $this->getServerCount() > 1 &&
1698 // Stay in lagged replica mode during the load balancer instance lifetime
1699 !$this->laggedReplicaMode
1702 // See if laggedReplicaMode gets set
1703 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1704 $this->reuseConnection( $conn );
1705 } catch ( DBConnectionError
$e ) {
1706 // Avoid expensive re-connect attempts and failures
1707 $this->allReplicasDownMode
= true;
1708 $this->laggedReplicaMode
= true;
1712 return $this->laggedReplicaMode
;
1715 public function laggedReplicaUsed() {
1716 return $this->laggedReplicaMode
;
1722 * @deprecated Since 1.28; use laggedReplicaUsed()
1724 public function laggedSlaveUsed() {
1725 return $this->laggedReplicaUsed();
1728 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1729 if ( $this->readOnlyReason
!== false ) {
1730 return $this->readOnlyReason
;
1731 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1732 if ( $this->allReplicasDownMode
) {
1733 return 'The database has been automatically locked ' .
1734 'until the replica database servers become available';
1736 return 'The database has been automatically locked ' .
1737 'while the replica database servers catch up to the master.';
1739 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1740 return 'The database master is running in read-only mode.';
1747 * @param string $domain Domain ID, or false for the current domain
1748 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1751 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1752 $cache = $this->wanCache
;
1753 $masterServer = $this->getServerName( $this->getWriterIndex() );
1755 return (bool)$cache->getWithSetCallback(
1756 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1757 self
::TTL_CACHE_READONLY
,
1758 function () use ( $domain, $conn ) {
1759 $old = $this->trxProfiler
->setSilenced( true );
1761 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1762 $readOnly = (int)$dbw->serverIsReadOnly();
1764 $this->reuseConnection( $dbw );
1766 } catch ( DBError
$e ) {
1769 $this->trxProfiler
->setSilenced( $old );
1772 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1776 public function allowLagged( $mode = null ) {
1777 if ( $mode === null ) {
1778 return $this->allowLagged
;
1780 $this->allowLagged
= $mode;
1782 return $this->allowLagged
;
1785 public function pingAll() {
1787 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1788 if ( !$conn->ping() ) {
1796 public function forEachOpenConnection( $callback, array $params = [] ) {
1797 foreach ( $this->conns
as $connsByServer ) {
1798 foreach ( $connsByServer as $serverConns ) {
1799 foreach ( $serverConns as $conn ) {
1800 $callback( $conn, ...$params );
1806 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1807 $masterIndex = $this->getWriterIndex();
1808 foreach ( $this->conns
as $connsByServer ) {
1809 if ( isset( $connsByServer[$masterIndex] ) ) {
1810 /** @var IDatabase $conn */
1811 foreach ( $connsByServer[$masterIndex] as $conn ) {
1812 $callback( $conn, ...$params );
1818 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1819 foreach ( $this->conns
as $connsByServer ) {
1820 foreach ( $connsByServer as $i => $serverConns ) {
1821 if ( $i === $this->getWriterIndex() ) {
1822 continue; // skip master
1824 foreach ( $serverConns as $conn ) {
1825 $callback( $conn, ...$params );
1831 public function getMaxLag( $domain = false ) {
1836 if ( $this->getServerCount() <= 1 ) {
1837 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1840 $lagTimes = $this->getLagTimes( $domain );
1841 foreach ( $lagTimes as $i => $lag ) {
1842 if ( $this->loads
[$i] > 0 && $lag > $maxLag ) {
1844 $host = $this->servers
[$i]['host'];
1849 return [ $host, $maxLag, $maxIndex ];
1852 public function getLagTimes( $domain = false ) {
1853 if ( $this->getServerCount() <= 1 ) {
1854 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1857 $knownLagTimes = []; // map of (server index => 0 seconds)
1858 $indexesWithLag = [];
1859 foreach ( $this->servers
as $i => $server ) {
1860 if ( empty( $server['is static'] ) ) {
1861 $indexesWithLag[] = $i; // DB server might have replication lag
1863 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1867 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1870 public function safeGetLag( IDatabase
$conn ) {
1871 if ( $this->getServerCount() <= 1 ) {
1874 return $conn->getLag();
1878 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
1879 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
1881 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1882 return true; // server is not a replica DB
1886 // Get the current master position, opening a connection if needed
1887 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1888 if ( $masterConn ) {
1889 $pos = $masterConn->getMasterPos();
1891 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1892 if ( !$masterConn ) {
1893 throw new DBReplicationWaitError(
1895 "Could not obtain a master database connection to get the position"
1898 $pos = $masterConn->getMasterPos();
1899 $this->closeConnection( $masterConn );
1903 if ( $pos instanceof DBMasterPos
) {
1904 $result = $conn->masterPosWait( $pos, $timeout );
1905 if ( $result == -1 ||
is_null( $result ) ) {
1906 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos}';
1907 $this->replLogger
->warning( $msg, [
1908 'host' => $conn->getServer(),
1910 'trace' => ( new RuntimeException() )->getTraceAsString()
1914 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
1918 $ok = false; // something is misconfigured
1919 $this->replLogger
->error(
1920 __METHOD__
. ': could not get master pos for {host}',
1922 'host' => $conn->getServer(),
1923 'trace' => ( new RuntimeException() )->getTraceAsString()
1931 public function setTransactionListener( $name, callable
$callback = null ) {
1933 $this->trxRecurringCallbacks
[$name] = $callback;
1935 unset( $this->trxRecurringCallbacks
[$name] );
1937 $this->forEachOpenMasterConnection(
1938 function ( IDatabase
$conn ) use ( $name, $callback ) {
1939 $conn->setTransactionListener( $name, $callback );
1944 public function setTableAliases( array $aliases ) {
1945 $this->tableAliases
= $aliases;
1948 public function setIndexAliases( array $aliases ) {
1949 $this->indexAliases
= $aliases;
1953 * @param string $prefix
1954 * @deprecated Since 1.33
1956 public function setDomainPrefix( $prefix ) {
1957 $this->setLocalDomainPrefix( $prefix );
1960 public function setLocalDomainPrefix( $prefix ) {
1961 // Find connections to explicit foreign domains still marked as in-use...
1963 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
1964 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1965 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1966 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1967 $domainsInUse[] = $conn->getDomainID();
1971 // Do not switch connections to explicit foreign domains unless marked as safe
1972 if ( $domainsInUse ) {
1973 $domains = implode( ', ', $domainsInUse );
1974 throw new DBUnexpectedError( null,
1975 "Foreign domain connections are still in use ($domains)" );
1978 $this->setLocalDomain( new DatabaseDomain(
1979 $this->localDomain
->getDatabase(),
1980 $this->localDomain
->getSchema(),
1984 // Update the prefix for all local connections...
1985 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1986 if ( !$db->getLBInfo( 'foreign' ) ) {
1987 $db->tablePrefix( $prefix );
1992 public function redefineLocalDomain( $domain ) {
1995 $this->setLocalDomain( DatabaseDomain
::newFromId( $domain ) );
1999 * @param DatabaseDomain $domain
2001 private function setLocalDomain( DatabaseDomain
$domain ) {
2002 $this->localDomain
= $domain;
2003 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
2004 // always true, gracefully handle the case when they fail to account for escaping.
2005 if ( $this->localDomain
->getTablePrefix() != '' ) {
2006 $this->localDomainIdAlias
=
2007 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
2009 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
2013 function __destruct() {
2014 // Avoid connection leaks for sanity
2020 * @deprecated since 1.29
2022 class_alias( LoadBalancer
::class, 'LoadBalancer' );