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 string|bool String if a requested DBO_TRX transaction round is active */
126 private $trxRoundId = false;
127 /** @var string Stage of the current transaction round in the transaction round life-cycle */
128 private $trxRoundStage = self
::ROUND_CURSORY
;
130 /** @var string|null */
131 private $defaultGroup = null;
133 /** @var int Warn when this many connection are held */
134 const CONN_HELD_WARN_THRESHOLD
= 10;
136 /** @var int Default 'maxLag' when unspecified */
137 const MAX_LAG_DEFAULT
= 6;
138 /** @var int Default 'waitTimeout' when unspecified */
139 const MAX_WAIT_DEFAULT
= 10;
140 /** @var int Seconds to cache master server read-only status */
141 const TTL_CACHE_READONLY
= 5;
143 const KEY_LOCAL
= 'local';
144 const KEY_FOREIGN_FREE
= 'foreignFree';
145 const KEY_FOREIGN_INUSE
= 'foreignInUse';
147 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
148 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
149 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
151 /** @var string Transaction round, explicit or implicit, has not finished writing */
152 const ROUND_CURSORY
= 'cursory';
153 /** @var string Transaction round writes are complete and ready for pre-commit checks */
154 const ROUND_FINALIZED
= 'finalized';
155 /** @var string Transaction round passed final pre-commit checks */
156 const ROUND_APPROVED
= 'approved';
157 /** @var string Transaction round was committed and post-commit callbacks must be run */
158 const ROUND_COMMIT_CALLBACKS
= 'commit-callbacks';
159 /** @var string Transaction round was rolled back and post-rollback callbacks must be run */
160 const ROUND_ROLLBACK_CALLBACKS
= 'rollback-callbacks';
161 /** @var string Transaction round encountered an error */
162 const ROUND_ERROR
= 'error';
164 public function __construct( array $params ) {
165 if ( !isset( $params['servers'] ) ) {
166 throw new InvalidArgumentException( __CLASS__
. ': missing "servers" parameter' );
168 $this->servers
= $params['servers'];
169 foreach ( $this->servers
as $i => $server ) {
171 $this->servers
[$i]['master'] = true;
173 $this->servers
[$i]['replica'] = true;
177 $localDomain = isset( $params['localDomain'] )
178 ? DatabaseDomain
::newFromId( $params['localDomain'] )
179 : DatabaseDomain
::newUnspecified();
180 $this->setLocalDomain( $localDomain );
182 $this->waitTimeout
= $params['waitTimeout'] ?? self
::MAX_WAIT_DEFAULT
;
185 // Connection were transaction rounds may be applied
186 self
::KEY_LOCAL
=> [],
187 self
::KEY_FOREIGN_INUSE
=> [],
188 self
::KEY_FOREIGN_FREE
=> [],
189 // Auto-committing counterpart connections that ignore transaction rounds
190 self
::KEY_LOCAL_NOROUND
=> [],
191 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
192 self
::KEY_FOREIGN_FREE_NOROUND
=> []
194 $this->genericLoads
= [];
195 $this->waitForPos
= false;
196 $this->allowLagged
= false;
198 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
199 $this->readOnlyReason
= $params['readOnlyReason'];
202 $this->maxLag
= $params['maxLag'] ?? self
::MAX_LAG_DEFAULT
;
204 $this->loadMonitorConfig
= $params['loadMonitor'] ??
[ 'class' => 'LoadMonitorNull' ];
205 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
207 foreach ( $params['servers'] as $i => $server ) {
208 $this->genericLoads
[$i] = $server['load'];
209 if ( isset( $server['groupLoads'] ) ) {
210 foreach ( $server['groupLoads'] as $group => $ratio ) {
211 if ( !isset( $this->groupLoads
[$group] ) ) {
212 $this->groupLoads
[$group] = [];
214 $this->groupLoads
[$group][$i] = $ratio;
219 $this->srvCache
= $params['srvCache'] ??
new EmptyBagOStuff();
220 $this->wanCache
= $params['wanCache'] ?? WANObjectCache
::newEmpty();
221 $this->profiler
= $params['profiler'] ??
null;
222 $this->trxProfiler
= $params['trxProfiler'] ??
new TransactionProfiler();
224 $this->errorLogger
= $params['errorLogger'] ??
function ( Exception
$e ) {
225 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
227 $this->deprecationLogger
= $params['deprecationLogger'] ??
function ( $msg ) {
228 trigger_error( $msg, E_USER_DEPRECATED
);
231 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
232 $this->$key = $params[$key] ??
new NullLogger();
235 $this->hostname
= $params['hostname'] ??
( gethostname() ?
: 'unknown' );
236 $this->cliMode
= $params['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
237 $this->agent
= $params['agent'] ??
'';
239 if ( isset( $params['chronologyCallback'] ) ) {
240 $this->chronologyCallback
= $params['chronologyCallback'];
243 if ( isset( $params['roundStage'] ) ) {
244 if ( $params['roundStage'] === self
::STAGE_POSTCOMMIT_CALLBACKS
) {
245 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
246 } elseif ( $params['roundStage'] === self
::STAGE_POSTROLLBACK_CALLBACKS
) {
247 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
251 $this->defaultGroup
= $params['defaultGroup'] ??
null;
254 public function getLocalDomainID() {
255 return $this->localDomain
->getId();
258 public function resolveDomainID( $domain ) {
259 if ( $domain === $this->localDomainIdAlias ||
$domain === false ) {
260 // Local connection requested via some backwards-compatibility domain alias
261 return $this->getLocalDomainID();
264 return (string)$domain;
268 * Get a LoadMonitor instance
270 * @return ILoadMonitor
272 private function getLoadMonitor() {
273 if ( !isset( $this->loadMonitor
) ) {
275 'LoadMonitor' => LoadMonitor
::class,
276 'LoadMonitorNull' => LoadMonitorNull
::class,
277 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
280 $class = $this->loadMonitorConfig
['class'];
281 if ( isset( $compat[$class] ) ) {
282 $class = $compat[$class];
285 $this->loadMonitor
= new $class(
286 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
287 $this->loadMonitor
->setLogger( $this->replLogger
);
290 return $this->loadMonitor
;
294 * @param array $loads
295 * @param bool|string $domain Domain to get non-lagged for
296 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
297 * @return bool|int|string
299 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
300 $lags = $this->getLagTimes( $domain );
302 # Unset excessively lagged servers
303 foreach ( $lags as $i => $lag ) {
305 # How much lag this server nominally is allowed to have
306 $maxServerLag = $this->servers
[$i]['max lag'] ??
$this->maxLag
; // default
307 # Constrain that futher by $maxLag argument
308 $maxServerLag = min( $maxServerLag, $maxLag );
310 $host = $this->getServerName( $i );
311 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
312 $this->replLogger
->debug(
314 ": server {host} is not replicating?", [ 'host' => $host ] );
316 } elseif ( $lag > $maxServerLag ) {
317 $this->replLogger
->debug(
319 ": server {host} has {lag} seconds of lag (>= {maxlag})",
320 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
327 # Find out if all the replica DBs with non-zero load are lagged
329 foreach ( $loads as $load ) {
333 # No appropriate DB servers except maybe the master and some replica DBs with zero load
334 # Do NOT use the master
335 # Instead, this function will return false, triggering read-only mode,
336 # and a lagged replica DB will be used instead.
340 if ( count( $loads ) == 0 ) {
344 # Return a random representative of the remainder
345 return ArrayUtils
::pickRandom( $loads );
350 * @param array $groups
351 * @param string|bool $domain
354 private function getConnectionIndex( $i, $groups, $domain ) {
355 // Check one "group" per default: the generic pool
356 $defaultGroups = $this->defaultGroup ?
[ $this->defaultGroup
] : [ false ];
358 $groups = ( $groups === false ||
$groups === [] )
362 if ( $i == self
::DB_MASTER
) {
363 $i = $this->getWriterIndex();
364 } elseif ( $i == self
::DB_REPLICA
) {
365 # Try to find an available server in any the query groups (in order)
366 foreach ( $groups as $group ) {
367 $groupIndex = $this->getReaderIndex( $group, $domain );
368 if ( $groupIndex !== false ) {
375 # Operation-based index
376 if ( $i == self
::DB_REPLICA
) {
377 $this->lastError
= 'Unknown error'; // reset error string
378 # Try the general server pool if $groups are unavailable.
379 $i = ( $groups === [ false ] )
380 ?
false // don't bother with this if that is what was tried above
381 : $this->getReaderIndex( false, $domain );
382 # Couldn't find a working server in getReaderIndex()?
383 if ( $i === false ) {
384 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
385 // Throw an exception
386 $this->reportConnectionError();
387 return null; // not reached
394 public function getReaderIndex( $group = false, $domain = false ) {
395 if ( count( $this->servers
) == 1 ) {
396 // Skip the load balancing if there's only one server
397 return $this->getWriterIndex();
398 } elseif ( $group === false && $this->genericReadIndex
>= 0 ) {
399 // A generic reader index was already selected and "waitForPos" was handled
400 return $this->genericReadIndex
;
403 if ( $group !== false ) {
404 // Use the server weight array for this load group
405 if ( isset( $this->groupLoads
[$group] ) ) {
406 $loads = $this->groupLoads
[$group];
408 // No loads for this group, return false and the caller can use some other group
409 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
414 // Use the generic load group
415 $loads = $this->genericLoads
;
418 // Scale the configured load ratios according to each server's load and state
419 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
421 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
422 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
423 if ( $i === false ) {
424 // DB connection unsuccessful
428 // If data seen by queries is expected to reflect the transactions committed as of
429 // or after a given replication position then wait for the DB to apply those changes
430 if ( $this->waitForPos
&& $i != $this->getWriterIndex() && !$this->doWait( $i ) ) {
431 // Data will be outdated compared to what was expected
432 $laggedReplicaMode = true;
435 if ( $this->genericReadIndex
< 0 && $this->genericLoads
[$i] > 0 && $group === false ) {
436 // Cache the generic (ungrouped) reader index for future DB_REPLICA handles
437 $this->genericReadIndex
= $i;
438 // Record if the generic reader index is in "lagged replica DB" mode
439 $this->laggedReplicaMode
= ( $laggedReplicaMode ||
$this->laggedReplicaMode
);
442 $serverName = $this->getServerName( $i );
443 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
449 * @param array $loads List of server weights
450 * @param string|bool $domain
451 * @return array (reader index, lagged replica mode) or false on failure
453 private function pickReaderIndex( array $loads, $domain = false ) {
454 if ( $loads === [] ) {
455 throw new InvalidArgumentException( "Server configuration array is empty" );
458 /** @var int|bool $i Index of selected server */
460 /** @var bool $laggedReplicaMode Whether server is considered lagged */
461 $laggedReplicaMode = false;
463 // Quickly look through the available servers for a server that meets criteria...
464 $currentLoads = $loads;
465 while ( count( $currentLoads ) ) {
466 if ( $this->allowLagged ||
$laggedReplicaMode ) {
467 $i = ArrayUtils
::pickRandom( $currentLoads );
470 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
471 // "chronologyCallback" sets "waitForPos" for session consistency.
472 // This triggers doWait() after connect, so it's especially good to
473 // avoid lagged servers so as to avoid excessive delay in that method.
474 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
475 // Aim for <= 1 second of waiting (being too picky can backfire)
476 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
478 if ( $i === false ) {
479 // Any server with less lag than it's 'max lag' param is preferable
480 $i = $this->getRandomNonLagged( $currentLoads, $domain );
482 if ( $i === false && count( $currentLoads ) != 0 ) {
483 // All replica DBs lagged. Switch to read-only mode
484 $this->replLogger
->error(
485 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
486 $i = ArrayUtils
::pickRandom( $currentLoads );
487 $laggedReplicaMode = true;
491 if ( $i === false ) {
492 // pickRandom() returned false.
493 // This is permanent and means the configuration or the load monitor
494 // wants us to return false.
495 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
497 return [ false, false ];
500 $serverName = $this->getServerName( $i );
501 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
503 $conn = $this->openConnection( $i, $domain );
505 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
506 unset( $currentLoads[$i] ); // avoid this server next iteration
511 // Decrement reference counter, we are finished with this connection.
512 // It will be incremented for the caller later.
513 if ( $domain !== false ) {
514 $this->reuseConnection( $conn );
517 // Return this server
521 // If all servers were down, quit now
522 if ( $currentLoads === [] ) {
523 $this->connLogger
->error( __METHOD__
. ": all servers down" );
526 return [ $i, $laggedReplicaMode ];
529 public function waitFor( $pos ) {
530 $oldPos = $this->waitForPos
;
532 $this->waitForPos
= $pos;
533 // If a generic reader connection was already established, then wait now
534 if ( $this->genericReadIndex
> 0 && !$this->doWait( $this->genericReadIndex
) ) {
535 $this->laggedReplicaMode
= true;
537 // Otherwise, wait until a connection is established in getReaderIndex()
539 // Restore the older position if it was higher since this is used for lag-protection
540 $this->setWaitForPositionIfHigher( $oldPos );
544 public function waitForOne( $pos, $timeout = null ) {
545 $oldPos = $this->waitForPos
;
547 $this->waitForPos
= $pos;
549 $i = $this->genericReadIndex
;
551 // Pick a generic replica DB if there isn't one yet
552 $readLoads = $this->genericLoads
;
553 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
554 $readLoads = array_filter( $readLoads ); // with non-zero load
555 $i = ArrayUtils
::pickRandom( $readLoads );
559 $ok = $this->doWait( $i, true, $timeout );
561 $ok = true; // no applicable loads
564 # Restore the old position, as this is not used for lag-protection but for throttling
565 $this->waitForPos
= $oldPos;
571 public function waitForAll( $pos, $timeout = null ) {
572 $timeout = $timeout ?
: $this->waitTimeout
;
574 $oldPos = $this->waitForPos
;
576 $this->waitForPos
= $pos;
577 $serverCount = count( $this->servers
);
580 for ( $i = 1; $i < $serverCount; $i++
) {
581 if ( $this->genericLoads
[$i] > 0 ) {
582 $start = microtime( true );
583 $ok = $this->doWait( $i, true, $timeout ) && $ok;
584 $timeout -= intval( microtime( true ) - $start );
585 if ( $timeout <= 0 ) {
586 break; // timeout reached
591 # Restore the old position, as this is not used for lag-protection but for throttling
592 $this->waitForPos
= $oldPos;
599 * @param DBMasterPos|bool $pos
601 private function setWaitForPositionIfHigher( $pos ) {
606 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
607 $this->waitForPos
= $pos;
611 public function getAnyOpenConnection( $i, $flags = 0 ) {
612 $i = ( $i === self
::DB_MASTER
) ?
$this->getWriterIndex() : $i;
613 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
615 foreach ( $this->conns
as $connsByServer ) {
616 if ( $i === self
::DB_REPLICA
) {
617 $indexes = array_keys( $connsByServer );
619 $indexes = isset( $connsByServer[$i] ) ?
[ $i ] : [];
622 foreach ( $indexes as $index ) {
623 foreach ( $connsByServer[$index] as $conn ) {
624 if ( !$conn->isOpen() ) {
625 continue; // some sort of error occured?
627 if ( !$autocommit ||
$conn->getLBInfo( 'autoCommitOnly' ) ) {
638 * Wait for a given replica DB to catch up to the master pos stored in $this
639 * @param int $index Server index
640 * @param bool $open Check the server even if a new connection has to be made
641 * @param int|null $timeout Max seconds to wait; default is "waitTimeout" given to __construct()
644 protected function doWait( $index, $open = false, $timeout = null ) {
645 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
647 // Check if we already know that the DB has reached this point
648 $server = $this->getServerName( $index );
649 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
650 /** @var DBMasterPos $knownReachedPos */
651 $knownReachedPos = $this->srvCache
->get( $key );
653 $knownReachedPos instanceof DBMasterPos
&&
654 $knownReachedPos->hasReached( $this->waitForPos
)
656 $this->replLogger
->debug(
658 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
659 [ 'dbserver' => $server ]
664 // Find a connection to wait on, creating one if needed and allowed
665 $close = false; // close the connection afterwards
666 $conn = $this->getAnyOpenConnection( $index );
669 $this->replLogger
->debug(
670 __METHOD__
. ': no connection open for {dbserver}',
671 [ 'dbserver' => $server ]
676 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
678 $this->replLogger
->warning(
679 __METHOD__
. ': failed to connect to {dbserver}',
680 [ 'dbserver' => $server ]
685 // Avoid connection spam in waitForAll() when connections
686 // are made just for the sake of doing this lag check.
691 $this->replLogger
->info(
693 ': waiting for replica DB {dbserver} to catch up...',
694 [ 'dbserver' => $server ]
697 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
699 if ( $result === null ) {
700 $this->replLogger
->warning(
701 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
704 'pos' => $this->waitForPos
,
705 'trace' => ( new RuntimeException() )->getTraceAsString()
709 } elseif ( $result == -1 ) {
710 $this->replLogger
->warning(
711 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
714 'pos' => $this->waitForPos
,
715 'trace' => ( new RuntimeException() )->getTraceAsString()
720 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
722 // Remember that the DB reached this point
723 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
727 $this->closeConnection( $conn );
733 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
734 if ( $i === null ||
$i === false ) {
735 throw new InvalidArgumentException( "Cannot connect without a server index" );
738 $domain = $this->resolveDomainID( $domain );
739 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
741 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) === self
::CONN_TRX_AUTOCOMMIT
) {
742 // Assuming all servers are of the same type (or similar), which is overwhelmingly
743 // the case, use the master server information to get the attributes. The information
744 // for $i cannot be used since it might be DB_REPLICA, which might require connection
745 // attempts in order to be resolved into a real server index.
746 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
747 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
748 // Callers sometimes want to (a) escape REPEATABLE-READ stateness without locking
749 // rows (e.g. FOR UPDATE) or (b) make small commits during a larger transactions
750 // to reduce lock contention. None of these apply for sqlite and using separate
751 // connections just causes self-deadlocks.
752 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
753 $this->connLogger
->info( __METHOD__
.
754 ': ignoring CONN_TRX_AUTOCOMMIT to avoid deadlocks.' );
758 // Number of connections made before getting the server index and handle
759 $priorConnectionsMade = $this->connsOpened
;
760 // Decide which server to use (might trigger new connections)
761 $serverIndex = $this->getConnectionIndex( $i, $groups, $domain );
762 // Get an open connection to that server (might trigger a new connection)
763 $conn = $this->openConnection( $serverIndex, $domain, $flags );
765 $this->reportConnectionError();
766 return null; // unreachable due to exception
769 // Profile any new connections caused by this method
770 if ( $this->connsOpened
> $priorConnectionsMade ) {
771 $host = $conn->getServer();
772 $dbname = $conn->getDBname();
773 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
776 if ( $serverIndex == $this->getWriterIndex() ) {
777 // If the load balancer is read-only, perhaps due to replication lag, then master
778 // DB handles will reflect that. Note that Database::assertIsWritableMaster() takes
779 // care of replica DB handles whereas getReadOnlyReason() would cause infinite loops.
780 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
786 public function reuseConnection( IDatabase
$conn ) {
787 $serverIndex = $conn->getLBInfo( 'serverIndex' );
788 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
789 if ( $serverIndex === null ||
$refCount === null ) {
791 * This can happen in code like:
792 * foreach ( $dbs as $db ) {
793 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
795 * $lb->reuseConnection( $conn );
797 * When a connection to the local DB is opened in this way, reuseConnection()
801 } elseif ( $conn instanceof DBConnRef
) {
802 // DBConnRef already handles calling reuseConnection() and only passes the live
803 // Database instance to this method. Any caller passing in a DBConnRef is broken.
804 $this->connLogger
->error(
805 __METHOD__
. ": got DBConnRef instance.\n" .
806 ( new RuntimeException() )->getTraceAsString() );
811 if ( $this->disabled
) {
812 return; // DBConnRef handle probably survived longer than the LoadBalancer
815 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
816 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
817 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
819 $connFreeKey = self
::KEY_FOREIGN_FREE
;
820 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
823 $domain = $conn->getDomainID();
824 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
825 throw new InvalidArgumentException(
826 "Connection $serverIndex/$domain not found; it may have already been freed" );
827 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
828 throw new InvalidArgumentException(
829 "Connection $serverIndex/$domain mismatched; it may have already been freed" );
832 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
833 if ( $refCount <= 0 ) {
834 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
835 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
836 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
837 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
839 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
841 $this->connLogger
->debug( __METHOD__
.
842 ": reference count for $serverIndex/$domain reduced to $refCount" );
846 public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
847 $domain = $this->resolveDomainID( $domain );
848 $role = $this->getRoleFromIndex( $i );
850 return new DBConnRef( $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
853 public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
854 $domain = $this->resolveDomainID( $domain );
855 $role = $this->getRoleFromIndex( $i );
857 return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role );
860 public function getMaintenanceConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
861 $domain = $this->resolveDomainID( $domain );
862 $role = $this->getRoleFromIndex( $i );
864 return new MaintainableDBConnRef(
865 $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
869 * @param int $i Server index or DB_MASTER/DB_REPLICA
870 * @return int One of DB_MASTER/DB_REPLICA
872 private function getRoleFromIndex( $i ) {
873 return ( $i === self
::DB_MASTER ||
$i === $this->getWriterIndex() )
878 public function openConnection( $i, $domain = false, $flags = 0 ) {
879 $domain = $this->resolveDomainID( $domain );
881 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
882 // Load any "waitFor" positions before connecting so that doWait() is triggered
883 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
884 $this->connectionAttempted
= true;
885 ( $this->chronologyCallback
)( $this );
888 $conn = $this->localDomain
->equals( $domain )
889 ?
$this->openLocalConnection( $i, $flags )
890 : $this->openForeignConnection( $i, $domain, $flags );
892 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
893 // Connection was made but later unrecoverably lost for some reason.
894 // Do not return a handle that will just throw exceptions on use,
895 // but let the calling code (e.g. getReaderIndex) try another server.
896 $this->errorConnection
= $conn;
901 $conn instanceof IDatabase
&&
902 ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
)
904 if ( $conn->trxLevel() ) { // sanity
905 throw new DBUnexpectedError(
907 'Handle requested with CONN_TRX_AUTOCOMMIT yet it has a transaction'
911 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
918 * Open a connection to a local DB, or return one if it is already open.
920 * On error, returns false, and the connection which caused the
921 * error will be available via $this->errorConnection.
923 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
925 * @param int $i Server index
926 * @param int $flags Class CONN_* constant bitfield
929 private function openLocalConnection( $i, $flags = 0 ) {
930 // Connection handles required to be in auto-commit mode use a separate connection
931 // pool since the main pool is effected by implicit and explicit transaction rounds
932 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
934 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
935 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
936 $conn = $this->conns
[$connKey][$i][0];
938 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
939 throw new InvalidArgumentException( "No server with index '$i'" );
941 // Open a new connection
942 $server = $this->servers
[$i];
943 $server['serverIndex'] = $i;
944 $server['autoCommitOnly'] = $autoCommit;
945 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
946 $host = $this->getServerName( $i );
947 if ( $conn->isOpen() ) {
948 $this->connLogger
->debug(
949 __METHOD__
. ": connected to database $i at '$host'." );
950 $this->conns
[$connKey][$i][0] = $conn;
952 $this->connLogger
->warning(
953 __METHOD__
. ": failed to connect to database $i at '$host'." );
954 $this->errorConnection
= $conn;
959 // Final sanity check to make sure the right domain is selected
961 $conn instanceof IDatabase
&&
962 !$this->localDomain
->isCompatible( $conn->getDomainID() )
964 throw new UnexpectedValueException(
965 "Got connection to '{$conn->getDomainID()}', " .
966 "but expected local domain ('{$this->localDomain}')" );
973 * Open a connection to a foreign DB, or return one if it is already open.
975 * Increments a reference count on the returned connection which locks the
976 * connection to the requested domain. This reference count can be
977 * decremented by calling reuseConnection().
979 * If a connection is open to the appropriate server already, but with the wrong
980 * database, it will be switched to the right database and returned, as long as
981 * it has been freed first with reuseConnection().
983 * On error, returns false, and the connection which caused the
984 * error will be available via $this->errorConnection.
986 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
988 * @param int $i Server index
989 * @param string $domain Domain ID to open
990 * @param int $flags Class CONN_* constant bitfield
991 * @return Database|bool Returns false on connection error
992 * @throws DBError When database selection fails
994 private function openForeignConnection( $i, $domain, $flags = 0 ) {
995 $domainInstance = DatabaseDomain
::newFromId( $domain );
996 // Connection handles required to be in auto-commit mode use a separate connection
997 // pool since the main pool is effected by implicit and explicit transaction rounds
998 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
1000 if ( $autoCommit ) {
1001 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
1002 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
1004 $connFreeKey = self
::KEY_FOREIGN_FREE
;
1005 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
1008 /** @var Database $conn */
1011 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
1012 // Reuse an in-use connection for the same domain
1013 $conn = $this->conns
[$connInUseKey][$i][$domain];
1014 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
1015 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
1016 // Reuse a free connection for the same domain
1017 $conn = $this->conns
[$connFreeKey][$i][$domain];
1018 unset( $this->conns
[$connFreeKey][$i][$domain] );
1019 $this->conns
[$connInUseKey][$i][$domain] = $conn;
1020 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
1021 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
1022 // Reuse a free connection from another domain if possible
1023 foreach ( $this->conns
[$connFreeKey][$i] as $oldDomain => $conn ) {
1024 if ( $domainInstance->getDatabase() !== null ) {
1025 // Check if changing the database will require a new connection.
1026 // In that case, leave the connection handle alone and keep looking.
1027 // This prevents connections from being closed mid-transaction and can
1028 // also avoid overhead if the same database will later be requested.
1030 $conn->databasesAreIndependent() &&
1031 $conn->getDBname() !== $domainInstance->getDatabase()
1035 // Select the new database, schema, and prefix
1036 $conn->selectDomain( $domainInstance );
1038 // Stay on the current database, but update the schema/prefix
1039 $conn->dbSchema( $domainInstance->getSchema() );
1040 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1042 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
1043 // Note that if $domain is an empty string, getDomainID() might not match it
1044 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1045 $this->connLogger
->debug( __METHOD__
.
1046 ": reusing free connection from $oldDomain for $domain" );
1052 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
1053 throw new InvalidArgumentException( "No server with index '$i'" );
1055 // Open a new connection
1056 $server = $this->servers
[$i];
1057 $server['serverIndex'] = $i;
1058 $server['foreignPoolRefCount'] = 0;
1059 $server['foreign'] = true;
1060 $server['autoCommitOnly'] = $autoCommit;
1061 $conn = $this->reallyOpenConnection( $server, $domainInstance );
1062 if ( !$conn->isOpen() ) {
1063 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
1064 $this->errorConnection
= $conn;
1067 // Note that if $domain is an empty string, getDomainID() might not match it
1068 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1069 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1073 if ( $conn instanceof IDatabase
) {
1074 // Final sanity check to make sure the right domain is selected
1075 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1076 throw new UnexpectedValueException(
1077 "Got connection to '{$conn->getDomainID()}', but expected '$domain'" );
1079 // Increment reference count
1080 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1081 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1087 public function getServerAttributes( $i ) {
1088 return Database
::attributesFromType(
1089 $this->getServerType( $i ),
1090 $this->servers
[$i]['driver'] ??
null
1095 * Test if the specified index represents an open connection
1097 * @param int $index Server index
1101 private function isOpen( $index ) {
1102 if ( !is_int( $index ) ) {
1106 return (bool)$this->getAnyOpenConnection( $index );
1110 * Open a new network connection to a server (uncached)
1112 * Returns a Database object whether or not the connection was successful.
1114 * @param array $server
1115 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
1117 * @throws DBAccessError
1118 * @throws InvalidArgumentException
1120 protected function reallyOpenConnection( array $server, DatabaseDomain
$domain ) {
1121 if ( $this->disabled
) {
1122 throw new DBAccessError();
1125 if ( $domain->getDatabase() === null ) {
1126 // The database domain does not specify a DB name and some database systems require a
1127 // valid DB specified on connection. The $server configuration array contains a default
1128 // DB name to use for connections in such cases.
1129 if ( $server['type'] === 'mysql' ) {
1130 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1131 // and the DB name in $server might not exist due to legacy reasons (the default
1132 // domain used to ignore the local LB domain, even when mismatched).
1133 $server['dbname'] = null;
1136 $server['dbname'] = $domain->getDatabase();
1139 if ( $domain->getSchema() !== null ) {
1140 $server['schema'] = $domain->getSchema();
1143 // It is always possible to connect with any prefix, even the empty string
1144 $server['tablePrefix'] = $domain->getTablePrefix();
1146 // Let the handle know what the cluster master is (e.g. "db1052")
1147 $masterName = $this->getServerName( $this->getWriterIndex() );
1148 $server['clusterMasterHost'] = $masterName;
1150 // Log when many connection are made on requests
1151 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
1152 $this->perfLogger
->warning( __METHOD__
. ": " .
1153 "{$this->connsOpened}+ connections made (master=$masterName)" );
1156 $server['srvCache'] = $this->srvCache
;
1157 // Set loggers and profilers
1158 $server['connLogger'] = $this->connLogger
;
1159 $server['queryLogger'] = $this->queryLogger
;
1160 $server['errorLogger'] = $this->errorLogger
;
1161 $server['deprecationLogger'] = $this->deprecationLogger
;
1162 $server['profiler'] = $this->profiler
;
1163 $server['trxProfiler'] = $this->trxProfiler
;
1164 // Use the same agent and PHP mode for all DB handles
1165 $server['cliMode'] = $this->cliMode
;
1166 $server['agent'] = $this->agent
;
1167 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1168 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1169 $server['flags'] = $server['flags'] ?? IDatabase
::DBO_DEFAULT
;
1171 // Create a live connection object
1173 $db = Database
::factory( $server['type'], $server );
1174 } catch ( DBConnectionError
$e ) {
1175 // FIXME: This is probably the ugliest thing I have ever done to
1176 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1180 $db->setLBInfo( $server );
1181 $db->setLazyMasterHandle(
1182 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1184 $db->setTableAliases( $this->tableAliases
);
1185 $db->setIndexAliases( $this->indexAliases
);
1187 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1188 if ( $this->trxRoundId
!== false ) {
1189 $this->applyTransactionRoundFlags( $db );
1191 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1192 $db->setTransactionListener( $name, $callback );
1200 * @throws DBConnectionError
1202 private function reportConnectionError() {
1203 $conn = $this->errorConnection
; // the connection which caused the error
1205 'method' => __METHOD__
,
1206 'last_error' => $this->lastError
,
1209 if ( $conn instanceof IDatabase
) {
1210 $context['db_server'] = $conn->getServer();
1211 $this->connLogger
->warning(
1212 __METHOD__
. ": connection error: {last_error} ({db_server})",
1216 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1218 // No last connection, probably due to all servers being too busy
1219 $this->connLogger
->error(
1221 ": LB failure with no last connection. Connection error: {last_error}",
1225 // If all servers were busy, "lastError" will contain something sensible
1226 throw new DBConnectionError( null, $this->lastError
);
1230 public function getWriterIndex() {
1234 public function haveIndex( $i ) {
1235 return array_key_exists( $i, $this->servers
);
1238 public function isNonZeroLoad( $i ) {
1239 return array_key_exists( $i, $this->servers
) && $this->genericLoads
[$i] != 0;
1242 public function getServerCount() {
1243 return count( $this->servers
);
1246 public function getServerName( $i ) {
1247 $name = $this->servers
[$i]['hostName'] ??
$this->servers
[$i]['host'] ??
'';
1249 return ( $name != '' ) ?
$name : 'localhost';
1252 public function getServerInfo( $i ) {
1253 return $this->servers
[$i] ??
false;
1256 public function getServerType( $i ) {
1257 return $this->servers
[$i]['type'] ??
'unknown';
1260 public function getMasterPos() {
1261 # If this entire request was served from a replica DB without opening a connection to the
1262 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1263 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1264 if ( !$masterConn ) {
1265 $serverCount = count( $this->servers
);
1266 for ( $i = 1; $i < $serverCount; $i++
) {
1267 $conn = $this->getAnyOpenConnection( $i );
1269 return $conn->getReplicaPos();
1273 return $masterConn->getMasterPos();
1279 public function disable() {
1281 $this->disabled
= true;
1284 public function closeAll() {
1285 $fname = __METHOD__
;
1286 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( $fname ) {
1287 $host = $conn->getServer();
1288 $this->connLogger
->debug(
1289 $fname . ": closing connection to database '$host'." );
1294 self
::KEY_LOCAL
=> [],
1295 self
::KEY_FOREIGN_INUSE
=> [],
1296 self
::KEY_FOREIGN_FREE
=> [],
1297 self
::KEY_LOCAL_NOROUND
=> [],
1298 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1299 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1301 $this->connsOpened
= 0;
1304 public function closeConnection( IDatabase
$conn ) {
1305 if ( $conn instanceof DBConnRef
) {
1306 // Avoid calling close() but still leaving the handle in the pool
1307 throw new RuntimeException( 'Cannot close DBConnRef instance; it must be shareable' );
1310 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1311 foreach ( $this->conns
as $type => $connsByServer ) {
1312 if ( !isset( $connsByServer[$serverIndex] ) ) {
1316 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1317 if ( $conn === $trackedConn ) {
1318 $host = $this->getServerName( $i );
1319 $this->connLogger
->debug(
1320 __METHOD__
. ": closing connection to database $i at '$host'." );
1321 unset( $this->conns
[$type][$serverIndex][$i] );
1322 --$this->connsOpened
;
1331 public function commitAll( $fname = __METHOD__
) {
1332 $this->commitMasterChanges( $fname );
1333 $this->flushMasterSnapshots( $fname );
1334 $this->flushReplicaSnapshots( $fname );
1337 public function finalizeMasterChanges() {
1338 $this->assertTransactionRoundStage( [ self
::ROUND_CURSORY
, self
::ROUND_FINALIZED
] );
1340 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1341 // Loop until callbacks stop adding callbacks on other connections
1344 $count = 0; // callbacks execution attempts
1345 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$count ) {
1346 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1347 // Any error should cause all (peer) transactions to be rolled back together.
1348 $count +
= $conn->runOnTransactionPreCommitCallbacks();
1351 } while ( $count > 0 );
1352 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1353 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1354 $conn->setTrxEndCallbackSuppression( true );
1356 $this->trxRoundStage
= self
::ROUND_FINALIZED
;
1361 public function approveMasterChanges( array $options ) {
1362 $this->assertTransactionRoundStage( self
::ROUND_FINALIZED
);
1364 $limit = $options['maxWriteDuration'] ??
0;
1366 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1367 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1368 // If atomic sections or explicit transactions are still open, some caller must have
1369 // caught an exception but failed to properly rollback any changes. Detect that and
1370 // throw and error (causing rollback).
1371 $conn->assertNoOpenTransactions();
1372 // Assert that the time to replicate the transaction will be sane.
1373 // If this fails, then all DB transactions will be rollback back together.
1374 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1375 if ( $limit > 0 && $time > $limit ) {
1376 throw new DBTransactionSizeError(
1378 "Transaction spent $time second(s) in writes, exceeding the limit of $limit",
1382 // If a connection sits idle while slow queries execute on another, that connection
1383 // may end up dropped before the commit round is reached. Ping servers to detect this.
1384 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1385 throw new DBTransactionError(
1387 "A connection to the {$conn->getDBname()} database was lost before commit"
1391 $this->trxRoundStage
= self
::ROUND_APPROVED
;
1394 public function beginMasterChanges( $fname = __METHOD__
) {
1395 if ( $this->trxRoundId
!== false ) {
1396 throw new DBTransactionError(
1398 "$fname: Transaction round '{$this->trxRoundId}' already started"
1401 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
1403 // Clear any empty transactions (no writes/callbacks) from the implicit round
1404 $this->flushMasterSnapshots( $fname );
1406 $this->trxRoundId
= $fname;
1407 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1408 // Mark applicable handles as participating in this explicit transaction round.
1409 // For each of these handles, any writes and callbacks will be tied to a single
1410 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1411 // are part of an en masse commit or an en masse rollback.
1412 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1413 $this->applyTransactionRoundFlags( $conn );
1415 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1418 public function commitMasterChanges( $fname = __METHOD__
) {
1419 $this->assertTransactionRoundStage( self
::ROUND_APPROVED
);
1423 /** @noinspection PhpUnusedLocalVariableInspection */
1424 $scope = ScopedCallback
::newScopedIgnoreUserAbort(); // try to ignore client aborts
1426 $restore = ( $this->trxRoundId
!== false );
1427 $this->trxRoundId
= false;
1428 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1429 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1430 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1431 $this->forEachOpenMasterConnection(
1432 function ( IDatabase
$conn ) use ( $fname, &$failures ) {
1434 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1435 } catch ( DBError
$e ) {
1436 ( $this->errorLogger
)( $e );
1437 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1442 throw new DBTransactionError(
1444 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1448 // Unmark handles as participating in this explicit transaction round
1449 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1450 $this->undoTransactionRoundFlags( $conn );
1453 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
1456 public function runMasterTransactionIdleCallbacks() {
1457 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1458 $type = IDatabase
::TRIGGER_COMMIT
;
1459 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1460 $type = IDatabase
::TRIGGER_ROLLBACK
;
1462 throw new DBTransactionError(
1464 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1468 $oldStage = $this->trxRoundStage
;
1469 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1471 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1472 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1473 $conn->setTrxEndCallbackSuppression( false );
1476 $e = null; // first exception
1477 $fname = __METHOD__
;
1478 // Loop until callbacks stop adding callbacks on other connections
1480 // Run any pending callbacks for each connection...
1481 $count = 0; // callback execution attempts
1482 $this->forEachOpenMasterConnection(
1483 function ( Database
$conn ) use ( $type, &$e, &$count ) {
1484 if ( $conn->trxLevel() ) {
1485 return; // retry in the next iteration, after commit() is called
1488 $count +
= $conn->runOnTransactionIdleCallbacks( $type );
1489 } catch ( Exception
$ex ) {
1494 // Clear out any active transactions left over from callbacks...
1495 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$e, $fname ) {
1496 if ( $conn->writesPending() ) {
1497 // A callback from another handle wrote to this one and DBO_TRX is set
1498 $this->queryLogger
->warning( $fname . ": found writes pending." );
1499 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1500 $this->queryLogger
->warning(
1501 $fname . ": found writes pending ($fnames).",
1503 'db_server' => $conn->getServer(),
1504 'db_name' => $conn->getDBname()
1507 } elseif ( $conn->trxLevel() ) {
1508 // A callback from another handle read from this one and DBO_TRX is set,
1509 // which can easily happen if there is only one DB (no replicas)
1510 $this->queryLogger
->debug( $fname . ": found empty transaction." );
1513 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1514 } catch ( Exception
$ex ) {
1518 } while ( $count > 0 );
1520 $this->trxRoundStage
= $oldStage;
1525 public function runMasterTransactionListenerCallbacks() {
1526 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1527 $type = IDatabase
::TRIGGER_COMMIT
;
1528 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1529 $type = IDatabase
::TRIGGER_ROLLBACK
;
1531 throw new DBTransactionError(
1533 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1539 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1540 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1542 $conn->runTransactionListenerCallbacks( $type );
1543 } catch ( Exception
$ex ) {
1547 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1552 public function rollbackMasterChanges( $fname = __METHOD__
) {
1553 $restore = ( $this->trxRoundId
!== false );
1554 $this->trxRoundId
= false;
1555 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1556 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1557 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1560 // Unmark handles as participating in this explicit transaction round
1561 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1562 $this->undoTransactionRoundFlags( $conn );
1565 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
1569 * @param string|string[] $stage
1571 private function assertTransactionRoundStage( $stage ) {
1572 $stages = (array)$stage;
1574 if ( !in_array( $this->trxRoundStage
, $stages, true ) ) {
1575 $stageList = implode(
1577 array_map( function ( $v ) {
1581 throw new DBTransactionError(
1583 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1589 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1591 * Some servers may have neither flag enabled, meaning that they opt out of such
1592 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1593 * when a DB server is used for something like simple key/value storage.
1595 * @param Database $conn
1597 private function applyTransactionRoundFlags( Database
$conn ) {
1598 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1599 return; // transaction rounds do not apply to these connections
1602 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1603 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1604 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1605 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1608 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1609 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1614 * @param Database $conn
1616 private function undoTransactionRoundFlags( Database
$conn ) {
1617 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1618 return; // transaction rounds do not apply to these connections
1621 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1622 $conn->setLBInfo( 'trxRoundId', false );
1625 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1626 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1630 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1631 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) use ( $fname ) {
1632 $conn->flushSnapshot( $fname );
1636 public function flushMasterSnapshots( $fname = __METHOD__
) {
1637 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1638 $conn->flushSnapshot( $fname );
1646 public function getTransactionRoundStage() {
1647 return $this->trxRoundStage
;
1650 public function hasMasterConnection() {
1651 return $this->isOpen( $this->getWriterIndex() );
1654 public function hasMasterChanges() {
1656 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1657 $pending |
= $conn->writesOrCallbacksPending();
1660 return (bool)$pending;
1663 public function lastMasterChangeTimestamp() {
1665 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1666 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1672 public function hasOrMadeRecentMasterChanges( $age = null ) {
1673 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1675 return ( $this->hasMasterChanges()
1676 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1679 public function pendingMasterChangeCallers() {
1681 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1682 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1688 public function getLaggedReplicaMode( $domain = false ) {
1690 // Avoid recursion if there is only one DB
1691 $this->getServerCount() > 1 &&
1692 // Avoid recursion if the (non-zero load) master DB was picked for generic reads
1693 $this->genericReadIndex
!== $this->getWriterIndex() &&
1694 // Stay in lagged replica mode during the load balancer instance lifetime
1695 !$this->laggedReplicaMode
1698 // Calling this method will set "laggedReplicaMode" as needed
1699 $this->getReaderIndex( false, $domain );
1700 } catch ( DBConnectionError
$e ) {
1701 // Avoid expensive re-connect attempts and failures
1702 $this->allReplicasDownMode
= true;
1703 $this->laggedReplicaMode
= true;
1707 return $this->laggedReplicaMode
;
1710 public function laggedReplicaUsed() {
1711 return $this->laggedReplicaMode
;
1717 * @deprecated Since 1.28; use laggedReplicaUsed()
1719 public function laggedSlaveUsed() {
1720 return $this->laggedReplicaUsed();
1723 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1724 if ( $this->readOnlyReason
!== false ) {
1725 return $this->readOnlyReason
;
1726 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1727 if ( $this->allReplicasDownMode
) {
1728 return 'The database has been automatically locked ' .
1729 'until the replica database servers become available';
1731 return 'The database has been automatically locked ' .
1732 'while the replica database servers catch up to the master.';
1734 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1735 return 'The database master is running in read-only mode.';
1742 * @param string $domain Domain ID, or false for the current domain
1743 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1746 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1747 $cache = $this->wanCache
;
1748 $masterServer = $this->getServerName( $this->getWriterIndex() );
1750 return (bool)$cache->getWithSetCallback(
1751 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1752 self
::TTL_CACHE_READONLY
,
1753 function () use ( $domain, $conn ) {
1754 $old = $this->trxProfiler
->setSilenced( true );
1756 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1757 $readOnly = (int)$dbw->serverIsReadOnly();
1759 $this->reuseConnection( $dbw );
1761 } catch ( DBError
$e ) {
1764 $this->trxProfiler
->setSilenced( $old );
1767 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1771 public function allowLagged( $mode = null ) {
1772 if ( $mode === null ) {
1773 return $this->allowLagged
;
1775 $this->allowLagged
= $mode;
1777 return $this->allowLagged
;
1780 public function pingAll() {
1782 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1783 if ( !$conn->ping() ) {
1791 public function forEachOpenConnection( $callback, array $params = [] ) {
1792 foreach ( $this->conns
as $connsByServer ) {
1793 foreach ( $connsByServer as $serverConns ) {
1794 foreach ( $serverConns as $conn ) {
1795 $callback( $conn, ...$params );
1801 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1802 $masterIndex = $this->getWriterIndex();
1803 foreach ( $this->conns
as $connsByServer ) {
1804 if ( isset( $connsByServer[$masterIndex] ) ) {
1805 /** @var IDatabase $conn */
1806 foreach ( $connsByServer[$masterIndex] as $conn ) {
1807 $callback( $conn, ...$params );
1813 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1814 foreach ( $this->conns
as $connsByServer ) {
1815 foreach ( $connsByServer as $i => $serverConns ) {
1816 if ( $i === $this->getWriterIndex() ) {
1817 continue; // skip master
1819 foreach ( $serverConns as $conn ) {
1820 $callback( $conn, ...$params );
1826 public function getMaxLag( $domain = false ) {
1831 if ( $this->getServerCount() <= 1 ) {
1832 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1835 $lagTimes = $this->getLagTimes( $domain );
1836 foreach ( $lagTimes as $i => $lag ) {
1837 if ( $this->genericLoads
[$i] > 0 && $lag > $maxLag ) {
1839 $host = $this->servers
[$i]['host'];
1844 return [ $host, $maxLag, $maxIndex ];
1847 public function getLagTimes( $domain = false ) {
1848 if ( $this->getServerCount() <= 1 ) {
1849 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1852 $knownLagTimes = []; // map of (server index => 0 seconds)
1853 $indexesWithLag = [];
1854 foreach ( $this->servers
as $i => $server ) {
1855 if ( empty( $server['is static'] ) ) {
1856 $indexesWithLag[] = $i; // DB server might have replication lag
1858 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1862 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1865 public function safeGetLag( IDatabase
$conn ) {
1866 if ( $this->getServerCount() <= 1 ) {
1869 return $conn->getLag();
1873 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
1874 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
1876 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1877 return true; // server is not a replica DB
1881 // Get the current master position, opening a connection if needed
1882 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1883 if ( $masterConn ) {
1884 $pos = $masterConn->getMasterPos();
1886 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1887 if ( !$masterConn ) {
1888 throw new DBReplicationWaitError(
1890 "Could not obtain a master database connection to get the position"
1893 $pos = $masterConn->getMasterPos();
1894 $this->closeConnection( $masterConn );
1898 if ( $pos instanceof DBMasterPos
) {
1899 $result = $conn->masterPosWait( $pos, $timeout );
1900 if ( $result == -1 ||
is_null( $result ) ) {
1901 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos}';
1902 $this->replLogger
->warning( $msg, [
1903 'host' => $conn->getServer(),
1905 'trace' => ( new RuntimeException() )->getTraceAsString()
1909 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
1913 $ok = false; // something is misconfigured
1914 $this->replLogger
->error(
1915 __METHOD__
. ': could not get master pos for {host}',
1917 'host' => $conn->getServer(),
1918 'trace' => ( new RuntimeException() )->getTraceAsString()
1926 public function setTransactionListener( $name, callable
$callback = null ) {
1928 $this->trxRecurringCallbacks
[$name] = $callback;
1930 unset( $this->trxRecurringCallbacks
[$name] );
1932 $this->forEachOpenMasterConnection(
1933 function ( IDatabase
$conn ) use ( $name, $callback ) {
1934 $conn->setTransactionListener( $name, $callback );
1939 public function setTableAliases( array $aliases ) {
1940 $this->tableAliases
= $aliases;
1943 public function setIndexAliases( array $aliases ) {
1944 $this->indexAliases
= $aliases;
1948 * @param string $prefix
1949 * @deprecated Since 1.33
1951 public function setDomainPrefix( $prefix ) {
1952 $this->setLocalDomainPrefix( $prefix );
1955 public function setLocalDomainPrefix( $prefix ) {
1956 // Find connections to explicit foreign domains still marked as in-use...
1958 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
1959 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1960 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1961 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1962 $domainsInUse[] = $conn->getDomainID();
1966 // Do not switch connections to explicit foreign domains unless marked as safe
1967 if ( $domainsInUse ) {
1968 $domains = implode( ', ', $domainsInUse );
1969 throw new DBUnexpectedError( null,
1970 "Foreign domain connections are still in use ($domains)" );
1973 $this->setLocalDomain( new DatabaseDomain(
1974 $this->localDomain
->getDatabase(),
1975 $this->localDomain
->getSchema(),
1979 // Update the prefix for all local connections...
1980 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1981 if ( !$db->getLBInfo( 'foreign' ) ) {
1982 $db->tablePrefix( $prefix );
1987 public function redefineLocalDomain( $domain ) {
1990 $this->setLocalDomain( DatabaseDomain
::newFromId( $domain ) );
1994 * @param DatabaseDomain $domain
1996 private function setLocalDomain( DatabaseDomain
$domain ) {
1997 $this->localDomain
= $domain;
1998 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
1999 // always true, gracefully handle the case when they fail to account for escaping.
2000 if ( $this->localDomain
->getTablePrefix() != '' ) {
2001 $this->localDomainIdAlias
=
2002 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
2004 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
2008 function __destruct() {
2009 // Avoid connection leaks for sanity
2015 * @deprecated since 1.29
2017 class_alias( LoadBalancer
::class, 'LoadBalancer' );