3 * Database load balancing manager
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 namespace Wikimedia\Rdbms
;
24 use Psr\Log\LoggerInterface
;
25 use Psr\Log\NullLogger
;
26 use Wikimedia\ScopedCallback
;
31 use UnexpectedValueException
;
32 use InvalidArgumentException
;
37 * Database connection, tracking, load balancing, and transaction manager for a cluster
41 class LoadBalancer
implements ILoadBalancer
{
42 /** @var ILoadMonitor */
44 /** @var callable|null Callback to run before the first connection attempt */
45 private $chronologyCallback;
48 /** @var WANObjectCache */
50 /** @var mixed Class name or object With profileIn/profileOut methods */
52 /** @var TransactionProfiler */
54 /** @var LoggerInterface */
56 /** @var LoggerInterface */
58 /** @var LoggerInterface */
60 /** @var LoggerInterface */
62 /** @var callable Exception logger */
64 /** @var callable Deprecation logger */
65 private $deprecationLogger;
67 /** @var DatabaseDomain Local DB domain ID and default for selectDB() calls */
70 /** @var Database[][][] Map of (connection category => server index => IDatabase[]) */
73 /** @var array[] Map of (server index => server config array) */
75 /** @var float[] Map of (server index => weight) */
76 private $genericLoads;
77 /** @var array[] Map of (group => server index => weight) */
79 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
81 /** @var int Seconds to spend waiting on replica DB lag to resolve */
83 /** @var array The LoadMonitor configuration */
84 private $loadMonitorConfig;
85 /** @var string Alternate local DB domain instead of DatabaseDomain::getId() */
86 private $localDomainIdAlias;
90 /** @var string Current server name */
92 /** @var bool Whether this PHP instance is for a CLI script */
94 /** @var string Agent name for query profiling */
97 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
98 private $tableAliases = [];
99 /** @var string[] Map of (index alias => index) */
100 private $indexAliases = [];
101 /** @var array[] Map of (name => callable) */
102 private $trxRecurringCallbacks = [];
104 /** @var Database DB connection object that caused a problem */
105 private $errorConnection;
106 /** @var int The generic (not query grouped) replica DB index */
107 private $genericReadIndex = -1;
108 /** @var int[] The group replica DB indexes keyed by group */
109 private $readIndexByGroup = [];
110 /** @var bool|DBMasterPos False if not set */
112 /** @var bool Whether the generic reader fell back to a lagged replica DB */
113 private $laggedReplicaMode = false;
114 /** @var bool Whether the generic reader fell back to a lagged replica DB */
115 private $allReplicasDownMode = false;
116 /** @var string The last DB selection or connection error */
117 private $lastError = 'Unknown error';
118 /** @var string|bool Reason the LB is read-only or false if not */
119 private $readOnlyReason = false;
120 /** @var int Total connections opened */
121 private $connsOpened = 0;
123 private $disabled = false;
124 /** @var bool Whether any connection has been attempted yet */
125 private $connectionAttempted = false;
127 /** @var int|null An integer ID of the managing LBFactory instance or null */
129 /** @var string|bool String if a requested DBO_TRX transaction round is active */
130 private $trxRoundId = false;
131 /** @var string Stage of the current transaction round in the transaction round life-cycle */
132 private $trxRoundStage = self
::ROUND_CURSORY
;
134 /** @var string|null */
135 private $defaultGroup = null;
137 /** @var int Warn when this many connection are held */
138 const CONN_HELD_WARN_THRESHOLD
= 10;
140 /** @var int Default 'maxLag' when unspecified */
141 const MAX_LAG_DEFAULT
= 6;
142 /** @var int Default 'waitTimeout' when unspecified */
143 const MAX_WAIT_DEFAULT
= 10;
144 /** @var int Seconds to cache master server read-only status */
145 const TTL_CACHE_READONLY
= 5;
147 const KEY_LOCAL
= 'local';
148 const KEY_FOREIGN_FREE
= 'foreignFree';
149 const KEY_FOREIGN_INUSE
= 'foreignInUse';
151 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
152 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
153 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
155 /** @var string Transaction round, explicit or implicit, has not finished writing */
156 const ROUND_CURSORY
= 'cursory';
157 /** @var string Transaction round writes are complete and ready for pre-commit checks */
158 const ROUND_FINALIZED
= 'finalized';
159 /** @var string Transaction round passed final pre-commit checks */
160 const ROUND_APPROVED
= 'approved';
161 /** @var string Transaction round was committed and post-commit callbacks must be run */
162 const ROUND_COMMIT_CALLBACKS
= 'commit-callbacks';
163 /** @var string Transaction round was rolled back and post-rollback callbacks must be run */
164 const ROUND_ROLLBACK_CALLBACKS
= 'rollback-callbacks';
165 /** @var string Transaction round encountered an error */
166 const ROUND_ERROR
= 'error';
168 public function __construct( array $params ) {
169 if ( !isset( $params['servers'] ) ) {
170 throw new InvalidArgumentException( __CLASS__
. ': missing "servers" parameter' );
172 $this->servers
= $params['servers'];
173 foreach ( $this->servers
as $i => $server ) {
175 $this->servers
[$i]['master'] = true;
177 $this->servers
[$i]['replica'] = true;
181 $localDomain = isset( $params['localDomain'] )
182 ? DatabaseDomain
::newFromId( $params['localDomain'] )
183 : DatabaseDomain
::newUnspecified();
184 $this->setLocalDomain( $localDomain );
186 $this->waitTimeout
= $params['waitTimeout'] ?? self
::MAX_WAIT_DEFAULT
;
189 // Connection were transaction rounds may be applied
190 self
::KEY_LOCAL
=> [],
191 self
::KEY_FOREIGN_INUSE
=> [],
192 self
::KEY_FOREIGN_FREE
=> [],
193 // Auto-committing counterpart connections that ignore transaction rounds
194 self
::KEY_LOCAL_NOROUND
=> [],
195 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
196 self
::KEY_FOREIGN_FREE_NOROUND
=> []
198 $this->genericLoads
= [];
199 $this->waitForPos
= false;
200 $this->allowLagged
= false;
202 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
203 $this->readOnlyReason
= $params['readOnlyReason'];
206 $this->maxLag
= $params['maxLag'] ?? self
::MAX_LAG_DEFAULT
;
208 $this->loadMonitorConfig
= $params['loadMonitor'] ??
[ 'class' => 'LoadMonitorNull' ];
209 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
211 foreach ( $params['servers'] as $i => $server ) {
212 $this->genericLoads
[$i] = $server['load'];
213 if ( isset( $server['groupLoads'] ) ) {
214 foreach ( $server['groupLoads'] as $group => $ratio ) {
215 if ( !isset( $this->groupLoads
[$group] ) ) {
216 $this->groupLoads
[$group] = [];
218 $this->groupLoads
[$group][$i] = $ratio;
223 $this->srvCache
= $params['srvCache'] ??
new EmptyBagOStuff();
224 $this->wanCache
= $params['wanCache'] ?? WANObjectCache
::newEmpty();
225 $this->profiler
= $params['profiler'] ??
null;
226 $this->trxProfiler
= $params['trxProfiler'] ??
new TransactionProfiler();
228 $this->errorLogger
= $params['errorLogger'] ??
function ( Exception
$e ) {
229 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
231 $this->deprecationLogger
= $params['deprecationLogger'] ??
function ( $msg ) {
232 trigger_error( $msg, E_USER_DEPRECATED
);
235 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
236 $this->$key = $params[$key] ??
new NullLogger();
239 $this->hostname
= $params['hostname'] ??
( gethostname() ?
: 'unknown' );
240 $this->cliMode
= $params['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
241 $this->agent
= $params['agent'] ??
'';
243 if ( isset( $params['chronologyCallback'] ) ) {
244 $this->chronologyCallback
= $params['chronologyCallback'];
247 if ( isset( $params['roundStage'] ) ) {
248 if ( $params['roundStage'] === self
::STAGE_POSTCOMMIT_CALLBACKS
) {
249 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
250 } elseif ( $params['roundStage'] === self
::STAGE_POSTROLLBACK_CALLBACKS
) {
251 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
255 $this->defaultGroup
= $params['defaultGroup'] ??
null;
256 $this->ownerId
= $params['ownerId'] ??
null;
259 public function getLocalDomainID() {
260 return $this->localDomain
->getId();
263 public function resolveDomainID( $domain ) {
264 if ( $domain === $this->localDomainIdAlias ||
$domain === false ) {
265 // Local connection requested via some backwards-compatibility domain alias
266 return $this->getLocalDomainID();
269 return (string)$domain;
273 * Get a LoadMonitor instance
275 * @return ILoadMonitor
277 private function getLoadMonitor() {
278 if ( !isset( $this->loadMonitor
) ) {
280 'LoadMonitor' => LoadMonitor
::class,
281 'LoadMonitorNull' => LoadMonitorNull
::class,
282 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
285 $class = $this->loadMonitorConfig
['class'];
286 if ( isset( $compat[$class] ) ) {
287 $class = $compat[$class];
290 $this->loadMonitor
= new $class(
291 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
292 $this->loadMonitor
->setLogger( $this->replLogger
);
295 return $this->loadMonitor
;
299 * @param array $loads
300 * @param bool|string $domain Domain to get non-lagged for
301 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
302 * @return bool|int|string
304 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
305 $lags = $this->getLagTimes( $domain );
307 # Unset excessively lagged servers
308 foreach ( $lags as $i => $lag ) {
310 # How much lag this server nominally is allowed to have
311 $maxServerLag = $this->servers
[$i]['max lag'] ??
$this->maxLag
; // default
312 # Constrain that futher by $maxLag argument
313 $maxServerLag = min( $maxServerLag, $maxLag );
315 $host = $this->getServerName( $i );
316 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
317 $this->replLogger
->debug(
319 ": server {host} is not replicating?", [ 'host' => $host ] );
321 } elseif ( $lag > $maxServerLag ) {
322 $this->replLogger
->debug(
324 ": server {host} has {lag} seconds of lag (>= {maxlag})",
325 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
332 # Find out if all the replica DBs with non-zero load are lagged
334 foreach ( $loads as $load ) {
338 # No appropriate DB servers except maybe the master and some replica DBs with zero load
339 # Do NOT use the master
340 # Instead, this function will return false, triggering read-only mode,
341 # and a lagged replica DB will be used instead.
345 if ( count( $loads ) == 0 ) {
349 # Return a random representative of the remainder
350 return ArrayUtils
::pickRandom( $loads );
355 * @param array $groups
356 * @param string|bool $domain
359 private function getConnectionIndex( $i, $groups, $domain ) {
360 // Check one "group" per default: the generic pool
361 $defaultGroups = $this->defaultGroup ?
[ $this->defaultGroup
] : [ false ];
363 $groups = ( $groups === false ||
$groups === [] )
367 if ( $i == self
::DB_MASTER
) {
368 $i = $this->getWriterIndex();
369 } elseif ( $i == self
::DB_REPLICA
) {
370 # Try to find an available server in any the query groups (in order)
371 foreach ( $groups as $group ) {
372 $groupIndex = $this->getReaderIndex( $group, $domain );
373 if ( $groupIndex !== false ) {
380 # Operation-based index
381 if ( $i == self
::DB_REPLICA
) {
382 $this->lastError
= 'Unknown error'; // reset error string
383 # Try the general server pool if $groups are unavailable.
384 $i = ( $groups === [ false ] )
385 ?
false // don't bother with this if that is what was tried above
386 : $this->getReaderIndex( false, $domain );
387 # Couldn't find a working server in getReaderIndex()?
388 if ( $i === false ) {
389 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
390 // Throw an exception
391 $this->reportConnectionError();
392 return null; // not reached
399 public function getReaderIndex( $group = false, $domain = false ) {
400 if ( count( $this->servers
) == 1 ) {
401 // Skip the load balancing if there's only one server
402 return $this->getWriterIndex();
405 $index = $this->getExistingReaderIndex( $group );
407 // A reader index was already selected and "waitForPos" was handled
411 if ( $group !== false ) {
412 // Use the server weight array for this load group
413 if ( isset( $this->groupLoads
[$group] ) ) {
414 $loads = $this->groupLoads
[$group];
416 // No loads for this group, return false and the caller can use some other group
417 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
422 // Use the generic load group
423 $loads = $this->genericLoads
;
426 // Scale the configured load ratios according to each server's load and state
427 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
429 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
430 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
431 if ( $i === false ) {
432 // DB connection unsuccessful
436 // If data seen by queries is expected to reflect the transactions committed as of
437 // or after a given replication position then wait for the DB to apply those changes
438 if ( $this->waitForPos
&& $i != $this->getWriterIndex() && !$this->doWait( $i ) ) {
439 // Data will be outdated compared to what was expected
440 $laggedReplicaMode = true;
443 // Cache the reader index for future DB_REPLICA handles
444 $this->setExistingReaderIndex( $group, $i );
445 // Record whether the generic reader index is in "lagged replica DB" mode
446 if ( $group === false && $laggedReplicaMode ) {
447 $this->laggedReplicaMode
= true;
450 $serverName = $this->getServerName( $i );
451 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
457 * Get the server index chosen by the load balancer for use with the given query group
459 * @param string|bool $group Query group; use false for the generic group
460 * @return int Server index or -1 if none was chosen
462 protected function getExistingReaderIndex( $group ) {
463 if ( $group === false ) {
464 $index = $this->genericReadIndex
;
466 $index = $this->readIndexByGroup
[$group] ??
-1;
473 * Set the server index chosen by the load balancer for use with the given query group
475 * @param string|bool $group Query group; use false for the generic group
476 * @param int $index The index of a specific server
478 private function setExistingReaderIndex( $group, $index ) {
480 throw new UnexpectedValueException( "Cannot set a negative read server index" );
483 if ( $group === false ) {
484 $this->genericReadIndex
= $index;
486 $this->readIndexByGroup
[$group] = $index;
491 * @param array $loads List of server weights
492 * @param string|bool $domain
493 * @return array (reader index, lagged replica mode) or false on failure
495 private function pickReaderIndex( array $loads, $domain = false ) {
496 if ( $loads === [] ) {
497 throw new InvalidArgumentException( "Server configuration array is empty" );
500 /** @var int|bool $i Index of selected server */
502 /** @var bool $laggedReplicaMode Whether server is considered lagged */
503 $laggedReplicaMode = false;
505 // Quickly look through the available servers for a server that meets criteria...
506 $currentLoads = $loads;
507 while ( count( $currentLoads ) ) {
508 if ( $this->allowLagged ||
$laggedReplicaMode ) {
509 $i = ArrayUtils
::pickRandom( $currentLoads );
512 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
513 // "chronologyCallback" sets "waitForPos" for session consistency.
514 // This triggers doWait() after connect, so it's especially good to
515 // avoid lagged servers so as to avoid excessive delay in that method.
516 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
517 // Aim for <= 1 second of waiting (being too picky can backfire)
518 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
520 if ( $i === false ) {
521 // Any server with less lag than it's 'max lag' param is preferable
522 $i = $this->getRandomNonLagged( $currentLoads, $domain );
524 if ( $i === false && count( $currentLoads ) != 0 ) {
525 // All replica DBs lagged. Switch to read-only mode
526 $this->replLogger
->error(
527 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
528 $i = ArrayUtils
::pickRandom( $currentLoads );
529 $laggedReplicaMode = true;
533 if ( $i === false ) {
534 // pickRandom() returned false.
535 // This is permanent and means the configuration or the load monitor
536 // wants us to return false.
537 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
539 return [ false, false ];
542 $serverName = $this->getServerName( $i );
543 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
545 $conn = $this->openConnection( $i, $domain );
547 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
548 unset( $currentLoads[$i] ); // avoid this server next iteration
553 // Decrement reference counter, we are finished with this connection.
554 // It will be incremented for the caller later.
555 if ( $domain !== false ) {
556 $this->reuseConnection( $conn );
559 // Return this server
563 // If all servers were down, quit now
564 if ( $currentLoads === [] ) {
565 $this->connLogger
->error( __METHOD__
. ": all servers down" );
568 return [ $i, $laggedReplicaMode ];
571 public function waitFor( $pos ) {
572 $oldPos = $this->waitForPos
;
574 $this->waitForPos
= $pos;
575 // If a generic reader connection was already established, then wait now
576 if ( $this->genericReadIndex
> 0 && !$this->doWait( $this->genericReadIndex
) ) {
577 $this->laggedReplicaMode
= true;
579 // Otherwise, wait until a connection is established in getReaderIndex()
581 // Restore the older position if it was higher since this is used for lag-protection
582 $this->setWaitForPositionIfHigher( $oldPos );
586 public function waitForOne( $pos, $timeout = null ) {
587 $oldPos = $this->waitForPos
;
589 $this->waitForPos
= $pos;
591 $i = $this->genericReadIndex
;
593 // Pick a generic replica DB if there isn't one yet
594 $readLoads = $this->genericLoads
;
595 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
596 $readLoads = array_filter( $readLoads ); // with non-zero load
597 $i = ArrayUtils
::pickRandom( $readLoads );
601 $ok = $this->doWait( $i, true, $timeout );
603 $ok = true; // no applicable loads
606 # Restore the old position, as this is not used for lag-protection but for throttling
607 $this->waitForPos
= $oldPos;
613 public function waitForAll( $pos, $timeout = null ) {
614 $timeout = $timeout ?
: $this->waitTimeout
;
616 $oldPos = $this->waitForPos
;
618 $this->waitForPos
= $pos;
619 $serverCount = count( $this->servers
);
622 for ( $i = 1; $i < $serverCount; $i++
) {
623 if ( $this->genericLoads
[$i] > 0 ) {
624 $start = microtime( true );
625 $ok = $this->doWait( $i, true, $timeout ) && $ok;
626 $timeout -= intval( microtime( true ) - $start );
627 if ( $timeout <= 0 ) {
628 break; // timeout reached
633 # Restore the old position, as this is not used for lag-protection but for throttling
634 $this->waitForPos
= $oldPos;
641 * @param DBMasterPos|bool $pos
643 private function setWaitForPositionIfHigher( $pos ) {
648 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
649 $this->waitForPos
= $pos;
653 public function getAnyOpenConnection( $i, $flags = 0 ) {
654 $i = ( $i === self
::DB_MASTER
) ?
$this->getWriterIndex() : $i;
655 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
657 foreach ( $this->conns
as $connsByServer ) {
658 if ( $i === self
::DB_REPLICA
) {
659 $indexes = array_keys( $connsByServer );
661 $indexes = isset( $connsByServer[$i] ) ?
[ $i ] : [];
664 foreach ( $indexes as $index ) {
665 foreach ( $connsByServer[$index] as $conn ) {
666 if ( !$conn->isOpen() ) {
667 continue; // some sort of error occured?
669 if ( !$autocommit ||
$conn->getLBInfo( 'autoCommitOnly' ) ) {
680 * Wait for a given replica DB to catch up to the master pos stored in $this
681 * @param int $index Server index
682 * @param bool $open Check the server even if a new connection has to be made
683 * @param int|null $timeout Max seconds to wait; default is "waitTimeout" given to __construct()
686 protected function doWait( $index, $open = false, $timeout = null ) {
687 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
689 // Check if we already know that the DB has reached this point
690 $server = $this->getServerName( $index );
691 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
692 /** @var DBMasterPos $knownReachedPos */
693 $knownReachedPos = $this->srvCache
->get( $key );
695 $knownReachedPos instanceof DBMasterPos
&&
696 $knownReachedPos->hasReached( $this->waitForPos
)
698 $this->replLogger
->debug(
700 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
701 [ 'dbserver' => $server ]
706 // Find a connection to wait on, creating one if needed and allowed
707 $close = false; // close the connection afterwards
708 $conn = $this->getAnyOpenConnection( $index );
711 $this->replLogger
->debug(
712 __METHOD__
. ': no connection open for {dbserver}',
713 [ 'dbserver' => $server ]
718 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
720 $this->replLogger
->warning(
721 __METHOD__
. ': failed to connect to {dbserver}',
722 [ 'dbserver' => $server ]
727 // Avoid connection spam in waitForAll() when connections
728 // are made just for the sake of doing this lag check.
733 $this->replLogger
->info(
735 ': waiting for replica DB {dbserver} to catch up...',
736 [ 'dbserver' => $server ]
739 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
741 if ( $result === null ) {
742 $this->replLogger
->warning(
743 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
746 'pos' => $this->waitForPos
,
747 'trace' => ( new RuntimeException() )->getTraceAsString()
751 } elseif ( $result == -1 ) {
752 $this->replLogger
->warning(
753 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
756 'pos' => $this->waitForPos
,
757 'trace' => ( new RuntimeException() )->getTraceAsString()
762 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
764 // Remember that the DB reached this point
765 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
769 $this->closeConnection( $conn );
775 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
776 if ( $i === null ||
$i === false ) {
777 throw new InvalidArgumentException( "Cannot connect without a server index" );
780 $domain = $this->resolveDomainID( $domain );
781 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
783 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) === self
::CONN_TRX_AUTOCOMMIT
) {
784 // Assuming all servers are of the same type (or similar), which is overwhelmingly
785 // the case, use the master server information to get the attributes. The information
786 // for $i cannot be used since it might be DB_REPLICA, which might require connection
787 // attempts in order to be resolved into a real server index.
788 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
789 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
790 // Callers sometimes want to (a) escape REPEATABLE-READ stateness without locking
791 // rows (e.g. FOR UPDATE) or (b) make small commits during a larger transactions
792 // to reduce lock contention. None of these apply for sqlite and using separate
793 // connections just causes self-deadlocks.
794 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
795 $this->connLogger
->info( __METHOD__
.
796 ': ignoring CONN_TRX_AUTOCOMMIT to avoid deadlocks.' );
800 // Number of connections made before getting the server index and handle
801 $priorConnectionsMade = $this->connsOpened
;
802 // Decide which server to use (might trigger new connections)
803 $serverIndex = $this->getConnectionIndex( $i, $groups, $domain );
804 // Get an open connection to that server (might trigger a new connection)
805 $conn = $this->openConnection( $serverIndex, $domain, $flags );
807 $this->reportConnectionError();
808 return null; // unreachable due to exception
811 // Profile any new connections caused by this method
812 if ( $this->connsOpened
> $priorConnectionsMade ) {
813 $host = $conn->getServer();
814 $dbname = $conn->getDBname();
815 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
818 if ( $serverIndex == $this->getWriterIndex() ) {
819 // If the load balancer is read-only, perhaps due to replication lag, then master
820 // DB handles will reflect that. Note that Database::assertIsWritableMaster() takes
821 // care of replica DB handles whereas getReadOnlyReason() would cause infinite loops.
822 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
828 public function reuseConnection( IDatabase
$conn ) {
829 $serverIndex = $conn->getLBInfo( 'serverIndex' );
830 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
831 if ( $serverIndex === null ||
$refCount === null ) {
833 * This can happen in code like:
834 * foreach ( $dbs as $db ) {
835 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
837 * $lb->reuseConnection( $conn );
839 * When a connection to the local DB is opened in this way, reuseConnection()
843 } elseif ( $conn instanceof DBConnRef
) {
844 // DBConnRef already handles calling reuseConnection() and only passes the live
845 // Database instance to this method. Any caller passing in a DBConnRef is broken.
846 $this->connLogger
->error(
847 __METHOD__
. ": got DBConnRef instance.\n" .
848 ( new RuntimeException() )->getTraceAsString() );
853 if ( $this->disabled
) {
854 return; // DBConnRef handle probably survived longer than the LoadBalancer
857 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
858 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
859 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
861 $connFreeKey = self
::KEY_FOREIGN_FREE
;
862 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
865 $domain = $conn->getDomainID();
866 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
867 throw new InvalidArgumentException(
868 "Connection $serverIndex/$domain not found; it may have already been freed" );
869 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
870 throw new InvalidArgumentException(
871 "Connection $serverIndex/$domain mismatched; it may have already been freed" );
874 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
875 if ( $refCount <= 0 ) {
876 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
877 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
878 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
879 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
881 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
883 $this->connLogger
->debug( __METHOD__
.
884 ": reference count for $serverIndex/$domain reduced to $refCount" );
888 public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
889 $domain = $this->resolveDomainID( $domain );
890 $role = $this->getRoleFromIndex( $i );
892 return new DBConnRef( $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
895 public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
896 $domain = $this->resolveDomainID( $domain );
897 $role = $this->getRoleFromIndex( $i );
899 return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role );
902 public function getMaintenanceConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
903 $domain = $this->resolveDomainID( $domain );
904 $role = $this->getRoleFromIndex( $i );
906 return new MaintainableDBConnRef(
907 $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
911 * @param int $i Server index or DB_MASTER/DB_REPLICA
912 * @return int One of DB_MASTER/DB_REPLICA
914 private function getRoleFromIndex( $i ) {
915 return ( $i === self
::DB_MASTER ||
$i === $this->getWriterIndex() )
920 public function openConnection( $i, $domain = false, $flags = 0 ) {
921 $domain = $this->resolveDomainID( $domain );
923 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
924 // Load any "waitFor" positions before connecting so that doWait() is triggered
925 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
926 $this->connectionAttempted
= true;
927 ( $this->chronologyCallback
)( $this );
930 $conn = $this->localDomain
->equals( $domain )
931 ?
$this->openLocalConnection( $i, $flags )
932 : $this->openForeignConnection( $i, $domain, $flags );
934 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
935 // Connection was made but later unrecoverably lost for some reason.
936 // Do not return a handle that will just throw exceptions on use,
937 // but let the calling code (e.g. getReaderIndex) try another server.
938 $this->errorConnection
= $conn;
943 $conn instanceof IDatabase
&&
944 ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
)
946 if ( $conn->trxLevel() ) { // sanity
947 throw new DBUnexpectedError(
949 'Handle requested with CONN_TRX_AUTOCOMMIT yet it has a transaction'
953 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
960 * Open a connection to a local DB, or return one if it is already open.
962 * On error, returns false, and the connection which caused the
963 * error will be available via $this->errorConnection.
965 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
967 * @param int $i Server index
968 * @param int $flags Class CONN_* constant bitfield
971 private function openLocalConnection( $i, $flags = 0 ) {
972 // Connection handles required to be in auto-commit mode use a separate connection
973 // pool since the main pool is effected by implicit and explicit transaction rounds
974 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
976 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
977 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
978 $conn = $this->conns
[$connKey][$i][0];
980 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
981 throw new InvalidArgumentException( "No server with index '$i'" );
983 // Open a new connection
984 $server = $this->servers
[$i];
985 $server['serverIndex'] = $i;
986 $server['autoCommitOnly'] = $autoCommit;
987 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
988 $host = $this->getServerName( $i );
989 if ( $conn->isOpen() ) {
990 $this->connLogger
->debug(
991 __METHOD__
. ": connected to database $i at '$host'." );
992 $this->conns
[$connKey][$i][0] = $conn;
994 $this->connLogger
->warning(
995 __METHOD__
. ": failed to connect to database $i at '$host'." );
996 $this->errorConnection
= $conn;
1001 // Final sanity check to make sure the right domain is selected
1003 $conn instanceof IDatabase
&&
1004 !$this->localDomain
->isCompatible( $conn->getDomainID() )
1006 throw new UnexpectedValueException(
1007 "Got connection to '{$conn->getDomainID()}', " .
1008 "but expected local domain ('{$this->localDomain}')" );
1015 * Open a connection to a foreign DB, or return one if it is already open.
1017 * Increments a reference count on the returned connection which locks the
1018 * connection to the requested domain. This reference count can be
1019 * decremented by calling reuseConnection().
1021 * If a connection is open to the appropriate server already, but with the wrong
1022 * database, it will be switched to the right database and returned, as long as
1023 * it has been freed first with reuseConnection().
1025 * On error, returns false, and the connection which caused the
1026 * error will be available via $this->errorConnection.
1028 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
1030 * @param int $i Server index
1031 * @param string $domain Domain ID to open
1032 * @param int $flags Class CONN_* constant bitfield
1033 * @return Database|bool Returns false on connection error
1034 * @throws DBError When database selection fails
1036 private function openForeignConnection( $i, $domain, $flags = 0 ) {
1037 $domainInstance = DatabaseDomain
::newFromId( $domain );
1038 // Connection handles required to be in auto-commit mode use a separate connection
1039 // pool since the main pool is effected by implicit and explicit transaction rounds
1040 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
1042 if ( $autoCommit ) {
1043 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
1044 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
1046 $connFreeKey = self
::KEY_FOREIGN_FREE
;
1047 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
1050 /** @var Database $conn */
1053 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
1054 // Reuse an in-use connection for the same domain
1055 $conn = $this->conns
[$connInUseKey][$i][$domain];
1056 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
1057 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
1058 // Reuse a free connection for the same domain
1059 $conn = $this->conns
[$connFreeKey][$i][$domain];
1060 unset( $this->conns
[$connFreeKey][$i][$domain] );
1061 $this->conns
[$connInUseKey][$i][$domain] = $conn;
1062 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
1063 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
1064 // Reuse a free connection from another domain if possible
1065 foreach ( $this->conns
[$connFreeKey][$i] as $oldDomain => $conn ) {
1066 if ( $domainInstance->getDatabase() !== null ) {
1067 // Check if changing the database will require a new connection.
1068 // In that case, leave the connection handle alone and keep looking.
1069 // This prevents connections from being closed mid-transaction and can
1070 // also avoid overhead if the same database will later be requested.
1072 $conn->databasesAreIndependent() &&
1073 $conn->getDBname() !== $domainInstance->getDatabase()
1077 // Select the new database, schema, and prefix
1078 $conn->selectDomain( $domainInstance );
1080 // Stay on the current database, but update the schema/prefix
1081 $conn->dbSchema( $domainInstance->getSchema() );
1082 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1084 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
1085 // Note that if $domain is an empty string, getDomainID() might not match it
1086 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1087 $this->connLogger
->debug( __METHOD__
.
1088 ": reusing free connection from $oldDomain for $domain" );
1094 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
1095 throw new InvalidArgumentException( "No server with index '$i'" );
1097 // Open a new connection
1098 $server = $this->servers
[$i];
1099 $server['serverIndex'] = $i;
1100 $server['foreignPoolRefCount'] = 0;
1101 $server['foreign'] = true;
1102 $server['autoCommitOnly'] = $autoCommit;
1103 $conn = $this->reallyOpenConnection( $server, $domainInstance );
1104 if ( !$conn->isOpen() ) {
1105 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
1106 $this->errorConnection
= $conn;
1109 // Note that if $domain is an empty string, getDomainID() might not match it
1110 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1111 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1115 if ( $conn instanceof IDatabase
) {
1116 // Final sanity check to make sure the right domain is selected
1117 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1118 throw new UnexpectedValueException(
1119 "Got connection to '{$conn->getDomainID()}', but expected '$domain'" );
1121 // Increment reference count
1122 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1123 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1129 public function getServerAttributes( $i ) {
1130 return Database
::attributesFromType(
1131 $this->getServerType( $i ),
1132 $this->servers
[$i]['driver'] ??
null
1137 * Test if the specified index represents an open connection
1139 * @param int $index Server index
1143 private function isOpen( $index ) {
1144 if ( !is_int( $index ) ) {
1148 return (bool)$this->getAnyOpenConnection( $index );
1152 * Open a new network connection to a server (uncached)
1154 * Returns a Database object whether or not the connection was successful.
1156 * @param array $server
1157 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
1159 * @throws DBAccessError
1160 * @throws InvalidArgumentException
1162 protected function reallyOpenConnection( array $server, DatabaseDomain
$domain ) {
1163 if ( $this->disabled
) {
1164 throw new DBAccessError();
1167 if ( $domain->getDatabase() === null ) {
1168 // The database domain does not specify a DB name and some database systems require a
1169 // valid DB specified on connection. The $server configuration array contains a default
1170 // DB name to use for connections in such cases.
1171 if ( $server['type'] === 'mysql' ) {
1172 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1173 // and the DB name in $server might not exist due to legacy reasons (the default
1174 // domain used to ignore the local LB domain, even when mismatched).
1175 $server['dbname'] = null;
1178 $server['dbname'] = $domain->getDatabase();
1181 if ( $domain->getSchema() !== null ) {
1182 $server['schema'] = $domain->getSchema();
1185 // It is always possible to connect with any prefix, even the empty string
1186 $server['tablePrefix'] = $domain->getTablePrefix();
1188 // Let the handle know what the cluster master is (e.g. "db1052")
1189 $masterName = $this->getServerName( $this->getWriterIndex() );
1190 $server['clusterMasterHost'] = $masterName;
1192 // Log when many connection are made on requests
1193 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
1194 $this->perfLogger
->warning( __METHOD__
. ": " .
1195 "{$this->connsOpened}+ connections made (master=$masterName)" );
1198 $server['srvCache'] = $this->srvCache
;
1199 // Set loggers and profilers
1200 $server['connLogger'] = $this->connLogger
;
1201 $server['queryLogger'] = $this->queryLogger
;
1202 $server['errorLogger'] = $this->errorLogger
;
1203 $server['deprecationLogger'] = $this->deprecationLogger
;
1204 $server['profiler'] = $this->profiler
;
1205 $server['trxProfiler'] = $this->trxProfiler
;
1206 // Use the same agent and PHP mode for all DB handles
1207 $server['cliMode'] = $this->cliMode
;
1208 $server['agent'] = $this->agent
;
1209 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1210 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1211 $server['flags'] = $server['flags'] ?? IDatabase
::DBO_DEFAULT
;
1213 // Create a live connection object
1215 $db = Database
::factory( $server['type'], $server );
1216 } catch ( DBConnectionError
$e ) {
1217 // FIXME: This is probably the ugliest thing I have ever done to
1218 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1222 $db->setLBInfo( $server );
1223 $db->setLazyMasterHandle(
1224 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1226 $db->setTableAliases( $this->tableAliases
);
1227 $db->setIndexAliases( $this->indexAliases
);
1229 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1230 if ( $this->trxRoundId
!== false ) {
1231 $this->applyTransactionRoundFlags( $db );
1233 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1234 $db->setTransactionListener( $name, $callback );
1242 * @throws DBConnectionError
1244 private function reportConnectionError() {
1245 $conn = $this->errorConnection
; // the connection which caused the error
1247 'method' => __METHOD__
,
1248 'last_error' => $this->lastError
,
1251 if ( $conn instanceof IDatabase
) {
1252 $context['db_server'] = $conn->getServer();
1253 $this->connLogger
->warning(
1254 __METHOD__
. ": connection error: {last_error} ({db_server})",
1258 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1260 // No last connection, probably due to all servers being too busy
1261 $this->connLogger
->error(
1263 ": LB failure with no last connection. Connection error: {last_error}",
1267 // If all servers were busy, "lastError" will contain something sensible
1268 throw new DBConnectionError( null, $this->lastError
);
1272 public function getWriterIndex() {
1276 public function haveIndex( $i ) {
1277 return array_key_exists( $i, $this->servers
);
1280 public function isNonZeroLoad( $i ) {
1281 return array_key_exists( $i, $this->servers
) && $this->genericLoads
[$i] != 0;
1284 public function getServerCount() {
1285 return count( $this->servers
);
1288 public function getServerName( $i ) {
1289 $name = $this->servers
[$i]['hostName'] ??
$this->servers
[$i]['host'] ??
'';
1291 return ( $name != '' ) ?
$name : 'localhost';
1294 public function getServerInfo( $i ) {
1295 return $this->servers
[$i] ??
false;
1298 public function getServerType( $i ) {
1299 return $this->servers
[$i]['type'] ??
'unknown';
1302 public function getMasterPos() {
1303 # If this entire request was served from a replica DB without opening a connection to the
1304 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1305 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1306 if ( !$masterConn ) {
1307 $serverCount = count( $this->servers
);
1308 for ( $i = 1; $i < $serverCount; $i++
) {
1309 $conn = $this->getAnyOpenConnection( $i );
1311 return $conn->getReplicaPos();
1315 return $masterConn->getMasterPos();
1321 public function disable() {
1323 $this->disabled
= true;
1326 public function closeAll() {
1327 $fname = __METHOD__
;
1328 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( $fname ) {
1329 $host = $conn->getServer();
1330 $this->connLogger
->debug(
1331 $fname . ": closing connection to database '$host'." );
1336 self
::KEY_LOCAL
=> [],
1337 self
::KEY_FOREIGN_INUSE
=> [],
1338 self
::KEY_FOREIGN_FREE
=> [],
1339 self
::KEY_LOCAL_NOROUND
=> [],
1340 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1341 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1343 $this->connsOpened
= 0;
1346 public function closeConnection( IDatabase
$conn ) {
1347 if ( $conn instanceof DBConnRef
) {
1348 // Avoid calling close() but still leaving the handle in the pool
1349 throw new RuntimeException( 'Cannot close DBConnRef instance; it must be shareable' );
1352 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1353 foreach ( $this->conns
as $type => $connsByServer ) {
1354 if ( !isset( $connsByServer[$serverIndex] ) ) {
1358 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1359 if ( $conn === $trackedConn ) {
1360 $host = $this->getServerName( $i );
1361 $this->connLogger
->debug(
1362 __METHOD__
. ": closing connection to database $i at '$host'." );
1363 unset( $this->conns
[$type][$serverIndex][$i] );
1364 --$this->connsOpened
;
1373 public function commitAll( $fname = __METHOD__
, $owner = null ) {
1374 $this->commitMasterChanges( $fname, $owner );
1375 $this->flushMasterSnapshots( $fname );
1376 $this->flushReplicaSnapshots( $fname );
1379 public function finalizeMasterChanges( $fname = __METHOD__
, $owner = null ) {
1380 $this->assertOwnership( $fname, $owner );
1381 $this->assertTransactionRoundStage( [ self
::ROUND_CURSORY
, self
::ROUND_FINALIZED
] );
1383 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1384 // Loop until callbacks stop adding callbacks on other connections
1387 $count = 0; // callbacks execution attempts
1388 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$count ) {
1389 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1390 // Any error should cause all (peer) transactions to be rolled back together.
1391 $count +
= $conn->runOnTransactionPreCommitCallbacks();
1394 } while ( $count > 0 );
1395 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1396 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1397 $conn->setTrxEndCallbackSuppression( true );
1399 $this->trxRoundStage
= self
::ROUND_FINALIZED
;
1404 public function approveMasterChanges( array $options, $fname = __METHOD__
, $owner = null ) {
1405 $this->assertOwnership( $fname, $owner );
1406 $this->assertTransactionRoundStage( self
::ROUND_FINALIZED
);
1408 $limit = $options['maxWriteDuration'] ??
0;
1410 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1411 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1412 // If atomic sections or explicit transactions are still open, some caller must have
1413 // caught an exception but failed to properly rollback any changes. Detect that and
1414 // throw and error (causing rollback).
1415 $conn->assertNoOpenTransactions();
1416 // Assert that the time to replicate the transaction will be sane.
1417 // If this fails, then all DB transactions will be rollback back together.
1418 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1419 if ( $limit > 0 && $time > $limit ) {
1420 throw new DBTransactionSizeError(
1422 "Transaction spent $time second(s) in writes, exceeding the limit of $limit",
1426 // If a connection sits idle while slow queries execute on another, that connection
1427 // may end up dropped before the commit round is reached. Ping servers to detect this.
1428 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1429 throw new DBTransactionError(
1431 "A connection to the {$conn->getDBname()} database was lost before commit"
1435 $this->trxRoundStage
= self
::ROUND_APPROVED
;
1438 public function beginMasterChanges( $fname = __METHOD__
, $owner = null ) {
1439 $this->assertOwnership( $fname, $owner );
1440 if ( $this->trxRoundId
!== false ) {
1441 throw new DBTransactionError(
1443 "$fname: Transaction round '{$this->trxRoundId}' already started"
1446 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
1448 // Clear any empty transactions (no writes/callbacks) from the implicit round
1449 $this->flushMasterSnapshots( $fname );
1451 $this->trxRoundId
= $fname;
1452 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1453 // Mark applicable handles as participating in this explicit transaction round.
1454 // For each of these handles, any writes and callbacks will be tied to a single
1455 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1456 // are part of an en masse commit or an en masse rollback.
1457 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1458 $this->applyTransactionRoundFlags( $conn );
1460 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1463 public function commitMasterChanges( $fname = __METHOD__
, $owner = null ) {
1464 $this->assertOwnership( $fname, $owner );
1465 $this->assertTransactionRoundStage( self
::ROUND_APPROVED
);
1469 /** @noinspection PhpUnusedLocalVariableInspection */
1470 $scope = ScopedCallback
::newScopedIgnoreUserAbort(); // try to ignore client aborts
1472 $restore = ( $this->trxRoundId
!== false );
1473 $this->trxRoundId
= false;
1474 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1475 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1476 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1477 $this->forEachOpenMasterConnection(
1478 function ( IDatabase
$conn ) use ( $fname, &$failures ) {
1480 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1481 } catch ( DBError
$e ) {
1482 ( $this->errorLogger
)( $e );
1483 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1488 throw new DBTransactionError(
1490 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1494 // Unmark handles as participating in this explicit transaction round
1495 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1496 $this->undoTransactionRoundFlags( $conn );
1499 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
1502 public function runMasterTransactionIdleCallbacks( $fname = __METHOD__
, $owner = null ) {
1503 $this->assertOwnership( $fname, $owner );
1504 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1505 $type = IDatabase
::TRIGGER_COMMIT
;
1506 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1507 $type = IDatabase
::TRIGGER_ROLLBACK
;
1509 throw new DBTransactionError(
1511 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1515 $oldStage = $this->trxRoundStage
;
1516 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1518 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1519 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1520 $conn->setTrxEndCallbackSuppression( false );
1523 $e = null; // first exception
1524 $fname = __METHOD__
;
1525 // Loop until callbacks stop adding callbacks on other connections
1527 // Run any pending callbacks for each connection...
1528 $count = 0; // callback execution attempts
1529 $this->forEachOpenMasterConnection(
1530 function ( Database
$conn ) use ( $type, &$e, &$count ) {
1531 if ( $conn->trxLevel() ) {
1532 return; // retry in the next iteration, after commit() is called
1535 $count +
= $conn->runOnTransactionIdleCallbacks( $type );
1536 } catch ( Exception
$ex ) {
1541 // Clear out any active transactions left over from callbacks...
1542 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$e, $fname ) {
1543 if ( $conn->writesPending() ) {
1544 // A callback from another handle wrote to this one and DBO_TRX is set
1545 $this->queryLogger
->warning( $fname . ": found writes pending." );
1546 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1547 $this->queryLogger
->warning(
1548 $fname . ": found writes pending ($fnames).",
1550 'db_server' => $conn->getServer(),
1551 'db_name' => $conn->getDBname()
1554 } elseif ( $conn->trxLevel() ) {
1555 // A callback from another handle read from this one and DBO_TRX is set,
1556 // which can easily happen if there is only one DB (no replicas)
1557 $this->queryLogger
->debug( $fname . ": found empty transaction." );
1560 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1561 } catch ( Exception
$ex ) {
1565 } while ( $count > 0 );
1567 $this->trxRoundStage
= $oldStage;
1572 public function runMasterTransactionListenerCallbacks( $fname = __METHOD__
, $owner = null ) {
1573 $this->assertOwnership( $fname, $owner );
1574 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1575 $type = IDatabase
::TRIGGER_COMMIT
;
1576 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1577 $type = IDatabase
::TRIGGER_ROLLBACK
;
1579 throw new DBTransactionError(
1581 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1587 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1588 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1590 $conn->runTransactionListenerCallbacks( $type );
1591 } catch ( Exception
$ex ) {
1595 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1600 public function rollbackMasterChanges( $fname = __METHOD__
, $owner = null ) {
1601 $this->assertOwnership( $fname, $owner );
1603 $restore = ( $this->trxRoundId
!== false );
1604 $this->trxRoundId
= false;
1605 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1606 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1607 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1610 // Unmark handles as participating in this explicit transaction round
1611 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1612 $this->undoTransactionRoundFlags( $conn );
1615 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
1619 * @param string|string[] $stage
1620 * @throws DBTransactionError
1622 private function assertTransactionRoundStage( $stage ) {
1623 $stages = (array)$stage;
1625 if ( !in_array( $this->trxRoundStage
, $stages, true ) ) {
1626 $stageList = implode(
1628 array_map( function ( $v ) {
1632 throw new DBTransactionError(
1634 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1640 * @param string $fname
1641 * @param int|null $owner Owner ID of the caller
1642 * @throws DBTransactionError
1644 private function assertOwnership( $fname, $owner ) {
1645 if ( $this->ownerId
!== null && $owner !== $this->ownerId
) {
1646 throw new DBTransactionError(
1648 "$fname: LoadBalancer is owned by LBFactory #{$this->ownerId} (got '$owner')."
1654 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1656 * Some servers may have neither flag enabled, meaning that they opt out of such
1657 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1658 * when a DB server is used for something like simple key/value storage.
1660 * @param Database $conn
1662 private function applyTransactionRoundFlags( Database
$conn ) {
1663 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1664 return; // transaction rounds do not apply to these connections
1667 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1668 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1669 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1670 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1673 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1674 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1679 * @param Database $conn
1681 private function undoTransactionRoundFlags( Database
$conn ) {
1682 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1683 return; // transaction rounds do not apply to these connections
1686 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1687 $conn->setLBInfo( 'trxRoundId', false );
1690 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1691 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1695 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1696 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) use ( $fname ) {
1697 $conn->flushSnapshot( $fname );
1701 public function flushMasterSnapshots( $fname = __METHOD__
) {
1702 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1703 $conn->flushSnapshot( $fname );
1711 public function getTransactionRoundStage() {
1712 return $this->trxRoundStage
;
1715 public function hasMasterConnection() {
1716 return $this->isOpen( $this->getWriterIndex() );
1719 public function hasMasterChanges() {
1721 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1722 $pending |
= $conn->writesOrCallbacksPending();
1725 return (bool)$pending;
1728 public function lastMasterChangeTimestamp() {
1730 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1731 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1737 public function hasOrMadeRecentMasterChanges( $age = null ) {
1738 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1740 return ( $this->hasMasterChanges()
1741 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1744 public function pendingMasterChangeCallers() {
1746 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1747 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1753 public function getLaggedReplicaMode( $domain = false ) {
1755 // Avoid recursion if there is only one DB
1756 $this->getServerCount() > 1 &&
1757 // Avoid recursion if the (non-zero load) master DB was picked for generic reads
1758 $this->genericReadIndex
!== $this->getWriterIndex() &&
1759 // Stay in lagged replica mode during the load balancer instance lifetime
1760 !$this->laggedReplicaMode
1763 // Calling this method will set "laggedReplicaMode" as needed
1764 $this->getReaderIndex( false, $domain );
1765 } catch ( DBConnectionError
$e ) {
1766 // Avoid expensive re-connect attempts and failures
1767 $this->allReplicasDownMode
= true;
1768 $this->laggedReplicaMode
= true;
1772 return $this->laggedReplicaMode
;
1775 public function laggedReplicaUsed() {
1776 return $this->laggedReplicaMode
;
1782 * @deprecated Since 1.28; use laggedReplicaUsed()
1784 public function laggedSlaveUsed() {
1785 return $this->laggedReplicaUsed();
1788 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1789 if ( $this->readOnlyReason
!== false ) {
1790 return $this->readOnlyReason
;
1791 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1792 if ( $this->allReplicasDownMode
) {
1793 return 'The database has been automatically locked ' .
1794 'until the replica database servers become available';
1796 return 'The database has been automatically locked ' .
1797 'while the replica database servers catch up to the master.';
1799 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1800 return 'The database master is running in read-only mode.';
1807 * @param string $domain Domain ID, or false for the current domain
1808 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1811 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1812 $cache = $this->wanCache
;
1813 $masterServer = $this->getServerName( $this->getWriterIndex() );
1815 return (bool)$cache->getWithSetCallback(
1816 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1817 self
::TTL_CACHE_READONLY
,
1818 function () use ( $domain, $conn ) {
1819 $old = $this->trxProfiler
->setSilenced( true );
1821 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1822 $readOnly = (int)$dbw->serverIsReadOnly();
1824 $this->reuseConnection( $dbw );
1826 } catch ( DBError
$e ) {
1829 $this->trxProfiler
->setSilenced( $old );
1832 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1836 public function allowLagged( $mode = null ) {
1837 if ( $mode === null ) {
1838 return $this->allowLagged
;
1840 $this->allowLagged
= $mode;
1842 return $this->allowLagged
;
1845 public function pingAll() {
1847 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1848 if ( !$conn->ping() ) {
1856 public function forEachOpenConnection( $callback, array $params = [] ) {
1857 foreach ( $this->conns
as $connsByServer ) {
1858 foreach ( $connsByServer as $serverConns ) {
1859 foreach ( $serverConns as $conn ) {
1860 $callback( $conn, ...$params );
1866 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1867 $masterIndex = $this->getWriterIndex();
1868 foreach ( $this->conns
as $connsByServer ) {
1869 if ( isset( $connsByServer[$masterIndex] ) ) {
1870 /** @var IDatabase $conn */
1871 foreach ( $connsByServer[$masterIndex] as $conn ) {
1872 $callback( $conn, ...$params );
1878 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1879 foreach ( $this->conns
as $connsByServer ) {
1880 foreach ( $connsByServer as $i => $serverConns ) {
1881 if ( $i === $this->getWriterIndex() ) {
1882 continue; // skip master
1884 foreach ( $serverConns as $conn ) {
1885 $callback( $conn, ...$params );
1891 public function getMaxLag( $domain = false ) {
1896 if ( $this->getServerCount() <= 1 ) {
1897 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1900 $lagTimes = $this->getLagTimes( $domain );
1901 foreach ( $lagTimes as $i => $lag ) {
1902 if ( $this->genericLoads
[$i] > 0 && $lag > $maxLag ) {
1904 $host = $this->servers
[$i]['host'];
1909 return [ $host, $maxLag, $maxIndex ];
1912 public function getLagTimes( $domain = false ) {
1913 if ( $this->getServerCount() <= 1 ) {
1914 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1917 $knownLagTimes = []; // map of (server index => 0 seconds)
1918 $indexesWithLag = [];
1919 foreach ( $this->servers
as $i => $server ) {
1920 if ( empty( $server['is static'] ) ) {
1921 $indexesWithLag[] = $i; // DB server might have replication lag
1923 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1927 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1930 public function safeGetLag( IDatabase
$conn ) {
1931 if ( $this->getServerCount() <= 1 ) {
1934 return $conn->getLag();
1938 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
1939 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
1941 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1942 return true; // server is not a replica DB
1946 // Get the current master position, opening a connection if needed
1947 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1948 if ( $masterConn ) {
1949 $pos = $masterConn->getMasterPos();
1951 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1952 if ( !$masterConn ) {
1953 throw new DBReplicationWaitError(
1955 "Could not obtain a master database connection to get the position"
1958 $pos = $masterConn->getMasterPos();
1959 $this->closeConnection( $masterConn );
1963 if ( $pos instanceof DBMasterPos
) {
1964 $result = $conn->masterPosWait( $pos, $timeout );
1965 if ( $result == -1 ||
is_null( $result ) ) {
1966 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos}';
1967 $this->replLogger
->warning( $msg, [
1968 'host' => $conn->getServer(),
1970 'trace' => ( new RuntimeException() )->getTraceAsString()
1974 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
1978 $ok = false; // something is misconfigured
1979 $this->replLogger
->error(
1980 __METHOD__
. ': could not get master pos for {host}',
1982 'host' => $conn->getServer(),
1983 'trace' => ( new RuntimeException() )->getTraceAsString()
1991 public function setTransactionListener( $name, callable
$callback = null ) {
1993 $this->trxRecurringCallbacks
[$name] = $callback;
1995 unset( $this->trxRecurringCallbacks
[$name] );
1997 $this->forEachOpenMasterConnection(
1998 function ( IDatabase
$conn ) use ( $name, $callback ) {
1999 $conn->setTransactionListener( $name, $callback );
2004 public function setTableAliases( array $aliases ) {
2005 $this->tableAliases
= $aliases;
2008 public function setIndexAliases( array $aliases ) {
2009 $this->indexAliases
= $aliases;
2013 * @param string $prefix
2014 * @deprecated Since 1.33
2016 public function setDomainPrefix( $prefix ) {
2017 $this->setLocalDomainPrefix( $prefix );
2020 public function setLocalDomainPrefix( $prefix ) {
2021 // Find connections to explicit foreign domains still marked as in-use...
2023 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
2024 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
2025 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
2026 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
2027 $domainsInUse[] = $conn->getDomainID();
2031 // Do not switch connections to explicit foreign domains unless marked as safe
2032 if ( $domainsInUse ) {
2033 $domains = implode( ', ', $domainsInUse );
2034 throw new DBUnexpectedError( null,
2035 "Foreign domain connections are still in use ($domains)" );
2038 $this->setLocalDomain( new DatabaseDomain(
2039 $this->localDomain
->getDatabase(),
2040 $this->localDomain
->getSchema(),
2044 // Update the prefix for all local connections...
2045 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
2046 if ( !$db->getLBInfo( 'foreign' ) ) {
2047 $db->tablePrefix( $prefix );
2052 public function redefineLocalDomain( $domain ) {
2055 $this->setLocalDomain( DatabaseDomain
::newFromId( $domain ) );
2059 * @param DatabaseDomain $domain
2061 private function setLocalDomain( DatabaseDomain
$domain ) {
2062 $this->localDomain
= $domain;
2063 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
2064 // always true, gracefully handle the case when they fail to account for escaping.
2065 if ( $this->localDomain
->getTablePrefix() != '' ) {
2066 $this->localDomainIdAlias
=
2067 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
2069 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
2073 function __destruct() {
2074 // Avoid connection leaks for sanity
2080 * @deprecated since 1.29
2082 class_alias( LoadBalancer
::class, 'LoadBalancer' );