3 * Database load balancing manager
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 namespace Wikimedia\Rdbms
;
24 use Psr\Log\LoggerInterface
;
25 use Psr\Log\NullLogger
;
26 use Wikimedia\ScopedCallback
;
31 use UnexpectedValueException
;
32 use InvalidArgumentException
;
37 * Database connection, tracking, load balancing, and transaction manager for a cluster
41 class LoadBalancer
implements ILoadBalancer
{
42 /** @var ILoadMonitor */
44 /** @var callable|null Callback to run before the first connection attempt */
45 private $chronologyCallback;
48 /** @var WANObjectCache */
50 /** @var mixed Class name or object With profileIn/profileOut methods */
52 /** @var TransactionProfiler */
54 /** @var LoggerInterface */
56 /** @var LoggerInterface */
58 /** @var LoggerInterface */
60 /** @var LoggerInterface */
62 /** @var callable Exception logger */
64 /** @var callable Deprecation logger */
65 private $deprecationLogger;
67 /** @var DatabaseDomain Local DB domain ID and default for selectDB() calls */
70 /** @var Database[][][] Map of (connection category => server index => IDatabase[]) */
73 /** @var array[] Map of (server index => server config array) */
75 /** @var float[] Map of (server index => weight) */
76 private $genericLoads;
77 /** @var array[] Map of (group => server index => weight) */
79 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
81 /** @var int Seconds to spend waiting on replica DB lag to resolve */
83 /** @var array The LoadMonitor configuration */
84 private $loadMonitorConfig;
85 /** @var string Alternate local DB domain instead of DatabaseDomain::getId() */
86 private $localDomainIdAlias;
90 /** @var string Current server name */
92 /** @var bool Whether this PHP instance is for a CLI script */
94 /** @var string Agent name for query profiling */
97 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
98 private $tableAliases = [];
99 /** @var string[] Map of (index alias => index) */
100 private $indexAliases = [];
101 /** @var array[] Map of (name => callable) */
102 private $trxRecurringCallbacks = [];
104 /** @var Database DB connection object that caused a problem */
105 private $errorConnection;
106 /** @var int The generic (not query grouped) replica DB index */
107 private $genericReadIndex = -1;
108 /** @var 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 int|null An integer ID of the managing LBFactory instance or null */
127 /** @var string|bool String if a requested DBO_TRX transaction round is active */
128 private $trxRoundId = false;
129 /** @var string Stage of the current transaction round in the transaction round life-cycle */
130 private $trxRoundStage = self
::ROUND_CURSORY
;
132 /** @var string|null */
133 private $defaultGroup = null;
135 /** @var int Warn when this many connection are held */
136 const CONN_HELD_WARN_THRESHOLD
= 10;
138 /** @var int Default 'maxLag' when unspecified */
139 const MAX_LAG_DEFAULT
= 6;
140 /** @var int Default 'waitTimeout' when unspecified */
141 const MAX_WAIT_DEFAULT
= 10;
142 /** @var int Seconds to cache master server read-only status */
143 const TTL_CACHE_READONLY
= 5;
145 const KEY_LOCAL
= 'local';
146 const KEY_FOREIGN_FREE
= 'foreignFree';
147 const KEY_FOREIGN_INUSE
= 'foreignInUse';
149 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
150 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
151 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
153 /** @var string Transaction round, explicit or implicit, has not finished writing */
154 const ROUND_CURSORY
= 'cursory';
155 /** @var string Transaction round writes are complete and ready for pre-commit checks */
156 const ROUND_FINALIZED
= 'finalized';
157 /** @var string Transaction round passed final pre-commit checks */
158 const ROUND_APPROVED
= 'approved';
159 /** @var string Transaction round was committed and post-commit callbacks must be run */
160 const ROUND_COMMIT_CALLBACKS
= 'commit-callbacks';
161 /** @var string Transaction round was rolled back and post-rollback callbacks must be run */
162 const ROUND_ROLLBACK_CALLBACKS
= 'rollback-callbacks';
163 /** @var string Transaction round encountered an error */
164 const ROUND_ERROR
= 'error';
166 public function __construct( array $params ) {
167 if ( !isset( $params['servers'] ) ) {
168 throw new InvalidArgumentException( __CLASS__
. ': missing "servers" parameter' );
170 $this->servers
= $params['servers'];
171 foreach ( $this->servers
as $i => $server ) {
173 $this->servers
[$i]['master'] = true;
175 $this->servers
[$i]['replica'] = true;
179 $localDomain = isset( $params['localDomain'] )
180 ? DatabaseDomain
::newFromId( $params['localDomain'] )
181 : DatabaseDomain
::newUnspecified();
182 $this->setLocalDomain( $localDomain );
184 $this->waitTimeout
= $params['waitTimeout'] ?? self
::MAX_WAIT_DEFAULT
;
187 // Connection were transaction rounds may be applied
188 self
::KEY_LOCAL
=> [],
189 self
::KEY_FOREIGN_INUSE
=> [],
190 self
::KEY_FOREIGN_FREE
=> [],
191 // Auto-committing counterpart connections that ignore transaction rounds
192 self
::KEY_LOCAL_NOROUND
=> [],
193 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
194 self
::KEY_FOREIGN_FREE_NOROUND
=> []
196 $this->genericLoads
= [];
197 $this->waitForPos
= false;
198 $this->allowLagged
= false;
200 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
201 $this->readOnlyReason
= $params['readOnlyReason'];
204 $this->maxLag
= $params['maxLag'] ?? self
::MAX_LAG_DEFAULT
;
206 $this->loadMonitorConfig
= $params['loadMonitor'] ??
[ 'class' => 'LoadMonitorNull' ];
207 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
209 foreach ( $params['servers'] as $i => $server ) {
210 $this->genericLoads
[$i] = $server['load'];
211 if ( isset( $server['groupLoads'] ) ) {
212 foreach ( $server['groupLoads'] as $group => $ratio ) {
213 if ( !isset( $this->groupLoads
[$group] ) ) {
214 $this->groupLoads
[$group] = [];
216 $this->groupLoads
[$group][$i] = $ratio;
221 $this->srvCache
= $params['srvCache'] ??
new EmptyBagOStuff();
222 $this->wanCache
= $params['wanCache'] ?? WANObjectCache
::newEmpty();
223 $this->profiler
= $params['profiler'] ??
null;
224 $this->trxProfiler
= $params['trxProfiler'] ??
new TransactionProfiler();
226 $this->errorLogger
= $params['errorLogger'] ??
function ( Exception
$e ) {
227 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
229 $this->deprecationLogger
= $params['deprecationLogger'] ??
function ( $msg ) {
230 trigger_error( $msg, E_USER_DEPRECATED
);
233 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
234 $this->$key = $params[$key] ??
new NullLogger();
237 $this->hostname
= $params['hostname'] ??
( gethostname() ?
: 'unknown' );
238 $this->cliMode
= $params['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
239 $this->agent
= $params['agent'] ??
'';
241 if ( isset( $params['chronologyCallback'] ) ) {
242 $this->chronologyCallback
= $params['chronologyCallback'];
245 if ( isset( $params['roundStage'] ) ) {
246 if ( $params['roundStage'] === self
::STAGE_POSTCOMMIT_CALLBACKS
) {
247 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
248 } elseif ( $params['roundStage'] === self
::STAGE_POSTROLLBACK_CALLBACKS
) {
249 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
253 $this->defaultGroup
= $params['defaultGroup'] ??
null;
254 $this->ownerId
= $params['ownerId'] ??
null;
257 public function getLocalDomainID() {
258 return $this->localDomain
->getId();
261 public function resolveDomainID( $domain ) {
262 if ( $domain === $this->localDomainIdAlias ||
$domain === false ) {
263 // Local connection requested via some backwards-compatibility domain alias
264 return $this->getLocalDomainID();
267 return (string)$domain;
271 * Get a LoadMonitor instance
273 * @return ILoadMonitor
275 private function getLoadMonitor() {
276 if ( !isset( $this->loadMonitor
) ) {
278 'LoadMonitor' => LoadMonitor
::class,
279 'LoadMonitorNull' => LoadMonitorNull
::class,
280 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
283 $class = $this->loadMonitorConfig
['class'];
284 if ( isset( $compat[$class] ) ) {
285 $class = $compat[$class];
288 $this->loadMonitor
= new $class(
289 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
290 $this->loadMonitor
->setLogger( $this->replLogger
);
293 return $this->loadMonitor
;
297 * @param array $loads
298 * @param bool|string $domain Domain to get non-lagged for
299 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
300 * @return bool|int|string
302 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
303 $lags = $this->getLagTimes( $domain );
305 # Unset excessively lagged servers
306 foreach ( $lags as $i => $lag ) {
308 # How much lag this server nominally is allowed to have
309 $maxServerLag = $this->servers
[$i]['max lag'] ??
$this->maxLag
; // default
310 # Constrain that futher by $maxLag argument
311 $maxServerLag = min( $maxServerLag, $maxLag );
313 $host = $this->getServerName( $i );
314 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
315 $this->replLogger
->debug(
317 ": server {host} is not replicating?", [ 'host' => $host ] );
319 } elseif ( $lag > $maxServerLag ) {
320 $this->replLogger
->debug(
322 ": server {host} has {lag} seconds of lag (>= {maxlag})",
323 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
330 # Find out if all the replica DBs with non-zero load are lagged
332 foreach ( $loads as $load ) {
336 # No appropriate DB servers except maybe the master and some replica DBs with zero load
337 # Do NOT use the master
338 # Instead, this function will return false, triggering read-only mode,
339 # and a lagged replica DB will be used instead.
343 if ( count( $loads ) == 0 ) {
347 # Return a random representative of the remainder
348 return ArrayUtils
::pickRandom( $loads );
353 * @param array $groups
354 * @param string|bool $domain
357 private function getConnectionIndex( $i, $groups, $domain ) {
358 // Check one "group" per default: the generic pool
359 $defaultGroups = $this->defaultGroup ?
[ $this->defaultGroup
] : [ false ];
361 $groups = ( $groups === false ||
$groups === [] )
365 if ( $i == self
::DB_MASTER
) {
366 $i = $this->getWriterIndex();
367 } elseif ( $i == self
::DB_REPLICA
) {
368 # Try to find an available server in any the query groups (in order)
369 foreach ( $groups as $group ) {
370 $groupIndex = $this->getReaderIndex( $group, $domain );
371 if ( $groupIndex !== false ) {
378 # Operation-based index
379 if ( $i == self
::DB_REPLICA
) {
380 $this->lastError
= 'Unknown error'; // reset error string
381 # Try the general server pool if $groups are unavailable.
382 $i = ( $groups === [ false ] )
383 ?
false // don't bother with this if that is what was tried above
384 : $this->getReaderIndex( false, $domain );
385 # Couldn't find a working server in getReaderIndex()?
386 if ( $i === false ) {
387 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
388 // Throw an exception
389 $this->reportConnectionError();
390 return null; // not reached
397 public function getReaderIndex( $group = false, $domain = false ) {
398 if ( count( $this->servers
) == 1 ) {
399 // Skip the load balancing if there's only one server
400 return $this->getWriterIndex();
401 } elseif ( $group === false && $this->genericReadIndex
>= 0 ) {
402 // A generic reader index was already selected and "waitForPos" was handled
403 return $this->genericReadIndex
;
406 if ( $group !== false ) {
407 // Use the server weight array for this load group
408 if ( isset( $this->groupLoads
[$group] ) ) {
409 $loads = $this->groupLoads
[$group];
411 // No loads for this group, return false and the caller can use some other group
412 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
417 // Use the generic load group
418 $loads = $this->genericLoads
;
421 // Scale the configured load ratios according to each server's load and state
422 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
424 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
425 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
426 if ( $i === false ) {
427 // DB connection unsuccessful
431 // If data seen by queries is expected to reflect the transactions committed as of
432 // or after a given replication position then wait for the DB to apply those changes
433 if ( $this->waitForPos
&& $i != $this->getWriterIndex() && !$this->doWait( $i ) ) {
434 // Data will be outdated compared to what was expected
435 $laggedReplicaMode = true;
438 if ( $this->genericReadIndex
< 0 && $this->genericLoads
[$i] > 0 && $group === false ) {
439 // Cache the generic (ungrouped) reader index for future DB_REPLICA handles
440 $this->genericReadIndex
= $i;
441 // Record if the generic reader index is in "lagged replica DB" mode
442 $this->laggedReplicaMode
= ( $laggedReplicaMode ||
$this->laggedReplicaMode
);
445 $serverName = $this->getServerName( $i );
446 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
452 * @param array $loads List of server weights
453 * @param string|bool $domain
454 * @return array (reader index, lagged replica mode) or false on failure
456 private function pickReaderIndex( array $loads, $domain = false ) {
457 if ( $loads === [] ) {
458 throw new InvalidArgumentException( "Server configuration array is empty" );
461 /** @var int|bool $i Index of selected server */
463 /** @var bool $laggedReplicaMode Whether server is considered lagged */
464 $laggedReplicaMode = false;
466 // Quickly look through the available servers for a server that meets criteria...
467 $currentLoads = $loads;
468 while ( count( $currentLoads ) ) {
469 if ( $this->allowLagged ||
$laggedReplicaMode ) {
470 $i = ArrayUtils
::pickRandom( $currentLoads );
473 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
474 // "chronologyCallback" sets "waitForPos" for session consistency.
475 // This triggers doWait() after connect, so it's especially good to
476 // avoid lagged servers so as to avoid excessive delay in that method.
477 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
478 // Aim for <= 1 second of waiting (being too picky can backfire)
479 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
481 if ( $i === false ) {
482 // Any server with less lag than it's 'max lag' param is preferable
483 $i = $this->getRandomNonLagged( $currentLoads, $domain );
485 if ( $i === false && count( $currentLoads ) != 0 ) {
486 // All replica DBs lagged. Switch to read-only mode
487 $this->replLogger
->error(
488 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
489 $i = ArrayUtils
::pickRandom( $currentLoads );
490 $laggedReplicaMode = true;
494 if ( $i === false ) {
495 // pickRandom() returned false.
496 // This is permanent and means the configuration or the load monitor
497 // wants us to return false.
498 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
500 return [ false, false ];
503 $serverName = $this->getServerName( $i );
504 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
506 $conn = $this->openConnection( $i, $domain );
508 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
509 unset( $currentLoads[$i] ); // avoid this server next iteration
514 // Decrement reference counter, we are finished with this connection.
515 // It will be incremented for the caller later.
516 if ( $domain !== false ) {
517 $this->reuseConnection( $conn );
520 // Return this server
524 // If all servers were down, quit now
525 if ( $currentLoads === [] ) {
526 $this->connLogger
->error( __METHOD__
. ": all servers down" );
529 return [ $i, $laggedReplicaMode ];
532 public function waitFor( $pos ) {
533 $oldPos = $this->waitForPos
;
535 $this->waitForPos
= $pos;
536 // If a generic reader connection was already established, then wait now
537 if ( $this->genericReadIndex
> 0 && !$this->doWait( $this->genericReadIndex
) ) {
538 $this->laggedReplicaMode
= true;
540 // Otherwise, wait until a connection is established in getReaderIndex()
542 // Restore the older position if it was higher since this is used for lag-protection
543 $this->setWaitForPositionIfHigher( $oldPos );
547 public function waitForOne( $pos, $timeout = null ) {
548 $oldPos = $this->waitForPos
;
550 $this->waitForPos
= $pos;
552 $i = $this->genericReadIndex
;
554 // Pick a generic replica DB if there isn't one yet
555 $readLoads = $this->genericLoads
;
556 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
557 $readLoads = array_filter( $readLoads ); // with non-zero load
558 $i = ArrayUtils
::pickRandom( $readLoads );
562 $ok = $this->doWait( $i, true, $timeout );
564 $ok = true; // no applicable loads
567 # Restore the old position, as this is not used for lag-protection but for throttling
568 $this->waitForPos
= $oldPos;
574 public function waitForAll( $pos, $timeout = null ) {
575 $timeout = $timeout ?
: $this->waitTimeout
;
577 $oldPos = $this->waitForPos
;
579 $this->waitForPos
= $pos;
580 $serverCount = count( $this->servers
);
583 for ( $i = 1; $i < $serverCount; $i++
) {
584 if ( $this->genericLoads
[$i] > 0 ) {
585 $start = microtime( true );
586 $ok = $this->doWait( $i, true, $timeout ) && $ok;
587 $timeout -= intval( microtime( true ) - $start );
588 if ( $timeout <= 0 ) {
589 break; // timeout reached
594 # Restore the old position, as this is not used for lag-protection but for throttling
595 $this->waitForPos
= $oldPos;
602 * @param DBMasterPos|bool $pos
604 private function setWaitForPositionIfHigher( $pos ) {
609 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
610 $this->waitForPos
= $pos;
614 public function getAnyOpenConnection( $i, $flags = 0 ) {
615 $i = ( $i === self
::DB_MASTER
) ?
$this->getWriterIndex() : $i;
616 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
618 foreach ( $this->conns
as $connsByServer ) {
619 if ( $i === self
::DB_REPLICA
) {
620 $indexes = array_keys( $connsByServer );
622 $indexes = isset( $connsByServer[$i] ) ?
[ $i ] : [];
625 foreach ( $indexes as $index ) {
626 foreach ( $connsByServer[$index] as $conn ) {
627 if ( !$conn->isOpen() ) {
628 continue; // some sort of error occured?
630 if ( !$autocommit ||
$conn->getLBInfo( 'autoCommitOnly' ) ) {
641 * Wait for a given replica DB to catch up to the master pos stored in $this
642 * @param int $index Server index
643 * @param bool $open Check the server even if a new connection has to be made
644 * @param int|null $timeout Max seconds to wait; default is "waitTimeout" given to __construct()
647 protected function doWait( $index, $open = false, $timeout = null ) {
648 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
650 // Check if we already know that the DB has reached this point
651 $server = $this->getServerName( $index );
652 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
653 /** @var DBMasterPos $knownReachedPos */
654 $knownReachedPos = $this->srvCache
->get( $key );
656 $knownReachedPos instanceof DBMasterPos
&&
657 $knownReachedPos->hasReached( $this->waitForPos
)
659 $this->replLogger
->debug(
661 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
662 [ 'dbserver' => $server ]
667 // Find a connection to wait on, creating one if needed and allowed
668 $close = false; // close the connection afterwards
669 $conn = $this->getAnyOpenConnection( $index );
672 $this->replLogger
->debug(
673 __METHOD__
. ': no connection open for {dbserver}',
674 [ 'dbserver' => $server ]
679 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
681 $this->replLogger
->warning(
682 __METHOD__
. ': failed to connect to {dbserver}',
683 [ 'dbserver' => $server ]
688 // Avoid connection spam in waitForAll() when connections
689 // are made just for the sake of doing this lag check.
694 $this->replLogger
->info(
696 ': waiting for replica DB {dbserver} to catch up...',
697 [ 'dbserver' => $server ]
700 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
702 if ( $result === null ) {
703 $this->replLogger
->warning(
704 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
707 'pos' => $this->waitForPos
,
708 'trace' => ( new RuntimeException() )->getTraceAsString()
712 } elseif ( $result == -1 ) {
713 $this->replLogger
->warning(
714 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
717 'pos' => $this->waitForPos
,
718 'trace' => ( new RuntimeException() )->getTraceAsString()
723 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
725 // Remember that the DB reached this point
726 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
730 $this->closeConnection( $conn );
736 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
737 if ( $i === null ||
$i === false ) {
738 throw new InvalidArgumentException( "Cannot connect without a server index" );
741 $domain = $this->resolveDomainID( $domain );
742 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
744 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) === self
::CONN_TRX_AUTOCOMMIT
) {
745 // Assuming all servers are of the same type (or similar), which is overwhelmingly
746 // the case, use the master server information to get the attributes. The information
747 // for $i cannot be used since it might be DB_REPLICA, which might require connection
748 // attempts in order to be resolved into a real server index.
749 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
750 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
751 // Callers sometimes want to (a) escape REPEATABLE-READ stateness without locking
752 // rows (e.g. FOR UPDATE) or (b) make small commits during a larger transactions
753 // to reduce lock contention. None of these apply for sqlite and using separate
754 // connections just causes self-deadlocks.
755 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
756 $this->connLogger
->info( __METHOD__
.
757 ': ignoring CONN_TRX_AUTOCOMMIT to avoid deadlocks.' );
761 // Number of connections made before getting the server index and handle
762 $priorConnectionsMade = $this->connsOpened
;
763 // Decide which server to use (might trigger new connections)
764 $serverIndex = $this->getConnectionIndex( $i, $groups, $domain );
765 // Get an open connection to that server (might trigger a new connection)
766 $conn = $this->openConnection( $serverIndex, $domain, $flags );
768 $this->reportConnectionError();
769 return null; // unreachable due to exception
772 // Profile any new connections caused by this method
773 if ( $this->connsOpened
> $priorConnectionsMade ) {
774 $host = $conn->getServer();
775 $dbname = $conn->getDBname();
776 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
779 if ( $serverIndex == $this->getWriterIndex() ) {
780 // If the load balancer is read-only, perhaps due to replication lag, then master
781 // DB handles will reflect that. Note that Database::assertIsWritableMaster() takes
782 // care of replica DB handles whereas getReadOnlyReason() would cause infinite loops.
783 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
789 public function reuseConnection( IDatabase
$conn ) {
790 $serverIndex = $conn->getLBInfo( 'serverIndex' );
791 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
792 if ( $serverIndex === null ||
$refCount === null ) {
794 * This can happen in code like:
795 * foreach ( $dbs as $db ) {
796 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
798 * $lb->reuseConnection( $conn );
800 * When a connection to the local DB is opened in this way, reuseConnection()
804 } elseif ( $conn instanceof DBConnRef
) {
805 // DBConnRef already handles calling reuseConnection() and only passes the live
806 // Database instance to this method. Any caller passing in a DBConnRef is broken.
807 $this->connLogger
->error(
808 __METHOD__
. ": got DBConnRef instance.\n" .
809 ( new RuntimeException() )->getTraceAsString() );
814 if ( $this->disabled
) {
815 return; // DBConnRef handle probably survived longer than the LoadBalancer
818 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
819 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
820 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
822 $connFreeKey = self
::KEY_FOREIGN_FREE
;
823 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
826 $domain = $conn->getDomainID();
827 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
828 throw new InvalidArgumentException(
829 "Connection $serverIndex/$domain not found; it may have already been freed" );
830 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
831 throw new InvalidArgumentException(
832 "Connection $serverIndex/$domain mismatched; it may have already been freed" );
835 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
836 if ( $refCount <= 0 ) {
837 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
838 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
839 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
840 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
842 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
844 $this->connLogger
->debug( __METHOD__
.
845 ": reference count for $serverIndex/$domain reduced to $refCount" );
849 public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
850 $domain = $this->resolveDomainID( $domain );
851 $role = $this->getRoleFromIndex( $i );
853 return new DBConnRef( $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
856 public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
857 $domain = $this->resolveDomainID( $domain );
858 $role = $this->getRoleFromIndex( $i );
860 return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role );
863 public function getMaintenanceConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
864 $domain = $this->resolveDomainID( $domain );
865 $role = $this->getRoleFromIndex( $i );
867 return new MaintainableDBConnRef(
868 $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
872 * @param int $i Server index or DB_MASTER/DB_REPLICA
873 * @return int One of DB_MASTER/DB_REPLICA
875 private function getRoleFromIndex( $i ) {
876 return ( $i === self
::DB_MASTER ||
$i === $this->getWriterIndex() )
881 public function openConnection( $i, $domain = false, $flags = 0 ) {
882 $domain = $this->resolveDomainID( $domain );
884 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
885 // Load any "waitFor" positions before connecting so that doWait() is triggered
886 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
887 $this->connectionAttempted
= true;
888 ( $this->chronologyCallback
)( $this );
891 $conn = $this->localDomain
->equals( $domain )
892 ?
$this->openLocalConnection( $i, $flags )
893 : $this->openForeignConnection( $i, $domain, $flags );
895 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
896 // Connection was made but later unrecoverably lost for some reason.
897 // Do not return a handle that will just throw exceptions on use,
898 // but let the calling code (e.g. getReaderIndex) try another server.
899 $this->errorConnection
= $conn;
904 $conn instanceof IDatabase
&&
905 ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
)
907 if ( $conn->trxLevel() ) { // sanity
908 throw new DBUnexpectedError(
910 'Handle requested with CONN_TRX_AUTOCOMMIT yet it has a transaction'
914 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
921 * Open a connection to a local DB, or return one if it is already open.
923 * On error, returns false, and the connection which caused the
924 * error will be available via $this->errorConnection.
926 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
928 * @param int $i Server index
929 * @param int $flags Class CONN_* constant bitfield
932 private function openLocalConnection( $i, $flags = 0 ) {
933 // Connection handles required to be in auto-commit mode use a separate connection
934 // pool since the main pool is effected by implicit and explicit transaction rounds
935 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
937 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
938 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
939 $conn = $this->conns
[$connKey][$i][0];
941 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
942 throw new InvalidArgumentException( "No server with index '$i'" );
944 // Open a new connection
945 $server = $this->servers
[$i];
946 $server['serverIndex'] = $i;
947 $server['autoCommitOnly'] = $autoCommit;
948 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
949 $host = $this->getServerName( $i );
950 if ( $conn->isOpen() ) {
951 $this->connLogger
->debug(
952 __METHOD__
. ": connected to database $i at '$host'." );
953 $this->conns
[$connKey][$i][0] = $conn;
955 $this->connLogger
->warning(
956 __METHOD__
. ": failed to connect to database $i at '$host'." );
957 $this->errorConnection
= $conn;
962 // Final sanity check to make sure the right domain is selected
964 $conn instanceof IDatabase
&&
965 !$this->localDomain
->isCompatible( $conn->getDomainID() )
967 throw new UnexpectedValueException(
968 "Got connection to '{$conn->getDomainID()}', " .
969 "but expected local domain ('{$this->localDomain}')" );
976 * Open a connection to a foreign DB, or return one if it is already open.
978 * Increments a reference count on the returned connection which locks the
979 * connection to the requested domain. This reference count can be
980 * decremented by calling reuseConnection().
982 * If a connection is open to the appropriate server already, but with the wrong
983 * database, it will be switched to the right database and returned, as long as
984 * it has been freed first with reuseConnection().
986 * On error, returns false, and the connection which caused the
987 * error will be available via $this->errorConnection.
989 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
991 * @param int $i Server index
992 * @param string $domain Domain ID to open
993 * @param int $flags Class CONN_* constant bitfield
994 * @return Database|bool Returns false on connection error
995 * @throws DBError When database selection fails
997 private function openForeignConnection( $i, $domain, $flags = 0 ) {
998 $domainInstance = DatabaseDomain
::newFromId( $domain );
999 // Connection handles required to be in auto-commit mode use a separate connection
1000 // pool since the main pool is effected by implicit and explicit transaction rounds
1001 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
1003 if ( $autoCommit ) {
1004 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
1005 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
1007 $connFreeKey = self
::KEY_FOREIGN_FREE
;
1008 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
1011 /** @var Database $conn */
1014 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
1015 // Reuse an in-use connection for the same domain
1016 $conn = $this->conns
[$connInUseKey][$i][$domain];
1017 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
1018 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
1019 // Reuse a free connection for the same domain
1020 $conn = $this->conns
[$connFreeKey][$i][$domain];
1021 unset( $this->conns
[$connFreeKey][$i][$domain] );
1022 $this->conns
[$connInUseKey][$i][$domain] = $conn;
1023 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
1024 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
1025 // Reuse a free connection from another domain if possible
1026 foreach ( $this->conns
[$connFreeKey][$i] as $oldDomain => $conn ) {
1027 if ( $domainInstance->getDatabase() !== null ) {
1028 // Check if changing the database will require a new connection.
1029 // In that case, leave the connection handle alone and keep looking.
1030 // This prevents connections from being closed mid-transaction and can
1031 // also avoid overhead if the same database will later be requested.
1033 $conn->databasesAreIndependent() &&
1034 $conn->getDBname() !== $domainInstance->getDatabase()
1038 // Select the new database, schema, and prefix
1039 $conn->selectDomain( $domainInstance );
1041 // Stay on the current database, but update the schema/prefix
1042 $conn->dbSchema( $domainInstance->getSchema() );
1043 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1045 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
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__
.
1049 ": reusing free connection from $oldDomain for $domain" );
1055 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
1056 throw new InvalidArgumentException( "No server with index '$i'" );
1058 // Open a new connection
1059 $server = $this->servers
[$i];
1060 $server['serverIndex'] = $i;
1061 $server['foreignPoolRefCount'] = 0;
1062 $server['foreign'] = true;
1063 $server['autoCommitOnly'] = $autoCommit;
1064 $conn = $this->reallyOpenConnection( $server, $domainInstance );
1065 if ( !$conn->isOpen() ) {
1066 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
1067 $this->errorConnection
= $conn;
1070 // Note that if $domain is an empty string, getDomainID() might not match it
1071 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1072 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1076 if ( $conn instanceof IDatabase
) {
1077 // Final sanity check to make sure the right domain is selected
1078 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1079 throw new UnexpectedValueException(
1080 "Got connection to '{$conn->getDomainID()}', but expected '$domain'" );
1082 // Increment reference count
1083 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1084 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1090 public function getServerAttributes( $i ) {
1091 return Database
::attributesFromType(
1092 $this->getServerType( $i ),
1093 $this->servers
[$i]['driver'] ??
null
1098 * Test if the specified index represents an open connection
1100 * @param int $index Server index
1104 private function isOpen( $index ) {
1105 if ( !is_int( $index ) ) {
1109 return (bool)$this->getAnyOpenConnection( $index );
1113 * Open a new network connection to a server (uncached)
1115 * Returns a Database object whether or not the connection was successful.
1117 * @param array $server
1118 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
1120 * @throws DBAccessError
1121 * @throws InvalidArgumentException
1123 protected function reallyOpenConnection( array $server, DatabaseDomain
$domain ) {
1124 if ( $this->disabled
) {
1125 throw new DBAccessError();
1128 if ( $domain->getDatabase() === null ) {
1129 // The database domain does not specify a DB name and some database systems require a
1130 // valid DB specified on connection. The $server configuration array contains a default
1131 // DB name to use for connections in such cases.
1132 if ( $server['type'] === 'mysql' ) {
1133 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1134 // and the DB name in $server might not exist due to legacy reasons (the default
1135 // domain used to ignore the local LB domain, even when mismatched).
1136 $server['dbname'] = null;
1139 $server['dbname'] = $domain->getDatabase();
1142 if ( $domain->getSchema() !== null ) {
1143 $server['schema'] = $domain->getSchema();
1146 // It is always possible to connect with any prefix, even the empty string
1147 $server['tablePrefix'] = $domain->getTablePrefix();
1149 // Let the handle know what the cluster master is (e.g. "db1052")
1150 $masterName = $this->getServerName( $this->getWriterIndex() );
1151 $server['clusterMasterHost'] = $masterName;
1153 // Log when many connection are made on requests
1154 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
1155 $this->perfLogger
->warning( __METHOD__
. ": " .
1156 "{$this->connsOpened}+ connections made (master=$masterName)" );
1159 $server['srvCache'] = $this->srvCache
;
1160 // Set loggers and profilers
1161 $server['connLogger'] = $this->connLogger
;
1162 $server['queryLogger'] = $this->queryLogger
;
1163 $server['errorLogger'] = $this->errorLogger
;
1164 $server['deprecationLogger'] = $this->deprecationLogger
;
1165 $server['profiler'] = $this->profiler
;
1166 $server['trxProfiler'] = $this->trxProfiler
;
1167 // Use the same agent and PHP mode for all DB handles
1168 $server['cliMode'] = $this->cliMode
;
1169 $server['agent'] = $this->agent
;
1170 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1171 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1172 $server['flags'] = $server['flags'] ?? IDatabase
::DBO_DEFAULT
;
1174 // Create a live connection object
1176 $db = Database
::factory( $server['type'], $server );
1177 } catch ( DBConnectionError
$e ) {
1178 // FIXME: This is probably the ugliest thing I have ever done to
1179 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1183 $db->setLBInfo( $server );
1184 $db->setLazyMasterHandle(
1185 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1187 $db->setTableAliases( $this->tableAliases
);
1188 $db->setIndexAliases( $this->indexAliases
);
1190 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1191 if ( $this->trxRoundId
!== false ) {
1192 $this->applyTransactionRoundFlags( $db );
1194 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1195 $db->setTransactionListener( $name, $callback );
1203 * @throws DBConnectionError
1205 private function reportConnectionError() {
1206 $conn = $this->errorConnection
; // the connection which caused the error
1208 'method' => __METHOD__
,
1209 'last_error' => $this->lastError
,
1212 if ( $conn instanceof IDatabase
) {
1213 $context['db_server'] = $conn->getServer();
1214 $this->connLogger
->warning(
1215 __METHOD__
. ": connection error: {last_error} ({db_server})",
1219 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1221 // No last connection, probably due to all servers being too busy
1222 $this->connLogger
->error(
1224 ": LB failure with no last connection. Connection error: {last_error}",
1228 // If all servers were busy, "lastError" will contain something sensible
1229 throw new DBConnectionError( null, $this->lastError
);
1233 public function getWriterIndex() {
1237 public function haveIndex( $i ) {
1238 return array_key_exists( $i, $this->servers
);
1241 public function isNonZeroLoad( $i ) {
1242 return array_key_exists( $i, $this->servers
) && $this->genericLoads
[$i] != 0;
1245 public function getServerCount() {
1246 return count( $this->servers
);
1249 public function getServerName( $i ) {
1250 $name = $this->servers
[$i]['hostName'] ??
$this->servers
[$i]['host'] ??
'';
1252 return ( $name != '' ) ?
$name : 'localhost';
1255 public function getServerInfo( $i ) {
1256 return $this->servers
[$i] ??
false;
1259 public function getServerType( $i ) {
1260 return $this->servers
[$i]['type'] ??
'unknown';
1263 public function getMasterPos() {
1264 # If this entire request was served from a replica DB without opening a connection to the
1265 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1266 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1267 if ( !$masterConn ) {
1268 $serverCount = count( $this->servers
);
1269 for ( $i = 1; $i < $serverCount; $i++
) {
1270 $conn = $this->getAnyOpenConnection( $i );
1272 return $conn->getReplicaPos();
1276 return $masterConn->getMasterPos();
1282 public function disable() {
1284 $this->disabled
= true;
1287 public function closeAll() {
1288 $fname = __METHOD__
;
1289 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( $fname ) {
1290 $host = $conn->getServer();
1291 $this->connLogger
->debug(
1292 $fname . ": closing connection to database '$host'." );
1297 self
::KEY_LOCAL
=> [],
1298 self
::KEY_FOREIGN_INUSE
=> [],
1299 self
::KEY_FOREIGN_FREE
=> [],
1300 self
::KEY_LOCAL_NOROUND
=> [],
1301 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1302 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1304 $this->connsOpened
= 0;
1307 public function closeConnection( IDatabase
$conn ) {
1308 if ( $conn instanceof DBConnRef
) {
1309 // Avoid calling close() but still leaving the handle in the pool
1310 throw new RuntimeException( 'Cannot close DBConnRef instance; it must be shareable' );
1313 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1314 foreach ( $this->conns
as $type => $connsByServer ) {
1315 if ( !isset( $connsByServer[$serverIndex] ) ) {
1319 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1320 if ( $conn === $trackedConn ) {
1321 $host = $this->getServerName( $i );
1322 $this->connLogger
->debug(
1323 __METHOD__
. ": closing connection to database $i at '$host'." );
1324 unset( $this->conns
[$type][$serverIndex][$i] );
1325 --$this->connsOpened
;
1334 public function commitAll( $fname = __METHOD__
, $owner = null ) {
1335 $this->commitMasterChanges( $fname, $owner );
1336 $this->flushMasterSnapshots( $fname );
1337 $this->flushReplicaSnapshots( $fname );
1340 public function finalizeMasterChanges( $fname = __METHOD__
, $owner = null ) {
1341 $this->assertOwnership( $fname, $owner );
1342 $this->assertTransactionRoundStage( [ self
::ROUND_CURSORY
, self
::ROUND_FINALIZED
] );
1344 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1345 // Loop until callbacks stop adding callbacks on other connections
1348 $count = 0; // callbacks execution attempts
1349 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$count ) {
1350 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1351 // Any error should cause all (peer) transactions to be rolled back together.
1352 $count +
= $conn->runOnTransactionPreCommitCallbacks();
1355 } while ( $count > 0 );
1356 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1357 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1358 $conn->setTrxEndCallbackSuppression( true );
1360 $this->trxRoundStage
= self
::ROUND_FINALIZED
;
1365 public function approveMasterChanges( array $options, $fname = __METHOD__
, $owner = null ) {
1366 $this->assertOwnership( $fname, $owner );
1367 $this->assertTransactionRoundStage( self
::ROUND_FINALIZED
);
1369 $limit = $options['maxWriteDuration'] ??
0;
1371 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1372 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1373 // If atomic sections or explicit transactions are still open, some caller must have
1374 // caught an exception but failed to properly rollback any changes. Detect that and
1375 // throw and error (causing rollback).
1376 $conn->assertNoOpenTransactions();
1377 // Assert that the time to replicate the transaction will be sane.
1378 // If this fails, then all DB transactions will be rollback back together.
1379 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1380 if ( $limit > 0 && $time > $limit ) {
1381 throw new DBTransactionSizeError(
1383 "Transaction spent $time second(s) in writes, exceeding the limit of $limit",
1387 // If a connection sits idle while slow queries execute on another, that connection
1388 // may end up dropped before the commit round is reached. Ping servers to detect this.
1389 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1390 throw new DBTransactionError(
1392 "A connection to the {$conn->getDBname()} database was lost before commit"
1396 $this->trxRoundStage
= self
::ROUND_APPROVED
;
1399 public function beginMasterChanges( $fname = __METHOD__
, $owner = null ) {
1400 $this->assertOwnership( $fname, $owner );
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__
, $owner = null ) {
1425 $this->assertOwnership( $fname, $owner );
1426 $this->assertTransactionRoundStage( self
::ROUND_APPROVED
);
1430 /** @noinspection PhpUnusedLocalVariableInspection */
1431 $scope = ScopedCallback
::newScopedIgnoreUserAbort(); // try to ignore client aborts
1433 $restore = ( $this->trxRoundId
!== false );
1434 $this->trxRoundId
= false;
1435 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1436 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1437 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1438 $this->forEachOpenMasterConnection(
1439 function ( IDatabase
$conn ) use ( $fname, &$failures ) {
1441 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1442 } catch ( DBError
$e ) {
1443 ( $this->errorLogger
)( $e );
1444 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1449 throw new DBTransactionError(
1451 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1455 // Unmark handles as participating in this explicit transaction round
1456 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1457 $this->undoTransactionRoundFlags( $conn );
1460 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
1463 public function runMasterTransactionIdleCallbacks( $fname = __METHOD__
, $owner = null ) {
1464 $this->assertOwnership( $fname, $owner );
1465 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1466 $type = IDatabase
::TRIGGER_COMMIT
;
1467 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1468 $type = IDatabase
::TRIGGER_ROLLBACK
;
1470 throw new DBTransactionError(
1472 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1476 $oldStage = $this->trxRoundStage
;
1477 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1479 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1480 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1481 $conn->setTrxEndCallbackSuppression( false );
1484 $e = null; // first exception
1485 $fname = __METHOD__
;
1486 // Loop until callbacks stop adding callbacks on other connections
1488 // Run any pending callbacks for each connection...
1489 $count = 0; // callback execution attempts
1490 $this->forEachOpenMasterConnection(
1491 function ( Database
$conn ) use ( $type, &$e, &$count ) {
1492 if ( $conn->trxLevel() ) {
1493 return; // retry in the next iteration, after commit() is called
1496 $count +
= $conn->runOnTransactionIdleCallbacks( $type );
1497 } catch ( Exception
$ex ) {
1502 // Clear out any active transactions left over from callbacks...
1503 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$e, $fname ) {
1504 if ( $conn->writesPending() ) {
1505 // A callback from another handle wrote to this one and DBO_TRX is set
1506 $this->queryLogger
->warning( $fname . ": found writes pending." );
1507 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1508 $this->queryLogger
->warning(
1509 $fname . ": found writes pending ($fnames).",
1511 'db_server' => $conn->getServer(),
1512 'db_name' => $conn->getDBname()
1515 } elseif ( $conn->trxLevel() ) {
1516 // A callback from another handle read from this one and DBO_TRX is set,
1517 // which can easily happen if there is only one DB (no replicas)
1518 $this->queryLogger
->debug( $fname . ": found empty transaction." );
1521 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1522 } catch ( Exception
$ex ) {
1526 } while ( $count > 0 );
1528 $this->trxRoundStage
= $oldStage;
1533 public function runMasterTransactionListenerCallbacks( $fname = __METHOD__
, $owner = null ) {
1534 $this->assertOwnership( $fname, $owner );
1535 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1536 $type = IDatabase
::TRIGGER_COMMIT
;
1537 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1538 $type = IDatabase
::TRIGGER_ROLLBACK
;
1540 throw new DBTransactionError(
1542 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1548 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1549 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1551 $conn->runTransactionListenerCallbacks( $type );
1552 } catch ( Exception
$ex ) {
1556 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1561 public function rollbackMasterChanges( $fname = __METHOD__
, $owner = null ) {
1562 $this->assertOwnership( $fname, $owner );
1564 $restore = ( $this->trxRoundId
!== false );
1565 $this->trxRoundId
= false;
1566 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1567 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1568 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1571 // Unmark handles as participating in this explicit transaction round
1572 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1573 $this->undoTransactionRoundFlags( $conn );
1576 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
1580 * @param string|string[] $stage
1581 * @throws DBTransactionError
1583 private function assertTransactionRoundStage( $stage ) {
1584 $stages = (array)$stage;
1586 if ( !in_array( $this->trxRoundStage
, $stages, true ) ) {
1587 $stageList = implode(
1589 array_map( function ( $v ) {
1593 throw new DBTransactionError(
1595 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1601 * @param string $fname
1602 * @param int|null $owner Owner ID of the caller
1603 * @throws DBTransactionError
1605 private function assertOwnership( $fname, $owner ) {
1606 if ( $this->ownerId
!== null && $owner !== $this->ownerId
) {
1607 throw new DBTransactionError(
1609 "$fname: LoadBalancer is owned by LBFactory #{$this->ownerId} (got '$owner')."
1615 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1617 * Some servers may have neither flag enabled, meaning that they opt out of such
1618 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1619 * when a DB server is used for something like simple key/value storage.
1621 * @param Database $conn
1623 private function applyTransactionRoundFlags( Database
$conn ) {
1624 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1625 return; // transaction rounds do not apply to these connections
1628 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1629 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1630 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1631 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1634 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1635 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1640 * @param Database $conn
1642 private function undoTransactionRoundFlags( Database
$conn ) {
1643 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1644 return; // transaction rounds do not apply to these connections
1647 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1648 $conn->setLBInfo( 'trxRoundId', false );
1651 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1652 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1656 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1657 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) use ( $fname ) {
1658 $conn->flushSnapshot( $fname );
1662 public function flushMasterSnapshots( $fname = __METHOD__
) {
1663 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1664 $conn->flushSnapshot( $fname );
1672 public function getTransactionRoundStage() {
1673 return $this->trxRoundStage
;
1676 public function hasMasterConnection() {
1677 return $this->isOpen( $this->getWriterIndex() );
1680 public function hasMasterChanges() {
1682 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1683 $pending |
= $conn->writesOrCallbacksPending();
1686 return (bool)$pending;
1689 public function lastMasterChangeTimestamp() {
1691 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1692 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1698 public function hasOrMadeRecentMasterChanges( $age = null ) {
1699 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1701 return ( $this->hasMasterChanges()
1702 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1705 public function pendingMasterChangeCallers() {
1707 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1708 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1714 public function getLaggedReplicaMode( $domain = false ) {
1716 // Avoid recursion if there is only one DB
1717 $this->getServerCount() > 1 &&
1718 // Avoid recursion if the (non-zero load) master DB was picked for generic reads
1719 $this->genericReadIndex
!== $this->getWriterIndex() &&
1720 // Stay in lagged replica mode during the load balancer instance lifetime
1721 !$this->laggedReplicaMode
1724 // Calling this method will set "laggedReplicaMode" as needed
1725 $this->getReaderIndex( false, $domain );
1726 } catch ( DBConnectionError
$e ) {
1727 // Avoid expensive re-connect attempts and failures
1728 $this->allReplicasDownMode
= true;
1729 $this->laggedReplicaMode
= true;
1733 return $this->laggedReplicaMode
;
1736 public function laggedReplicaUsed() {
1737 return $this->laggedReplicaMode
;
1743 * @deprecated Since 1.28; use laggedReplicaUsed()
1745 public function laggedSlaveUsed() {
1746 return $this->laggedReplicaUsed();
1749 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1750 if ( $this->readOnlyReason
!== false ) {
1751 return $this->readOnlyReason
;
1752 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1753 if ( $this->allReplicasDownMode
) {
1754 return 'The database has been automatically locked ' .
1755 'until the replica database servers become available';
1757 return 'The database has been automatically locked ' .
1758 'while the replica database servers catch up to the master.';
1760 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1761 return 'The database master is running in read-only mode.';
1768 * @param string $domain Domain ID, or false for the current domain
1769 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1772 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1773 $cache = $this->wanCache
;
1774 $masterServer = $this->getServerName( $this->getWriterIndex() );
1776 return (bool)$cache->getWithSetCallback(
1777 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1778 self
::TTL_CACHE_READONLY
,
1779 function () use ( $domain, $conn ) {
1780 $old = $this->trxProfiler
->setSilenced( true );
1782 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1783 $readOnly = (int)$dbw->serverIsReadOnly();
1785 $this->reuseConnection( $dbw );
1787 } catch ( DBError
$e ) {
1790 $this->trxProfiler
->setSilenced( $old );
1793 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1797 public function allowLagged( $mode = null ) {
1798 if ( $mode === null ) {
1799 return $this->allowLagged
;
1801 $this->allowLagged
= $mode;
1803 return $this->allowLagged
;
1806 public function pingAll() {
1808 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1809 if ( !$conn->ping() ) {
1817 public function forEachOpenConnection( $callback, array $params = [] ) {
1818 foreach ( $this->conns
as $connsByServer ) {
1819 foreach ( $connsByServer as $serverConns ) {
1820 foreach ( $serverConns as $conn ) {
1821 $callback( $conn, ...$params );
1827 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1828 $masterIndex = $this->getWriterIndex();
1829 foreach ( $this->conns
as $connsByServer ) {
1830 if ( isset( $connsByServer[$masterIndex] ) ) {
1831 /** @var IDatabase $conn */
1832 foreach ( $connsByServer[$masterIndex] as $conn ) {
1833 $callback( $conn, ...$params );
1839 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1840 foreach ( $this->conns
as $connsByServer ) {
1841 foreach ( $connsByServer as $i => $serverConns ) {
1842 if ( $i === $this->getWriterIndex() ) {
1843 continue; // skip master
1845 foreach ( $serverConns as $conn ) {
1846 $callback( $conn, ...$params );
1852 public function getMaxLag( $domain = false ) {
1857 if ( $this->getServerCount() <= 1 ) {
1858 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1861 $lagTimes = $this->getLagTimes( $domain );
1862 foreach ( $lagTimes as $i => $lag ) {
1863 if ( $this->genericLoads
[$i] > 0 && $lag > $maxLag ) {
1865 $host = $this->servers
[$i]['host'];
1870 return [ $host, $maxLag, $maxIndex ];
1873 public function getLagTimes( $domain = false ) {
1874 if ( $this->getServerCount() <= 1 ) {
1875 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1878 $knownLagTimes = []; // map of (server index => 0 seconds)
1879 $indexesWithLag = [];
1880 foreach ( $this->servers
as $i => $server ) {
1881 if ( empty( $server['is static'] ) ) {
1882 $indexesWithLag[] = $i; // DB server might have replication lag
1884 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1888 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1891 public function safeGetLag( IDatabase
$conn ) {
1892 if ( $this->getServerCount() <= 1 ) {
1895 return $conn->getLag();
1899 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
1900 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
1902 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1903 return true; // server is not a replica DB
1907 // Get the current master position, opening a connection if needed
1908 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1909 if ( $masterConn ) {
1910 $pos = $masterConn->getMasterPos();
1912 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1913 if ( !$masterConn ) {
1914 throw new DBReplicationWaitError(
1916 "Could not obtain a master database connection to get the position"
1919 $pos = $masterConn->getMasterPos();
1920 $this->closeConnection( $masterConn );
1924 if ( $pos instanceof DBMasterPos
) {
1925 $result = $conn->masterPosWait( $pos, $timeout );
1926 if ( $result == -1 ||
is_null( $result ) ) {
1927 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos}';
1928 $this->replLogger
->warning( $msg, [
1929 'host' => $conn->getServer(),
1931 'trace' => ( new RuntimeException() )->getTraceAsString()
1935 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
1939 $ok = false; // something is misconfigured
1940 $this->replLogger
->error(
1941 __METHOD__
. ': could not get master pos for {host}',
1943 'host' => $conn->getServer(),
1944 'trace' => ( new RuntimeException() )->getTraceAsString()
1952 public function setTransactionListener( $name, callable
$callback = null ) {
1954 $this->trxRecurringCallbacks
[$name] = $callback;
1956 unset( $this->trxRecurringCallbacks
[$name] );
1958 $this->forEachOpenMasterConnection(
1959 function ( IDatabase
$conn ) use ( $name, $callback ) {
1960 $conn->setTransactionListener( $name, $callback );
1965 public function setTableAliases( array $aliases ) {
1966 $this->tableAliases
= $aliases;
1969 public function setIndexAliases( array $aliases ) {
1970 $this->indexAliases
= $aliases;
1974 * @param string $prefix
1975 * @deprecated Since 1.33
1977 public function setDomainPrefix( $prefix ) {
1978 $this->setLocalDomainPrefix( $prefix );
1981 public function setLocalDomainPrefix( $prefix ) {
1982 // Find connections to explicit foreign domains still marked as in-use...
1984 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
1985 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1986 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1987 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1988 $domainsInUse[] = $conn->getDomainID();
1992 // Do not switch connections to explicit foreign domains unless marked as safe
1993 if ( $domainsInUse ) {
1994 $domains = implode( ', ', $domainsInUse );
1995 throw new DBUnexpectedError( null,
1996 "Foreign domain connections are still in use ($domains)" );
1999 $this->setLocalDomain( new DatabaseDomain(
2000 $this->localDomain
->getDatabase(),
2001 $this->localDomain
->getSchema(),
2005 // Update the prefix for all local connections...
2006 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
2007 if ( !$db->getLBInfo( 'foreign' ) ) {
2008 $db->tablePrefix( $prefix );
2013 public function redefineLocalDomain( $domain ) {
2016 $this->setLocalDomain( DatabaseDomain
::newFromId( $domain ) );
2020 * @param DatabaseDomain $domain
2022 private function setLocalDomain( DatabaseDomain
$domain ) {
2023 $this->localDomain
= $domain;
2024 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
2025 // always true, gracefully handle the case when they fail to account for escaping.
2026 if ( $this->localDomain
->getTablePrefix() != '' ) {
2027 $this->localDomainIdAlias
=
2028 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
2030 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
2034 function __destruct() {
2035 // Avoid connection leaks for sanity
2041 * @deprecated since 1.29
2043 class_alias( LoadBalancer
::class, 'LoadBalancer' );