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 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 ID string for the domain instead of DatabaseDomain::getId() */
86 private $localDomainIdAlias;
88 private $maxLag = self
::MAX_LAG_DEFAULT
;
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
= 10;
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 if ( isset( $params['maxLag'] ) ) {
204 $this->maxLag
= $params['maxLag'];
207 $this->loadMonitorConfig
= $params['loadMonitor'] ??
[ 'class' => 'LoadMonitorNull' ];
208 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
210 foreach ( $params['servers'] as $i => $server ) {
211 $this->loads
[$i] = $server['load'];
212 if ( isset( $server['groupLoads'] ) ) {
213 foreach ( $server['groupLoads'] as $group => $ratio ) {
214 if ( !isset( $this->groupLoads
[$group] ) ) {
215 $this->groupLoads
[$group] = [];
217 $this->groupLoads
[$group][$i] = $ratio;
222 $this->srvCache
= $params['srvCache'] ??
new EmptyBagOStuff();
223 $this->wanCache
= $params['wanCache'] ?? WANObjectCache
::newEmpty();
224 $this->profiler
= $params['profiler'] ??
null;
225 $this->trxProfiler
= $params['trxProfiler'] ??
new TransactionProfiler();
227 $this->errorLogger
= $params['errorLogger'] ??
function ( Exception
$e ) {
228 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
230 $this->deprecationLogger
= $params['deprecationLogger'] ??
function ( $msg ) {
231 trigger_error( $msg, E_USER_DEPRECATED
);
234 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
235 $this->$key = $params[$key] ??
new NullLogger();
238 $this->hostname
= $params['hostname'] ??
( gethostname() ?
: 'unknown' );
239 $this->cliMode
= $params['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
240 $this->agent
= $params['agent'] ??
'';
242 if ( isset( $params['chronologyCallback'] ) ) {
243 $this->chronologyCallback
= $params['chronologyCallback'];
246 if ( isset( $params['roundStage'] ) ) {
247 if ( $params['roundStage'] === self
::STAGE_POSTCOMMIT_CALLBACKS
) {
248 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
249 } elseif ( $params['roundStage'] === self
::STAGE_POSTROLLBACK_CALLBACKS
) {
250 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
254 $this->defaultGroup
= $params['defaultGroup'] ??
null;
257 public function getLocalDomainID() {
258 return $this->localDomain
->getId();
261 public function resolveDomainID( $domain ) {
262 return ( $domain !== false ) ?
(string)$domain : $this->getLocalDomainID();
266 * Get a LoadMonitor instance
268 * @return ILoadMonitor
270 private function getLoadMonitor() {
271 if ( !isset( $this->loadMonitor
) ) {
273 'LoadMonitor' => LoadMonitor
::class,
274 'LoadMonitorNull' => LoadMonitorNull
::class,
275 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
278 $class = $this->loadMonitorConfig
['class'];
279 if ( isset( $compat[$class] ) ) {
280 $class = $compat[$class];
283 $this->loadMonitor
= new $class(
284 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
285 $this->loadMonitor
->setLogger( $this->replLogger
);
288 return $this->loadMonitor
;
292 * @param array $loads
293 * @param bool|string $domain Domain to get non-lagged for
294 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
295 * @return bool|int|string
297 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
298 $lags = $this->getLagTimes( $domain );
300 # Unset excessively lagged servers
301 foreach ( $lags as $i => $lag ) {
303 # How much lag this server nominally is allowed to have
304 $maxServerLag = $this->servers
[$i]['max lag'] ??
$this->maxLag
; // default
305 # Constrain that futher by $maxLag argument
306 $maxServerLag = min( $maxServerLag, $maxLag );
308 $host = $this->getServerName( $i );
309 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
310 $this->replLogger
->error(
312 ": server {host} is not replicating?", [ 'host' => $host ] );
314 } elseif ( $lag > $maxServerLag ) {
315 $this->replLogger
->info(
317 ": server {host} has {lag} seconds of lag (>= {maxlag})",
318 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
325 # Find out if all the replica DBs with non-zero load are lagged
327 foreach ( $loads as $load ) {
331 # No appropriate DB servers except maybe the master and some replica DBs with zero load
332 # Do NOT use the master
333 # Instead, this function will return false, triggering read-only mode,
334 # and a lagged replica DB will be used instead.
338 if ( count( $loads ) == 0 ) {
342 # Return a random representative of the remainder
343 return ArrayUtils
::pickRandom( $loads );
346 public function getReaderIndex( $group = false, $domain = false ) {
347 if ( count( $this->servers
) == 1 ) {
348 // Skip the load balancing if there's only one server
349 return $this->getWriterIndex();
350 } elseif ( $group === false && $this->readIndex
>= 0 ) {
351 // Shortcut if the generic reader index was already cached
352 return $this->readIndex
;
355 if ( $group !== false ) {
356 // Use the server weight array for this load group
357 if ( isset( $this->groupLoads
[$group] ) ) {
358 $loads = $this->groupLoads
[$group];
360 // No loads for this group, return false and the caller can use some other group
361 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
366 // Use the generic load group
367 $loads = $this->loads
;
370 // Scale the configured load ratios according to each server's load and state
371 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
373 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
374 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
375 if ( $i === false ) {
376 // Replica DB connection unsuccessful
380 if ( $this->waitForPos
&& $i != $this->getWriterIndex() ) {
381 // Before any data queries are run, wait for the server to catch up to the
382 // specified position. This is used to improve session consistency. Note that
383 // when LoadBalancer::waitFor() sets "waitForPos", the waiting triggers here,
384 // so update laggedReplicaMode as needed for consistency.
385 if ( !$this->doWait( $i ) ) {
386 $laggedReplicaMode = true;
390 if ( $this->readIndex
<= 0 && $this->loads
[$i] > 0 && $group === false ) {
391 // Cache the generic reader index for future ungrouped DB_REPLICA handles
392 $this->readIndex
= $i;
393 // Record if the generic reader index is in "lagged replica DB" mode
394 if ( $laggedReplicaMode ) {
395 $this->laggedReplicaMode
= true;
399 $serverName = $this->getServerName( $i );
400 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
406 * @param array $loads List of server weights
407 * @param string|bool $domain
408 * @return array (reader index, lagged replica mode) or false on failure
410 private function pickReaderIndex( array $loads, $domain = false ) {
411 if ( !count( $loads ) ) {
412 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
415 /** @var int|bool $i Index of selected server */
417 /** @var bool $laggedReplicaMode Whether server is considered lagged */
418 $laggedReplicaMode = false;
420 // Quickly look through the available servers for a server that meets criteria...
421 $currentLoads = $loads;
422 while ( count( $currentLoads ) ) {
423 if ( $this->allowLagged ||
$laggedReplicaMode ) {
424 $i = ArrayUtils
::pickRandom( $currentLoads );
427 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
428 // "chronologyCallback" sets "waitForPos" for session consistency.
429 // This triggers doWait() after connect, so it's especially good to
430 // avoid lagged servers so as to avoid excessive delay in that method.
431 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
432 // Aim for <= 1 second of waiting (being too picky can backfire)
433 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
435 if ( $i === false ) {
436 // Any server with less lag than it's 'max lag' param is preferable
437 $i = $this->getRandomNonLagged( $currentLoads, $domain );
439 if ( $i === false && count( $currentLoads ) != 0 ) {
440 // All replica DBs lagged. Switch to read-only mode
441 $this->replLogger
->error(
442 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
443 $i = ArrayUtils
::pickRandom( $currentLoads );
444 $laggedReplicaMode = true;
448 if ( $i === false ) {
449 // pickRandom() returned false.
450 // This is permanent and means the configuration or the load monitor
451 // wants us to return false.
452 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
454 return [ false, false ];
457 $serverName = $this->getServerName( $i );
458 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
460 $conn = $this->openConnection( $i, $domain );
462 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
463 unset( $currentLoads[$i] ); // avoid this server next iteration
468 // Decrement reference counter, we are finished with this connection.
469 // It will be incremented for the caller later.
470 if ( $domain !== false ) {
471 $this->reuseConnection( $conn );
474 // Return this server
478 // If all servers were down, quit now
479 if ( !count( $currentLoads ) ) {
480 $this->connLogger
->error( __METHOD__
. ": all servers down" );
483 return [ $i, $laggedReplicaMode ];
486 public function waitFor( $pos ) {
487 $oldPos = $this->waitForPos
;
489 $this->waitForPos
= $pos;
490 // If a generic reader connection was already established, then wait now
491 $i = $this->readIndex
;
493 if ( !$this->doWait( $i ) ) {
494 $this->laggedReplicaMode
= true;
498 // Restore the older position if it was higher since this is used for lag-protection
499 $this->setWaitForPositionIfHigher( $oldPos );
503 public function waitForOne( $pos, $timeout = null ) {
504 $oldPos = $this->waitForPos
;
506 $this->waitForPos
= $pos;
508 $i = $this->readIndex
;
510 // Pick a generic replica DB if there isn't one yet
511 $readLoads = $this->loads
;
512 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
513 $readLoads = array_filter( $readLoads ); // with non-zero load
514 $i = ArrayUtils
::pickRandom( $readLoads );
518 $ok = $this->doWait( $i, true, $timeout );
520 $ok = true; // no applicable loads
523 # Restore the old position, as this is not used for lag-protection but for throttling
524 $this->waitForPos
= $oldPos;
530 public function waitForAll( $pos, $timeout = null ) {
531 $timeout = $timeout ?
: $this->waitTimeout
;
533 $oldPos = $this->waitForPos
;
535 $this->waitForPos
= $pos;
536 $serverCount = count( $this->servers
);
539 for ( $i = 1; $i < $serverCount; $i++
) {
540 if ( $this->loads
[$i] > 0 ) {
541 $start = microtime( true );
542 $ok = $this->doWait( $i, true, $timeout ) && $ok;
543 $timeout -= intval( microtime( true ) - $start );
544 if ( $timeout <= 0 ) {
545 break; // timeout reached
550 # Restore the old position, as this is not used for lag-protection but for throttling
551 $this->waitForPos
= $oldPos;
558 * @param DBMasterPos|bool $pos
560 private function setWaitForPositionIfHigher( $pos ) {
565 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
566 $this->waitForPos
= $pos;
570 public function getAnyOpenConnection( $i, $flags = 0 ) {
571 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
572 foreach ( $this->conns
as $connsByServer ) {
573 if ( !isset( $connsByServer[$i] ) ) {
577 foreach ( $connsByServer[$i] as $conn ) {
578 if ( !$autocommit ||
$conn->getLBInfo( 'autoCommitOnly' ) ) {
588 * Wait for a given replica DB to catch up to the master pos stored in $this
589 * @param int $index Server index
590 * @param bool $open Check the server even if a new connection has to be made
591 * @param int|null $timeout Max seconds to wait; default is "waitTimeout" given to __construct()
594 protected function doWait( $index, $open = false, $timeout = null ) {
595 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
597 // Check if we already know that the DB has reached this point
598 $server = $this->getServerName( $index );
599 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
600 /** @var DBMasterPos $knownReachedPos */
601 $knownReachedPos = $this->srvCache
->get( $key );
603 $knownReachedPos instanceof DBMasterPos
&&
604 $knownReachedPos->hasReached( $this->waitForPos
)
606 $this->replLogger
->debug(
608 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
609 [ 'dbserver' => $server ]
614 // Find a connection to wait on, creating one if needed and allowed
615 $close = false; // close the connection afterwards
616 $conn = $this->getAnyOpenConnection( $index );
619 $this->replLogger
->debug(
620 __METHOD__
. ': no connection open for {dbserver}',
621 [ 'dbserver' => $server ]
626 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
628 $this->replLogger
->warning(
629 __METHOD__
. ': failed to connect to {dbserver}',
630 [ 'dbserver' => $server ]
635 // Avoid connection spam in waitForAll() when connections
636 // are made just for the sake of doing this lag check.
641 $this->replLogger
->info(
643 ': waiting for replica DB {dbserver} to catch up...',
644 [ 'dbserver' => $server ]
647 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
649 if ( $result === null ) {
650 $this->replLogger
->warning(
651 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
654 'pos' => $this->waitForPos
,
655 'trace' => ( new RuntimeException() )->getTraceAsString()
659 } elseif ( $result == -1 ) {
660 $this->replLogger
->warning(
661 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
664 'pos' => $this->waitForPos
,
665 'trace' => ( new RuntimeException() )->getTraceAsString()
670 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
672 // Remember that the DB reached this point
673 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
677 $this->closeConnection( $conn );
683 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
684 if ( $i === null ||
$i === false ) {
685 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
686 ' with invalid server index' );
689 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
690 $domain = false; // local connection requested
693 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) === self
::CONN_TRX_AUTOCOMMIT
) {
694 // Assuming all servers are of the same type (or similar), which is overwhelmingly
695 // the case, use the master server information to get the attributes. The information
696 // for $i cannot be used since it might be DB_REPLICA, which might require connection
697 // attempts in order to be resolved into a real server index.
698 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
699 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
700 // Callers sometimes want to (a) escape REPEATABLE-READ stateness without locking
701 // rows (e.g. FOR UPDATE) or (b) make small commits during a larger transactions
702 // to reduce lock contention. None of these apply for sqlite and using separate
703 // connections just causes self-deadlocks.
704 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
705 $this->connLogger
->info( __METHOD__
.
706 ': ignoring CONN_TRX_AUTOCOMMIT to avoid deadlocks.' );
710 // Check one "group" per default: the generic pool
711 $defaultGroups = $this->defaultGroup ?
[ $this->defaultGroup
] : [ false ];
713 $groups = ( $groups === false ||
$groups === [] )
717 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
718 $oldConnsOpened = $this->connsOpened
; // connections open now
720 if ( $i == self
::DB_MASTER
) {
721 $i = $this->getWriterIndex();
722 } elseif ( $i == self
::DB_REPLICA
) {
723 # Try to find an available server in any the query groups (in order)
724 foreach ( $groups as $group ) {
725 $groupIndex = $this->getReaderIndex( $group, $domain );
726 if ( $groupIndex !== false ) {
733 # Operation-based index
734 if ( $i == self
::DB_REPLICA
) {
735 $this->lastError
= 'Unknown error'; // reset error string
736 # Try the general server pool if $groups are unavailable.
737 $i = ( $groups === [ false ] )
738 ?
false // don't bother with this if that is what was tried above
739 : $this->getReaderIndex( false, $domain );
740 # Couldn't find a working server in getReaderIndex()?
741 if ( $i === false ) {
742 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
743 // Throw an exception
744 $this->reportConnectionError();
745 return null; // not reached
749 # Now we have an explicit index into the servers array
750 $conn = $this->openConnection( $i, $domain, $flags );
752 // Throw an exception
753 $this->reportConnectionError();
754 return null; // not reached
757 # Profile any new connections that happen
758 if ( $this->connsOpened
> $oldConnsOpened ) {
759 $host = $conn->getServer();
760 $dbname = $conn->getDBname();
761 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
765 # Make master-requested DB handles inherit any read-only mode setting
766 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
772 public function reuseConnection( IDatabase
$conn ) {
773 $serverIndex = $conn->getLBInfo( 'serverIndex' );
774 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
775 if ( $serverIndex === null ||
$refCount === null ) {
777 * This can happen in code like:
778 * foreach ( $dbs as $db ) {
779 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
781 * $lb->reuseConnection( $conn );
783 * When a connection to the local DB is opened in this way, reuseConnection()
787 } elseif ( $conn instanceof DBConnRef
) {
788 // DBConnRef already handles calling reuseConnection() and only passes the live
789 // Database instance to this method. Any caller passing in a DBConnRef is broken.
790 $this->connLogger
->error(
791 __METHOD__
. ": got DBConnRef instance.\n" .
792 ( new RuntimeException() )->getTraceAsString() );
797 if ( $this->disabled
) {
798 return; // DBConnRef handle probably survived longer than the LoadBalancer
801 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
802 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
803 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
805 $connFreeKey = self
::KEY_FOREIGN_FREE
;
806 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
809 $domain = $conn->getDomainID();
810 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
811 throw new InvalidArgumentException( __METHOD__
.
812 ": connection $serverIndex/$domain not found; it may have already been freed." );
813 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
814 throw new InvalidArgumentException( __METHOD__
.
815 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
818 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
819 if ( $refCount <= 0 ) {
820 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
821 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
822 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
823 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
825 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
827 $this->connLogger
->debug( __METHOD__
.
828 ": reference count for $serverIndex/$domain reduced to $refCount" );
832 public function getConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
833 $domain = $this->resolveDomainID( $domain );
835 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain, $flags ) );
838 public function getLazyConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
839 $domain = $this->resolveDomainID( $domain );
841 return new DBConnRef( $this, [ $db, $groups, $domain, $flags ] );
844 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
845 $domain = $this->resolveDomainID( $domain );
847 return new MaintainableDBConnRef(
848 $this, $this->getConnection( $db, $groups, $domain, $flags ) );
851 public function openConnection( $i, $domain = false, $flags = 0 ) {
852 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
853 $domain = false; // local connection requested
856 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
857 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
858 // Load any "waitFor" positions before connecting so that doWait() is triggered
859 $this->connectionAttempted
= true;
860 ( $this->chronologyCallback
)( $this );
863 // Check if an auto-commit connection is being requested. If so, it will not reuse the
864 // main set of DB connections but rather its own pool since:
865 // a) those are usually set to implicitly use transaction rounds via DBO_TRX
866 // b) those must support the use of explicit transaction rounds via beginMasterChanges()
867 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
869 if ( $domain !== false ) {
870 // Connection is to a foreign domain
871 $conn = $this->openForeignConnection( $i, $domain, $flags );
873 // Connection is to the local domain
874 $conn = $this->openLocalConnection( $i, $flags );
877 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
878 // Connection was made but later unrecoverably lost for some reason.
879 // Do not return a handle that will just throw exceptions on use,
880 // but let the calling code (e.g. getReaderIndex) try another server.
881 // See DatabaseMyslBase::ping() for how this can happen.
882 $this->errorConnection
= $conn;
886 if ( $autoCommit && $conn instanceof IDatabase
) {
887 if ( $conn->trxLevel() ) { // sanity
888 throw new DBUnexpectedError(
890 __METHOD__
. ': CONN_TRX_AUTOCOMMIT handle has a transaction.'
894 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
901 * Open a connection to a local DB, or return one if it is already open.
903 * On error, returns false, and the connection which caused the
904 * error will be available via $this->errorConnection.
906 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
908 * @param int $i Server index
909 * @param int $flags Class CONN_* constant bitfield
912 private function openLocalConnection( $i, $flags = 0 ) {
913 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
915 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
916 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
917 $conn = $this->conns
[$connKey][$i][0];
919 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
920 throw new InvalidArgumentException( "No server with index '$i'." );
922 // Open a new connection
923 $server = $this->servers
[$i];
924 $server['serverIndex'] = $i;
925 $server['autoCommitOnly'] = $autoCommit;
926 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
927 $host = $this->getServerName( $i );
928 if ( $conn->isOpen() ) {
929 $this->connLogger
->debug(
930 __METHOD__
. ": connected to database $i at '$host'." );
931 $this->conns
[$connKey][$i][0] = $conn;
933 $this->connLogger
->warning(
934 __METHOD__
. ": failed to connect to database $i at '$host'." );
935 $this->errorConnection
= $conn;
940 // Final sanity check to make sure the right domain is selected
942 $conn instanceof IDatabase
&&
943 !$this->localDomain
->isCompatible( $conn->getDomainID() )
945 throw new UnexpectedValueException(
946 "Got connection to '{$conn->getDomainID()}', " .
947 "but expected local domain ('{$this->localDomain}')." );
954 * Open a connection to a foreign DB, or return one if it is already open.
956 * Increments a reference count on the returned connection which locks the
957 * connection to the requested domain. This reference count can be
958 * decremented by calling reuseConnection().
960 * If a connection is open to the appropriate server already, but with the wrong
961 * database, it will be switched to the right database and returned, as long as
962 * it has been freed first with reuseConnection().
964 * On error, returns false, and the connection which caused the
965 * error will be available via $this->errorConnection.
967 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
969 * @param int $i Server index
970 * @param string $domain Domain ID to open
971 * @param int $flags Class CONN_* constant bitfield
972 * @return Database|bool Returns false on connection error
973 * @throws DBError When database selection fails
975 private function openForeignConnection( $i, $domain, $flags = 0 ) {
976 $domainInstance = DatabaseDomain
::newFromId( $domain );
977 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
980 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
981 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
983 $connFreeKey = self
::KEY_FOREIGN_FREE
;
984 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
987 /** @var Database $conn */
990 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
991 // Reuse an in-use connection for the same domain
992 $conn = $this->conns
[$connInUseKey][$i][$domain];
993 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
994 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
995 // Reuse a free connection for the same domain
996 $conn = $this->conns
[$connFreeKey][$i][$domain];
997 unset( $this->conns
[$connFreeKey][$i][$domain] );
998 $this->conns
[$connInUseKey][$i][$domain] = $conn;
999 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
1000 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
1001 // Reuse a free connection from another domain if possible
1002 foreach ( $this->conns
[$connFreeKey][$i] as $oldDomain => $conn ) {
1003 if ( $domainInstance->getDatabase() !== null ) {
1004 // Check if changing the database will require a new connection.
1005 // In that case, leave the connection handle alone and keep looking.
1006 // This prevents connections from being closed mid-transaction and can
1007 // also avoid overhead if the same database will later be requested.
1009 $conn->databasesAreIndependent() &&
1010 $conn->getDBname() !== $domainInstance->getDatabase()
1014 // Select the new database, schema, and prefix
1015 $conn->selectDomain( $domainInstance );
1017 // Stay on the current database, but update the schema/prefix
1018 $conn->dbSchema( $domainInstance->getSchema() );
1019 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1021 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
1022 // Note that if $domain is an empty string, getDomainID() might not match it
1023 $this->conns
[$connInUseKey][$i][$conn->getDomainId()] = $conn;
1024 $this->connLogger
->debug( __METHOD__
.
1025 ": reusing free connection from $oldDomain for $domain" );
1031 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
1032 throw new InvalidArgumentException( "No server with index '$i'." );
1034 // Open a new connection
1035 $server = $this->servers
[$i];
1036 $server['serverIndex'] = $i;
1037 $server['foreignPoolRefCount'] = 0;
1038 $server['foreign'] = true;
1039 $server['autoCommitOnly'] = $autoCommit;
1040 $conn = $this->reallyOpenConnection( $server, $domainInstance );
1041 if ( !$conn->isOpen() ) {
1042 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
1043 $this->errorConnection
= $conn;
1046 // Note that if $domain is an empty string, getDomainID() might not match it
1047 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1048 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1052 if ( $conn instanceof IDatabase
) {
1053 // Final sanity check to make sure the right domain is selected
1054 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1055 throw new UnexpectedValueException(
1056 "Got connection to '{$conn->getDomainID()}', but expected '$domain'." );
1058 // Increment reference count
1059 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1060 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1066 public function getServerAttributes( $i ) {
1067 return Database
::attributesFromType(
1068 $this->getServerType( $i ),
1069 $this->servers
[$i]['driver'] ??
null
1074 * Test if the specified index represents an open connection
1076 * @param int $index Server index
1080 private function isOpen( $index ) {
1081 if ( !is_int( $index ) ) {
1085 return (bool)$this->getAnyOpenConnection( $index );
1089 * Open a new network connection to a server (uncached)
1091 * Returns a Database object whether or not the connection was successful.
1093 * @param array $server
1094 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
1096 * @throws DBAccessError
1097 * @throws InvalidArgumentException
1099 protected function reallyOpenConnection( array $server, DatabaseDomain
$domain ) {
1100 if ( $this->disabled
) {
1101 throw new DBAccessError();
1104 if ( $domain->getDatabase() === null ) {
1105 // The database domain does not specify a DB name and some database systems require a
1106 // valid DB specified on connection. The $server configuration array contains a default
1107 // DB name to use for connections in such cases.
1108 if ( $server['type'] === 'mysql' ) {
1109 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1110 // and the DB name in $server might not exist due to legacy reasons (the default
1111 // domain used to ignore the local LB domain, even when mismatched).
1112 $server['dbname'] = null;
1115 $server['dbname'] = $domain->getDatabase();
1118 if ( $domain->getSchema() !== null ) {
1119 $server['schema'] = $domain->getSchema();
1122 // It is always possible to connect with any prefix, even the empty string
1123 $server['tablePrefix'] = $domain->getTablePrefix();
1125 // Let the handle know what the cluster master is (e.g. "db1052")
1126 $masterName = $this->getServerName( $this->getWriterIndex() );
1127 $server['clusterMasterHost'] = $masterName;
1129 // Log when many connection are made on requests
1130 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
1131 $this->perfLogger
->warning( __METHOD__
. ": " .
1132 "{$this->connsOpened}+ connections made (master=$masterName)" );
1135 $server['srvCache'] = $this->srvCache
;
1136 // Set loggers and profilers
1137 $server['connLogger'] = $this->connLogger
;
1138 $server['queryLogger'] = $this->queryLogger
;
1139 $server['errorLogger'] = $this->errorLogger
;
1140 $server['deprecationLogger'] = $this->deprecationLogger
;
1141 $server['profiler'] = $this->profiler
;
1142 $server['trxProfiler'] = $this->trxProfiler
;
1143 // Use the same agent and PHP mode for all DB handles
1144 $server['cliMode'] = $this->cliMode
;
1145 $server['agent'] = $this->agent
;
1146 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1147 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1148 $server['flags'] = $server['flags'] ?? IDatabase
::DBO_DEFAULT
;
1150 // Create a live connection object
1152 $db = Database
::factory( $server['type'], $server );
1153 } catch ( DBConnectionError
$e ) {
1154 // FIXME: This is probably the ugliest thing I have ever done to
1155 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1159 $db->setLBInfo( $server );
1160 $db->setLazyMasterHandle(
1161 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1163 $db->setTableAliases( $this->tableAliases
);
1164 $db->setIndexAliases( $this->indexAliases
);
1166 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1167 if ( $this->trxRoundId
!== false ) {
1168 $this->applyTransactionRoundFlags( $db );
1170 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1171 $db->setTransactionListener( $name, $callback );
1179 * @throws DBConnectionError
1181 private function reportConnectionError() {
1182 $conn = $this->errorConnection
; // the connection which caused the error
1184 'method' => __METHOD__
,
1185 'last_error' => $this->lastError
,
1188 if ( $conn instanceof IDatabase
) {
1189 $context['db_server'] = $conn->getServer();
1190 $this->connLogger
->warning(
1191 __METHOD__
. ": connection error: {last_error} ({db_server})",
1195 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1197 // No last connection, probably due to all servers being too busy
1198 $this->connLogger
->error(
1200 ": LB failure with no last connection. Connection error: {last_error}",
1204 // If all servers were busy, "lastError" will contain something sensible
1205 throw new DBConnectionError( null, $this->lastError
);
1209 public function getWriterIndex() {
1213 public function haveIndex( $i ) {
1214 return array_key_exists( $i, $this->servers
);
1217 public function isNonZeroLoad( $i ) {
1218 return array_key_exists( $i, $this->servers
) && $this->loads
[$i] != 0;
1221 public function getServerCount() {
1222 return count( $this->servers
);
1225 public function getServerName( $i ) {
1226 $name = $this->servers
[$i]['hostName'] ??
$this->servers
[$i]['host'] ??
'';
1228 return ( $name != '' ) ?
$name : 'localhost';
1231 public function getServerInfo( $i ) {
1232 return $this->servers
[$i] ??
false;
1235 public function getServerType( $i ) {
1236 return $this->servers
[$i]['type'] ??
'unknown';
1239 public function getMasterPos() {
1240 # If this entire request was served from a replica DB without opening a connection to the
1241 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1242 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1243 if ( !$masterConn ) {
1244 $serverCount = count( $this->servers
);
1245 for ( $i = 1; $i < $serverCount; $i++
) {
1246 $conn = $this->getAnyOpenConnection( $i );
1248 return $conn->getReplicaPos();
1252 return $masterConn->getMasterPos();
1258 public function disable() {
1260 $this->disabled
= true;
1263 public function closeAll() {
1264 $fname = __METHOD__
;
1265 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( $fname ) {
1266 $host = $conn->getServer();
1267 $this->connLogger
->debug(
1268 $fname . ": closing connection to database '$host'." );
1273 self
::KEY_LOCAL
=> [],
1274 self
::KEY_FOREIGN_INUSE
=> [],
1275 self
::KEY_FOREIGN_FREE
=> [],
1276 self
::KEY_LOCAL_NOROUND
=> [],
1277 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1278 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1280 $this->connsOpened
= 0;
1283 public function closeConnection( IDatabase
$conn ) {
1284 if ( $conn instanceof DBConnRef
) {
1285 // Avoid calling close() but still leaving the handle in the pool
1286 throw new RuntimeException( __METHOD__
. ': got DBConnRef instance.' );
1289 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1290 foreach ( $this->conns
as $type => $connsByServer ) {
1291 if ( !isset( $connsByServer[$serverIndex] ) ) {
1295 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1296 if ( $conn === $trackedConn ) {
1297 $host = $this->getServerName( $i );
1298 $this->connLogger
->debug(
1299 __METHOD__
. ": closing connection to database $i at '$host'." );
1300 unset( $this->conns
[$type][$serverIndex][$i] );
1301 --$this->connsOpened
;
1310 public function commitAll( $fname = __METHOD__
) {
1311 $this->commitMasterChanges( $fname );
1312 $this->flushMasterSnapshots( $fname );
1313 $this->flushReplicaSnapshots( $fname );
1316 public function finalizeMasterChanges() {
1317 $this->assertTransactionRoundStage( [ self
::ROUND_CURSORY
, self
::ROUND_FINALIZED
] );
1319 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1320 // Loop until callbacks stop adding callbacks on other connections
1323 $count = 0; // callbacks execution attempts
1324 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$count ) {
1325 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1326 // Any error should cause all (peer) transactions to be rolled back together.
1327 $count +
= $conn->runOnTransactionPreCommitCallbacks();
1330 } while ( $count > 0 );
1331 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1332 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1333 $conn->setTrxEndCallbackSuppression( true );
1335 $this->trxRoundStage
= self
::ROUND_FINALIZED
;
1340 public function approveMasterChanges( array $options ) {
1341 $this->assertTransactionRoundStage( self
::ROUND_FINALIZED
);
1343 $limit = $options['maxWriteDuration'] ??
0;
1345 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1346 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1347 // If atomic sections or explicit transactions are still open, some caller must have
1348 // caught an exception but failed to properly rollback any changes. Detect that and
1349 // throw and error (causing rollback).
1350 $conn->assertNoOpenTransactions();
1351 // Assert that the time to replicate the transaction will be sane.
1352 // If this fails, then all DB transactions will be rollback back together.
1353 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1354 if ( $limit > 0 && $time > $limit ) {
1355 throw new DBTransactionSizeError(
1357 "Transaction spent $time second(s) in writes, exceeding the limit of $limit.",
1361 // If a connection sits idle while slow queries execute on another, that connection
1362 // may end up dropped before the commit round is reached. Ping servers to detect this.
1363 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1364 throw new DBTransactionError(
1366 "A connection to the {$conn->getDBname()} database was lost before commit."
1370 $this->trxRoundStage
= self
::ROUND_APPROVED
;
1373 public function beginMasterChanges( $fname = __METHOD__
) {
1374 if ( $this->trxRoundId
!== false ) {
1375 throw new DBTransactionError(
1377 "$fname: Transaction round '{$this->trxRoundId}' already started."
1380 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
1382 // Clear any empty transactions (no writes/callbacks) from the implicit round
1383 $this->flushMasterSnapshots( $fname );
1385 $this->trxRoundId
= $fname;
1386 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1387 // Mark applicable handles as participating in this explicit transaction round.
1388 // For each of these handles, any writes and callbacks will be tied to a single
1389 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1390 // are part of an en masse commit or an en masse rollback.
1391 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1392 $this->applyTransactionRoundFlags( $conn );
1394 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1397 public function commitMasterChanges( $fname = __METHOD__
) {
1398 $this->assertTransactionRoundStage( self
::ROUND_APPROVED
);
1402 /** @noinspection PhpUnusedLocalVariableInspection */
1403 $scope = ScopedCallback
::newScopedIgnoreUserAbort(); // try to ignore client aborts
1405 $restore = ( $this->trxRoundId
!== false );
1406 $this->trxRoundId
= false;
1407 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1408 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1409 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1410 $this->forEachOpenMasterConnection(
1411 function ( IDatabase
$conn ) use ( $fname, &$failures ) {
1413 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1414 } catch ( DBError
$e ) {
1415 ( $this->errorLogger
)( $e );
1416 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1421 throw new DBTransactionError(
1423 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1427 // Unmark handles as participating in this explicit transaction round
1428 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1429 $this->undoTransactionRoundFlags( $conn );
1432 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
1435 public function runMasterTransactionIdleCallbacks() {
1436 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1437 $type = IDatabase
::TRIGGER_COMMIT
;
1438 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1439 $type = IDatabase
::TRIGGER_ROLLBACK
;
1441 throw new DBTransactionError(
1443 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1447 $oldStage = $this->trxRoundStage
;
1448 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1450 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1451 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1452 $conn->setTrxEndCallbackSuppression( false );
1455 $e = null; // first exception
1456 $fname = __METHOD__
;
1457 // Loop until callbacks stop adding callbacks on other connections
1459 // Run any pending callbacks for each connection...
1460 $count = 0; // callback execution attempts
1461 $this->forEachOpenMasterConnection(
1462 function ( Database
$conn ) use ( $type, &$e, &$count ) {
1463 if ( $conn->trxLevel() ) {
1464 return; // retry in the next iteration, after commit() is called
1467 $count +
= $conn->runOnTransactionIdleCallbacks( $type );
1468 } catch ( Exception
$ex ) {
1473 // Clear out any active transactions left over from callbacks...
1474 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$e, $fname ) {
1475 if ( $conn->writesPending() ) {
1476 // A callback from another handle wrote to this one and DBO_TRX is set
1477 $this->queryLogger
->warning( $fname . ": found writes pending." );
1478 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1479 $this->queryLogger
->warning(
1480 $fname . ": found writes pending ($fnames).",
1482 'db_server' => $conn->getServer(),
1483 'db_name' => $conn->getDBname()
1486 } elseif ( $conn->trxLevel() ) {
1487 // A callback from another handle read from this one and DBO_TRX is set,
1488 // which can easily happen if there is only one DB (no replicas)
1489 $this->queryLogger
->debug( $fname . ": found empty transaction." );
1492 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1493 } catch ( Exception
$ex ) {
1497 } while ( $count > 0 );
1499 $this->trxRoundStage
= $oldStage;
1504 public function runMasterTransactionListenerCallbacks() {
1505 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1506 $type = IDatabase
::TRIGGER_COMMIT
;
1507 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1508 $type = IDatabase
::TRIGGER_ROLLBACK
;
1510 throw new DBTransactionError(
1512 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1518 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1519 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1521 $conn->runTransactionListenerCallbacks( $type );
1522 } catch ( Exception
$ex ) {
1526 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1531 public function rollbackMasterChanges( $fname = __METHOD__
) {
1532 $restore = ( $this->trxRoundId
!== false );
1533 $this->trxRoundId
= false;
1534 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1535 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1536 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1539 // Unmark handles as participating in this explicit transaction round
1540 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1541 $this->undoTransactionRoundFlags( $conn );
1544 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
1548 * @param string|string[] $stage
1550 private function assertTransactionRoundStage( $stage ) {
1551 $stages = (array)$stage;
1553 if ( !in_array( $this->trxRoundStage
, $stages, true ) ) {
1554 $stageList = implode(
1556 array_map( function ( $v ) {
1560 throw new DBTransactionError(
1562 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1568 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1570 * Some servers may have neither flag enabled, meaning that they opt out of such
1571 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1572 * when a DB server is used for something like simple key/value storage.
1574 * @param Database $conn
1576 private function applyTransactionRoundFlags( Database
$conn ) {
1577 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1578 return; // transaction rounds do not apply to these connections
1581 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1582 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1583 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1584 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1587 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1588 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1593 * @param Database $conn
1595 private function undoTransactionRoundFlags( Database
$conn ) {
1596 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1597 return; // transaction rounds do not apply to these connections
1600 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1601 $conn->setLBInfo( 'trxRoundId', false );
1604 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1605 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1609 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1610 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) use ( $fname ) {
1611 $conn->flushSnapshot( $fname );
1615 public function flushMasterSnapshots( $fname = __METHOD__
) {
1616 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1617 $conn->flushSnapshot( $fname );
1625 public function getTransactionRoundStage() {
1626 return $this->trxRoundStage
;
1629 public function hasMasterConnection() {
1630 return $this->isOpen( $this->getWriterIndex() );
1633 public function hasMasterChanges() {
1635 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1636 $pending |
= $conn->writesOrCallbacksPending();
1639 return (bool)$pending;
1642 public function lastMasterChangeTimestamp() {
1644 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1645 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1651 public function hasOrMadeRecentMasterChanges( $age = null ) {
1652 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1654 return ( $this->hasMasterChanges()
1655 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1658 public function pendingMasterChangeCallers() {
1660 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1661 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1667 public function getLaggedReplicaMode( $domain = false ) {
1668 // No-op if there is only one DB (also avoids recursion)
1669 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1671 // See if laggedReplicaMode gets set
1672 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1673 $this->reuseConnection( $conn );
1674 } catch ( DBConnectionError
$e ) {
1675 // Avoid expensive re-connect attempts and failures
1676 $this->allReplicasDownMode
= true;
1677 $this->laggedReplicaMode
= true;
1681 return $this->laggedReplicaMode
;
1684 public function laggedReplicaUsed() {
1685 return $this->laggedReplicaMode
;
1691 * @deprecated Since 1.28; use laggedReplicaUsed()
1693 public function laggedSlaveUsed() {
1694 return $this->laggedReplicaUsed();
1697 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1698 if ( $this->readOnlyReason
!== false ) {
1699 return $this->readOnlyReason
;
1700 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1701 if ( $this->allReplicasDownMode
) {
1702 return 'The database has been automatically locked ' .
1703 'until the replica database servers become available';
1705 return 'The database has been automatically locked ' .
1706 'while the replica database servers catch up to the master.';
1708 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1709 return 'The database master is running in read-only mode.';
1716 * @param string $domain Domain ID, or false for the current domain
1717 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1720 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1721 $cache = $this->wanCache
;
1722 $masterServer = $this->getServerName( $this->getWriterIndex() );
1724 return (bool)$cache->getWithSetCallback(
1725 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1726 self
::TTL_CACHE_READONLY
,
1727 function () use ( $domain, $conn ) {
1728 $old = $this->trxProfiler
->setSilenced( true );
1730 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1731 $readOnly = (int)$dbw->serverIsReadOnly();
1733 $this->reuseConnection( $dbw );
1735 } catch ( DBError
$e ) {
1738 $this->trxProfiler
->setSilenced( $old );
1741 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1745 public function allowLagged( $mode = null ) {
1746 if ( $mode === null ) {
1747 return $this->allowLagged
;
1749 $this->allowLagged
= $mode;
1751 return $this->allowLagged
;
1754 public function pingAll() {
1756 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1757 if ( !$conn->ping() ) {
1765 public function forEachOpenConnection( $callback, array $params = [] ) {
1766 foreach ( $this->conns
as $connsByServer ) {
1767 foreach ( $connsByServer as $serverConns ) {
1768 foreach ( $serverConns as $conn ) {
1769 $callback( $conn, ...$params );
1775 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1776 $masterIndex = $this->getWriterIndex();
1777 foreach ( $this->conns
as $connsByServer ) {
1778 if ( isset( $connsByServer[$masterIndex] ) ) {
1779 /** @var IDatabase $conn */
1780 foreach ( $connsByServer[$masterIndex] as $conn ) {
1781 $callback( $conn, ...$params );
1787 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1788 foreach ( $this->conns
as $connsByServer ) {
1789 foreach ( $connsByServer as $i => $serverConns ) {
1790 if ( $i === $this->getWriterIndex() ) {
1791 continue; // skip master
1793 foreach ( $serverConns as $conn ) {
1794 $callback( $conn, ...$params );
1800 public function getMaxLag( $domain = false ) {
1805 if ( $this->getServerCount() <= 1 ) {
1806 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1809 $lagTimes = $this->getLagTimes( $domain );
1810 foreach ( $lagTimes as $i => $lag ) {
1811 if ( $this->loads
[$i] > 0 && $lag > $maxLag ) {
1813 $host = $this->servers
[$i]['host'];
1818 return [ $host, $maxLag, $maxIndex ];
1821 public function getLagTimes( $domain = false ) {
1822 if ( $this->getServerCount() <= 1 ) {
1823 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1826 $knownLagTimes = []; // map of (server index => 0 seconds)
1827 $indexesWithLag = [];
1828 foreach ( $this->servers
as $i => $server ) {
1829 if ( empty( $server['is static'] ) ) {
1830 $indexesWithLag[] = $i; // DB server might have replication lag
1832 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1836 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1839 public function safeGetLag( IDatabase
$conn ) {
1840 if ( $this->getServerCount() <= 1 ) {
1843 return $conn->getLag();
1848 * @param IDatabase $conn
1849 * @param DBMasterPos|bool $pos
1850 * @param int|null $timeout
1853 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
1854 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
1856 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1857 return true; // server is not a replica DB
1861 // Get the current master position, opening a connection if needed
1862 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1863 if ( $masterConn ) {
1864 $pos = $masterConn->getMasterPos();
1866 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1867 $pos = $masterConn->getMasterPos();
1868 $this->closeConnection( $masterConn );
1872 if ( $pos instanceof DBMasterPos
) {
1873 $result = $conn->masterPosWait( $pos, $timeout );
1874 if ( $result == -1 ||
is_null( $result ) ) {
1875 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos}';
1876 $this->replLogger
->warning( $msg, [
1877 'host' => $conn->getServer(),
1879 'trace' => ( new RuntimeException() )->getTraceAsString()
1883 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
1887 $ok = false; // something is misconfigured
1888 $this->replLogger
->error(
1889 __METHOD__
. ': could not get master pos for {host}',
1891 'host' => $conn->getServer(),
1892 'trace' => ( new RuntimeException() )->getTraceAsString()
1900 public function setTransactionListener( $name, callable
$callback = null ) {
1902 $this->trxRecurringCallbacks
[$name] = $callback;
1904 unset( $this->trxRecurringCallbacks
[$name] );
1906 $this->forEachOpenMasterConnection(
1907 function ( IDatabase
$conn ) use ( $name, $callback ) {
1908 $conn->setTransactionListener( $name, $callback );
1913 public function setTableAliases( array $aliases ) {
1914 $this->tableAliases
= $aliases;
1917 public function setIndexAliases( array $aliases ) {
1918 $this->indexAliases
= $aliases;
1921 public function setDomainPrefix( $prefix ) {
1922 // Find connections to explicit foreign domains still marked as in-use...
1924 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
1925 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1926 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1927 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1928 $domainsInUse[] = $conn->getDomainID();
1932 // Do not switch connections to explicit foreign domains unless marked as safe
1933 if ( $domainsInUse ) {
1934 $domains = implode( ', ', $domainsInUse );
1935 throw new DBUnexpectedError( null,
1936 "Foreign domain connections are still in use ($domains)." );
1939 $this->setLocalDomain( new DatabaseDomain(
1940 $this->localDomain
->getDatabase(),
1941 $this->localDomain
->getSchema(),
1945 // Update the prefix for all local connections...
1946 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1947 if ( !$db->getLBInfo( 'foreign' ) ) {
1948 $db->tablePrefix( $prefix );
1954 * @param DatabaseDomain $domain
1956 private function setLocalDomain( DatabaseDomain
$domain ) {
1957 $this->localDomain
= $domain;
1958 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
1959 // always true, gracefully handle the case when they fail to account for escaping.
1960 if ( $this->localDomain
->getTablePrefix() != '' ) {
1961 $this->localDomainIdAlias
=
1962 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
1964 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
1968 function __destruct() {
1969 // Avoid connection leaks for sanity
1975 * @deprecated since 1.29
1977 class_alias( LoadBalancer
::class, 'LoadBalancer' );