3 * Database load balancing manager
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 namespace Wikimedia\Rdbms
;
24 use Psr\Log\LoggerInterface
;
25 use Psr\Log\NullLogger
;
26 use Wikimedia\ScopedCallback
;
31 use UnexpectedValueException
;
32 use InvalidArgumentException
;
37 * Database connection, tracking, load balancing, and transaction manager for a cluster
41 class LoadBalancer
implements ILoadBalancer
{
42 /** @var ILoadMonitor */
44 /** @var callable|null Callback to run before the first connection attempt */
45 private $chronologyCallback;
48 /** @var WANObjectCache */
50 /** @var mixed Class name or object With profileIn/profileOut methods */
52 /** @var TransactionProfiler */
54 /** @var LoggerInterface */
56 /** @var LoggerInterface */
58 /** @var LoggerInterface */
60 /** @var LoggerInterface */
62 /** @var callable Exception logger */
64 /** @var callable Deprecation logger */
65 private $deprecationLogger;
67 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
70 /** @var Database[][][] Map of (connection category => server index => IDatabase[]) */
73 /** @var array[] Map of (server index => server config array) */
75 /** @var float[] Map of (server index => weight) */
77 /** @var array[] Map of (group => server index => weight) */
79 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
81 /** @var int Seconds to spend waiting on replica DB lag to resolve */
83 /** @var array The LoadMonitor configuration */
84 private $loadMonitorConfig;
85 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
86 private $localDomainIdAlias;
90 /** @var string Current server name */
92 /** @var bool Whether this PHP instance is for a CLI script */
94 /** @var string Agent name for query profiling */
97 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
98 private $tableAliases = [];
99 /** @var string[] Map of (index alias => index) */
100 private $indexAliases = [];
101 /** @var array[] Map of (name => callable) */
102 private $trxRecurringCallbacks = [];
104 /** @var Database DB connection object that caused a problem */
105 private $errorConnection;
106 /** @var int The generic (not query grouped) replica DB index (of $mServers) */
108 /** @var bool|DBMasterPos False if not set */
110 /** @var bool Whether the generic reader fell back to a lagged replica DB */
111 private $laggedReplicaMode = false;
112 /** @var bool Whether the generic reader fell back to a lagged replica DB */
113 private $allReplicasDownMode = false;
114 /** @var string The last DB selection or connection error */
115 private $lastError = 'Unknown error';
116 /** @var string|bool Reason the LB is read-only or false if not */
117 private $readOnlyReason = false;
118 /** @var int Total connections opened */
119 private $connsOpened = 0;
121 private $disabled = false;
122 /** @var bool Whether any connection has been attempted yet */
123 private $connectionAttempted = false;
125 /** @var string|bool String if a requested DBO_TRX transaction round is active */
126 private $trxRoundId = false;
127 /** @var string Stage of the current transaction round in the transaction round life-cycle */
128 private $trxRoundStage = self
::ROUND_CURSORY
;
130 /** @var string|null */
131 private $defaultGroup = null;
133 /** @var int Warn when this many connection are held */
134 const CONN_HELD_WARN_THRESHOLD
= 10;
136 /** @var int Default 'maxLag' when unspecified */
137 const MAX_LAG_DEFAULT
= 6;
138 /** @var int Default 'waitTimeout' when unspecified */
139 const MAX_WAIT_DEFAULT
= 10;
140 /** @var int Seconds to cache master server read-only status */
141 const TTL_CACHE_READONLY
= 5;
143 const KEY_LOCAL
= 'local';
144 const KEY_FOREIGN_FREE
= 'foreignFree';
145 const KEY_FOREIGN_INUSE
= 'foreignInUse';
147 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
148 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
149 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
151 /** @var string Transaction round, explicit or implicit, has not finished writing */
152 const ROUND_CURSORY
= 'cursory';
153 /** @var string Transaction round writes are complete and ready for pre-commit checks */
154 const ROUND_FINALIZED
= 'finalized';
155 /** @var string Transaction round passed final pre-commit checks */
156 const ROUND_APPROVED
= 'approved';
157 /** @var string Transaction round was committed and post-commit callbacks must be run */
158 const ROUND_COMMIT_CALLBACKS
= 'commit-callbacks';
159 /** @var string Transaction round was rolled back and post-rollback callbacks must be run */
160 const ROUND_ROLLBACK_CALLBACKS
= 'rollback-callbacks';
161 /** @var string Transaction round encountered an error */
162 const ROUND_ERROR
= 'error';
164 public function __construct( array $params ) {
165 if ( !isset( $params['servers'] ) ) {
166 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
168 $this->servers
= $params['servers'];
169 foreach ( $this->servers
as $i => $server ) {
171 $this->servers
[$i]['master'] = true;
173 $this->servers
[$i]['replica'] = true;
177 $localDomain = isset( $params['localDomain'] )
178 ? DatabaseDomain
::newFromId( $params['localDomain'] )
179 : DatabaseDomain
::newUnspecified();
180 $this->setLocalDomain( $localDomain );
182 $this->waitTimeout
= $params['waitTimeout'] ?? self
::MAX_WAIT_DEFAULT
;
184 $this->readIndex
= -1;
186 // Connection were transaction rounds may be applied
187 self
::KEY_LOCAL
=> [],
188 self
::KEY_FOREIGN_INUSE
=> [],
189 self
::KEY_FOREIGN_FREE
=> [],
190 // Auto-committing counterpart connections that ignore transaction rounds
191 self
::KEY_LOCAL_NOROUND
=> [],
192 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
193 self
::KEY_FOREIGN_FREE_NOROUND
=> []
196 $this->waitForPos
= false;
197 $this->allowLagged
= false;
199 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
200 $this->readOnlyReason
= $params['readOnlyReason'];
203 $this->maxLag
= $params['maxLag'] ?? self
::MAX_LAG_DEFAULT
;
205 $this->loadMonitorConfig
= $params['loadMonitor'] ??
[ 'class' => 'LoadMonitorNull' ];
206 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
208 foreach ( $params['servers'] as $i => $server ) {
209 $this->loads
[$i] = $server['load'];
210 if ( isset( $server['groupLoads'] ) ) {
211 foreach ( $server['groupLoads'] as $group => $ratio ) {
212 if ( !isset( $this->groupLoads
[$group] ) ) {
213 $this->groupLoads
[$group] = [];
215 $this->groupLoads
[$group][$i] = $ratio;
220 $this->srvCache
= $params['srvCache'] ??
new EmptyBagOStuff();
221 $this->wanCache
= $params['wanCache'] ?? WANObjectCache
::newEmpty();
222 $this->profiler
= $params['profiler'] ??
null;
223 $this->trxProfiler
= $params['trxProfiler'] ??
new TransactionProfiler();
225 $this->errorLogger
= $params['errorLogger'] ??
function ( Exception
$e ) {
226 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
228 $this->deprecationLogger
= $params['deprecationLogger'] ??
function ( $msg ) {
229 trigger_error( $msg, E_USER_DEPRECATED
);
232 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
233 $this->$key = $params[$key] ??
new NullLogger();
236 $this->hostname
= $params['hostname'] ??
( gethostname() ?
: 'unknown' );
237 $this->cliMode
= $params['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
238 $this->agent
= $params['agent'] ??
'';
240 if ( isset( $params['chronologyCallback'] ) ) {
241 $this->chronologyCallback
= $params['chronologyCallback'];
244 if ( isset( $params['roundStage'] ) ) {
245 if ( $params['roundStage'] === self
::STAGE_POSTCOMMIT_CALLBACKS
) {
246 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
247 } elseif ( $params['roundStage'] === self
::STAGE_POSTROLLBACK_CALLBACKS
) {
248 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
252 $this->defaultGroup
= $params['defaultGroup'] ??
null;
255 public function getLocalDomainID() {
256 return $this->localDomain
->getId();
259 public function resolveDomainID( $domain ) {
260 return ( $domain !== false ) ?
(string)$domain : $this->getLocalDomainID();
264 * Get a LoadMonitor instance
266 * @return ILoadMonitor
268 private function getLoadMonitor() {
269 if ( !isset( $this->loadMonitor
) ) {
271 'LoadMonitor' => LoadMonitor
::class,
272 'LoadMonitorNull' => LoadMonitorNull
::class,
273 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
276 $class = $this->loadMonitorConfig
['class'];
277 if ( isset( $compat[$class] ) ) {
278 $class = $compat[$class];
281 $this->loadMonitor
= new $class(
282 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
283 $this->loadMonitor
->setLogger( $this->replLogger
);
286 return $this->loadMonitor
;
290 * @param array $loads
291 * @param bool|string $domain Domain to get non-lagged for
292 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
293 * @return bool|int|string
295 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
296 $lags = $this->getLagTimes( $domain );
298 # Unset excessively lagged servers
299 foreach ( $lags as $i => $lag ) {
301 # How much lag this server nominally is allowed to have
302 $maxServerLag = $this->servers
[$i]['max lag'] ??
$this->maxLag
; // default
303 # Constrain that futher by $maxLag argument
304 $maxServerLag = min( $maxServerLag, $maxLag );
306 $host = $this->getServerName( $i );
307 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
308 $this->replLogger
->debug(
310 ": server {host} is not replicating?", [ 'host' => $host ] );
312 } elseif ( $lag > $maxServerLag ) {
313 $this->replLogger
->debug(
315 ": server {host} has {lag} seconds of lag (>= {maxlag})",
316 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
323 # Find out if all the replica DBs with non-zero load are lagged
325 foreach ( $loads as $load ) {
329 # No appropriate DB servers except maybe the master and some replica DBs with zero load
330 # Do NOT use the master
331 # Instead, this function will return false, triggering read-only mode,
332 # and a lagged replica DB will be used instead.
336 if ( count( $loads ) == 0 ) {
340 # Return a random representative of the remainder
341 return ArrayUtils
::pickRandom( $loads );
344 public function getReaderIndex( $group = false, $domain = false ) {
345 if ( count( $this->servers
) == 1 ) {
346 // Skip the load balancing if there's only one server
347 return $this->getWriterIndex();
348 } elseif ( $group === false && $this->readIndex
>= 0 ) {
349 // Shortcut if the generic reader index was already cached
350 return $this->readIndex
;
353 if ( $group !== false ) {
354 // Use the server weight array for this load group
355 if ( isset( $this->groupLoads
[$group] ) ) {
356 $loads = $this->groupLoads
[$group];
358 // No loads for this group, return false and the caller can use some other group
359 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
364 // Use the generic load group
365 $loads = $this->loads
;
368 // Scale the configured load ratios according to each server's load and state
369 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
371 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
372 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
373 if ( $i === false ) {
374 // Replica DB connection unsuccessful
378 if ( $this->waitForPos
&& $i != $this->getWriterIndex() ) {
379 // Before any data queries are run, wait for the server to catch up to the
380 // specified position. This is used to improve session consistency. Note that
381 // when LoadBalancer::waitFor() sets "waitForPos", the waiting triggers here,
382 // so update laggedReplicaMode as needed for consistency.
383 if ( !$this->doWait( $i ) ) {
384 $laggedReplicaMode = true;
388 if ( $this->readIndex
<= 0 && $this->loads
[$i] > 0 && $group === false ) {
389 // Cache the generic reader index for future ungrouped DB_REPLICA handles
390 $this->readIndex
= $i;
391 // Record if the generic reader index is in "lagged replica DB" mode
392 if ( $laggedReplicaMode ) {
393 $this->laggedReplicaMode
= true;
397 $serverName = $this->getServerName( $i );
398 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
404 * @param array $loads List of server weights
405 * @param string|bool $domain
406 * @return array (reader index, lagged replica mode) or false on failure
408 private function pickReaderIndex( array $loads, $domain = false ) {
409 if ( $loads === [] ) {
410 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
413 /** @var int|bool $i Index of selected server */
415 /** @var bool $laggedReplicaMode Whether server is considered lagged */
416 $laggedReplicaMode = false;
418 // Quickly look through the available servers for a server that meets criteria...
419 $currentLoads = $loads;
420 while ( count( $currentLoads ) ) {
421 if ( $this->allowLagged ||
$laggedReplicaMode ) {
422 $i = ArrayUtils
::pickRandom( $currentLoads );
425 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
426 // "chronologyCallback" sets "waitForPos" for session consistency.
427 // This triggers doWait() after connect, so it's especially good to
428 // avoid lagged servers so as to avoid excessive delay in that method.
429 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
430 // Aim for <= 1 second of waiting (being too picky can backfire)
431 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
433 if ( $i === false ) {
434 // Any server with less lag than it's 'max lag' param is preferable
435 $i = $this->getRandomNonLagged( $currentLoads, $domain );
437 if ( $i === false && count( $currentLoads ) != 0 ) {
438 // All replica DBs lagged. Switch to read-only mode
439 $this->replLogger
->error(
440 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
441 $i = ArrayUtils
::pickRandom( $currentLoads );
442 $laggedReplicaMode = true;
446 if ( $i === false ) {
447 // pickRandom() returned false.
448 // This is permanent and means the configuration or the load monitor
449 // wants us to return false.
450 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
452 return [ false, false ];
455 $serverName = $this->getServerName( $i );
456 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
458 $conn = $this->openConnection( $i, $domain );
460 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
461 unset( $currentLoads[$i] ); // avoid this server next iteration
466 // Decrement reference counter, we are finished with this connection.
467 // It will be incremented for the caller later.
468 if ( $domain !== false ) {
469 $this->reuseConnection( $conn );
472 // Return this server
476 // If all servers were down, quit now
477 if ( $currentLoads === [] ) {
478 $this->connLogger
->error( __METHOD__
. ": all servers down" );
481 return [ $i, $laggedReplicaMode ];
484 public function waitFor( $pos ) {
485 $oldPos = $this->waitForPos
;
487 $this->waitForPos
= $pos;
488 // If a generic reader connection was already established, then wait now
489 $i = $this->readIndex
;
490 if ( ( $i > 0 ) && !$this->doWait( $i ) ) {
491 $this->laggedReplicaMode
= true;
494 // Restore the older position if it was higher since this is used for lag-protection
495 $this->setWaitForPositionIfHigher( $oldPos );
499 public function waitForOne( $pos, $timeout = null ) {
500 $oldPos = $this->waitForPos
;
502 $this->waitForPos
= $pos;
504 $i = $this->readIndex
;
506 // Pick a generic replica DB if there isn't one yet
507 $readLoads = $this->loads
;
508 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
509 $readLoads = array_filter( $readLoads ); // with non-zero load
510 $i = ArrayUtils
::pickRandom( $readLoads );
514 $ok = $this->doWait( $i, true, $timeout );
516 $ok = true; // no applicable loads
519 # Restore the old position, as this is not used for lag-protection but for throttling
520 $this->waitForPos
= $oldPos;
526 public function waitForAll( $pos, $timeout = null ) {
527 $timeout = $timeout ?
: $this->waitTimeout
;
529 $oldPos = $this->waitForPos
;
531 $this->waitForPos
= $pos;
532 $serverCount = count( $this->servers
);
535 for ( $i = 1; $i < $serverCount; $i++
) {
536 if ( $this->loads
[$i] > 0 ) {
537 $start = microtime( true );
538 $ok = $this->doWait( $i, true, $timeout ) && $ok;
539 $timeout -= intval( microtime( true ) - $start );
540 if ( $timeout <= 0 ) {
541 break; // timeout reached
546 # Restore the old position, as this is not used for lag-protection but for throttling
547 $this->waitForPos
= $oldPos;
554 * @param DBMasterPos|bool $pos
556 private function setWaitForPositionIfHigher( $pos ) {
561 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
562 $this->waitForPos
= $pos;
566 public function getAnyOpenConnection( $i, $flags = 0 ) {
567 $i = ( $i === self
::DB_MASTER
) ?
$this->getWriterIndex() : $i;
568 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
570 foreach ( $this->conns
as $connsByServer ) {
571 if ( $i === self
::DB_REPLICA
) {
572 $indexes = array_keys( $connsByServer );
574 $indexes = isset( $connsByServer[$i] ) ?
[ $i ] : [];
577 foreach ( $indexes as $index ) {
578 foreach ( $connsByServer[$index] as $conn ) {
579 if ( !$conn->isOpen() ) {
580 continue; // some sort of error occured?
582 if ( !$autocommit ||
$conn->getLBInfo( 'autoCommitOnly' ) ) {
593 * Wait for a given replica DB to catch up to the master pos stored in $this
594 * @param int $index Server index
595 * @param bool $open Check the server even if a new connection has to be made
596 * @param int|null $timeout Max seconds to wait; default is "waitTimeout" given to __construct()
599 protected function doWait( $index, $open = false, $timeout = null ) {
600 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
602 // Check if we already know that the DB has reached this point
603 $server = $this->getServerName( $index );
604 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
605 /** @var DBMasterPos $knownReachedPos */
606 $knownReachedPos = $this->srvCache
->get( $key );
608 $knownReachedPos instanceof DBMasterPos
&&
609 $knownReachedPos->hasReached( $this->waitForPos
)
611 $this->replLogger
->debug(
613 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
614 [ 'dbserver' => $server ]
619 // Find a connection to wait on, creating one if needed and allowed
620 $close = false; // close the connection afterwards
621 $conn = $this->getAnyOpenConnection( $index );
624 $this->replLogger
->debug(
625 __METHOD__
. ': no connection open for {dbserver}',
626 [ 'dbserver' => $server ]
631 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
633 $this->replLogger
->warning(
634 __METHOD__
. ': failed to connect to {dbserver}',
635 [ 'dbserver' => $server ]
640 // Avoid connection spam in waitForAll() when connections
641 // are made just for the sake of doing this lag check.
646 $this->replLogger
->info(
648 ': waiting for replica DB {dbserver} to catch up...',
649 [ 'dbserver' => $server ]
652 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
654 if ( $result === null ) {
655 $this->replLogger
->warning(
656 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
659 'pos' => $this->waitForPos
,
660 'trace' => ( new RuntimeException() )->getTraceAsString()
664 } elseif ( $result == -1 ) {
665 $this->replLogger
->warning(
666 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
669 'pos' => $this->waitForPos
,
670 'trace' => ( new RuntimeException() )->getTraceAsString()
675 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
677 // Remember that the DB reached this point
678 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
682 $this->closeConnection( $conn );
688 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
689 if ( $i === null ||
$i === false ) {
690 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
691 ' with invalid server index' );
694 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
695 $domain = false; // local connection requested
698 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) === self
::CONN_TRX_AUTOCOMMIT
) {
699 // Assuming all servers are of the same type (or similar), which is overwhelmingly
700 // the case, use the master server information to get the attributes. The information
701 // for $i cannot be used since it might be DB_REPLICA, which might require connection
702 // attempts in order to be resolved into a real server index.
703 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
704 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
705 // Callers sometimes want to (a) escape REPEATABLE-READ stateness without locking
706 // rows (e.g. FOR UPDATE) or (b) make small commits during a larger transactions
707 // to reduce lock contention. None of these apply for sqlite and using separate
708 // connections just causes self-deadlocks.
709 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
710 $this->connLogger
->info( __METHOD__
.
711 ': ignoring CONN_TRX_AUTOCOMMIT to avoid deadlocks.' );
715 // Check one "group" per default: the generic pool
716 $defaultGroups = $this->defaultGroup ?
[ $this->defaultGroup
] : [ false ];
718 $groups = ( $groups === false ||
$groups === [] )
722 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
723 $oldConnsOpened = $this->connsOpened
; // connections open now
725 if ( $i == self
::DB_MASTER
) {
726 $i = $this->getWriterIndex();
727 } elseif ( $i == self
::DB_REPLICA
) {
728 # Try to find an available server in any the query groups (in order)
729 foreach ( $groups as $group ) {
730 $groupIndex = $this->getReaderIndex( $group, $domain );
731 if ( $groupIndex !== false ) {
738 # Operation-based index
739 if ( $i == self
::DB_REPLICA
) {
740 $this->lastError
= 'Unknown error'; // reset error string
741 # Try the general server pool if $groups are unavailable.
742 $i = ( $groups === [ false ] )
743 ?
false // don't bother with this if that is what was tried above
744 : $this->getReaderIndex( false, $domain );
745 # Couldn't find a working server in getReaderIndex()?
746 if ( $i === false ) {
747 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
748 // Throw an exception
749 $this->reportConnectionError();
750 return null; // not reached
754 # Now we have an explicit index into the servers array
755 $conn = $this->openConnection( $i, $domain, $flags );
757 // Throw an exception
758 $this->reportConnectionError();
759 return null; // not reached
762 # Profile any new connections that happen
763 if ( $this->connsOpened
> $oldConnsOpened ) {
764 $host = $conn->getServer();
765 $dbname = $conn->getDBname();
766 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
770 # Make master-requested DB handles inherit any read-only mode setting
771 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
777 public function reuseConnection( IDatabase
$conn ) {
778 $serverIndex = $conn->getLBInfo( 'serverIndex' );
779 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
780 if ( $serverIndex === null ||
$refCount === null ) {
782 * This can happen in code like:
783 * foreach ( $dbs as $db ) {
784 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
786 * $lb->reuseConnection( $conn );
788 * When a connection to the local DB is opened in this way, reuseConnection()
792 } elseif ( $conn instanceof DBConnRef
) {
793 // DBConnRef already handles calling reuseConnection() and only passes the live
794 // Database instance to this method. Any caller passing in a DBConnRef is broken.
795 $this->connLogger
->error(
796 __METHOD__
. ": got DBConnRef instance.\n" .
797 ( new RuntimeException() )->getTraceAsString() );
802 if ( $this->disabled
) {
803 return; // DBConnRef handle probably survived longer than the LoadBalancer
806 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
807 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
808 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
810 $connFreeKey = self
::KEY_FOREIGN_FREE
;
811 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
814 $domain = $conn->getDomainID();
815 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
816 throw new InvalidArgumentException( __METHOD__
.
817 ": connection $serverIndex/$domain not found; it may have already been freed." );
818 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
819 throw new InvalidArgumentException( __METHOD__
.
820 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
823 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
824 if ( $refCount <= 0 ) {
825 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
826 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
827 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
828 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
830 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
832 $this->connLogger
->debug( __METHOD__
.
833 ": reference count for $serverIndex/$domain reduced to $refCount" );
837 public function getConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
838 $domain = $this->resolveDomainID( $domain );
840 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain, $flags ) );
843 public function getLazyConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
844 $domain = $this->resolveDomainID( $domain );
846 return new DBConnRef( $this, [ $db, $groups, $domain, $flags ] );
849 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
850 $domain = $this->resolveDomainID( $domain );
852 return new MaintainableDBConnRef(
853 $this, $this->getConnection( $db, $groups, $domain, $flags ) );
856 public function openConnection( $i, $domain = false, $flags = 0 ) {
857 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
858 $domain = false; // local connection requested
861 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
862 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
863 // Load any "waitFor" positions before connecting so that doWait() is triggered
864 $this->connectionAttempted
= true;
865 ( $this->chronologyCallback
)( $this );
868 // Check if an auto-commit connection is being requested. If so, it will not reuse the
869 // main set of DB connections but rather its own pool since:
870 // a) those are usually set to implicitly use transaction rounds via DBO_TRX
871 // b) those must support the use of explicit transaction rounds via beginMasterChanges()
872 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
874 if ( $domain !== false ) {
875 // Connection is to a foreign domain
876 $conn = $this->openForeignConnection( $i, $domain, $flags );
878 // Connection is to the local domain
879 $conn = $this->openLocalConnection( $i, $flags );
882 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
883 // Connection was made but later unrecoverably lost for some reason.
884 // Do not return a handle that will just throw exceptions on use,
885 // but let the calling code (e.g. getReaderIndex) try another server.
886 // See DatabaseMyslBase::ping() for how this can happen.
887 $this->errorConnection
= $conn;
891 if ( $autoCommit && $conn instanceof IDatabase
) {
892 if ( $conn->trxLevel() ) { // sanity
893 throw new DBUnexpectedError(
895 __METHOD__
. ': CONN_TRX_AUTOCOMMIT handle has a transaction.'
899 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
906 * Open a connection to a local DB, or return one if it is already open.
908 * On error, returns false, and the connection which caused the
909 * error will be available via $this->errorConnection.
911 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
913 * @param int $i Server index
914 * @param int $flags Class CONN_* constant bitfield
917 private function openLocalConnection( $i, $flags = 0 ) {
918 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
920 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
921 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
922 $conn = $this->conns
[$connKey][$i][0];
924 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
925 throw new InvalidArgumentException( "No server with index '$i'." );
927 // Open a new connection
928 $server = $this->servers
[$i];
929 $server['serverIndex'] = $i;
930 $server['autoCommitOnly'] = $autoCommit;
931 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
932 $host = $this->getServerName( $i );
933 if ( $conn->isOpen() ) {
934 $this->connLogger
->debug(
935 __METHOD__
. ": connected to database $i at '$host'." );
936 $this->conns
[$connKey][$i][0] = $conn;
938 $this->connLogger
->warning(
939 __METHOD__
. ": failed to connect to database $i at '$host'." );
940 $this->errorConnection
= $conn;
945 // Final sanity check to make sure the right domain is selected
947 $conn instanceof IDatabase
&&
948 !$this->localDomain
->isCompatible( $conn->getDomainID() )
950 throw new UnexpectedValueException(
951 "Got connection to '{$conn->getDomainID()}', " .
952 "but expected local domain ('{$this->localDomain}')." );
959 * Open a connection to a foreign DB, or return one if it is already open.
961 * Increments a reference count on the returned connection which locks the
962 * connection to the requested domain. This reference count can be
963 * decremented by calling reuseConnection().
965 * If a connection is open to the appropriate server already, but with the wrong
966 * database, it will be switched to the right database and returned, as long as
967 * it has been freed first with reuseConnection().
969 * On error, returns false, and the connection which caused the
970 * error will be available via $this->errorConnection.
972 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
974 * @param int $i Server index
975 * @param string $domain Domain ID to open
976 * @param int $flags Class CONN_* constant bitfield
977 * @return Database|bool Returns false on connection error
978 * @throws DBError When database selection fails
980 private function openForeignConnection( $i, $domain, $flags = 0 ) {
981 $domainInstance = DatabaseDomain
::newFromId( $domain );
982 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
985 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
986 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
988 $connFreeKey = self
::KEY_FOREIGN_FREE
;
989 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
992 /** @var Database $conn */
995 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
996 // Reuse an in-use connection for the same domain
997 $conn = $this->conns
[$connInUseKey][$i][$domain];
998 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
999 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
1000 // Reuse a free connection for the same domain
1001 $conn = $this->conns
[$connFreeKey][$i][$domain];
1002 unset( $this->conns
[$connFreeKey][$i][$domain] );
1003 $this->conns
[$connInUseKey][$i][$domain] = $conn;
1004 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
1005 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
1006 // Reuse a free connection from another domain if possible
1007 foreach ( $this->conns
[$connFreeKey][$i] as $oldDomain => $conn ) {
1008 if ( $domainInstance->getDatabase() !== null ) {
1009 // Check if changing the database will require a new connection.
1010 // In that case, leave the connection handle alone and keep looking.
1011 // This prevents connections from being closed mid-transaction and can
1012 // also avoid overhead if the same database will later be requested.
1014 $conn->databasesAreIndependent() &&
1015 $conn->getDBname() !== $domainInstance->getDatabase()
1019 // Select the new database, schema, and prefix
1020 $conn->selectDomain( $domainInstance );
1022 // Stay on the current database, but update the schema/prefix
1023 $conn->dbSchema( $domainInstance->getSchema() );
1024 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1026 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
1027 // Note that if $domain is an empty string, getDomainID() might not match it
1028 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1029 $this->connLogger
->debug( __METHOD__
.
1030 ": reusing free connection from $oldDomain for $domain" );
1036 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
1037 throw new InvalidArgumentException( "No server with index '$i'." );
1039 // Open a new connection
1040 $server = $this->servers
[$i];
1041 $server['serverIndex'] = $i;
1042 $server['foreignPoolRefCount'] = 0;
1043 $server['foreign'] = true;
1044 $server['autoCommitOnly'] = $autoCommit;
1045 $conn = $this->reallyOpenConnection( $server, $domainInstance );
1046 if ( !$conn->isOpen() ) {
1047 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
1048 $this->errorConnection
= $conn;
1051 // Note that if $domain is an empty string, getDomainID() might not match it
1052 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1053 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1057 if ( $conn instanceof IDatabase
) {
1058 // Final sanity check to make sure the right domain is selected
1059 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1060 throw new UnexpectedValueException(
1061 "Got connection to '{$conn->getDomainID()}', but expected '$domain'." );
1063 // Increment reference count
1064 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1065 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1071 public function getServerAttributes( $i ) {
1072 return Database
::attributesFromType(
1073 $this->getServerType( $i ),
1074 $this->servers
[$i]['driver'] ??
null
1079 * Test if the specified index represents an open connection
1081 * @param int $index Server index
1085 private function isOpen( $index ) {
1086 if ( !is_int( $index ) ) {
1090 return (bool)$this->getAnyOpenConnection( $index );
1094 * Open a new network connection to a server (uncached)
1096 * Returns a Database object whether or not the connection was successful.
1098 * @param array $server
1099 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
1101 * @throws DBAccessError
1102 * @throws InvalidArgumentException
1104 protected function reallyOpenConnection( array $server, DatabaseDomain
$domain ) {
1105 if ( $this->disabled
) {
1106 throw new DBAccessError();
1109 if ( $domain->getDatabase() === null ) {
1110 // The database domain does not specify a DB name and some database systems require a
1111 // valid DB specified on connection. The $server configuration array contains a default
1112 // DB name to use for connections in such cases.
1113 if ( $server['type'] === 'mysql' ) {
1114 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1115 // and the DB name in $server might not exist due to legacy reasons (the default
1116 // domain used to ignore the local LB domain, even when mismatched).
1117 $server['dbname'] = null;
1120 $server['dbname'] = $domain->getDatabase();
1123 if ( $domain->getSchema() !== null ) {
1124 $server['schema'] = $domain->getSchema();
1127 // It is always possible to connect with any prefix, even the empty string
1128 $server['tablePrefix'] = $domain->getTablePrefix();
1130 // Let the handle know what the cluster master is (e.g. "db1052")
1131 $masterName = $this->getServerName( $this->getWriterIndex() );
1132 $server['clusterMasterHost'] = $masterName;
1134 // Log when many connection are made on requests
1135 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
1136 $this->perfLogger
->warning( __METHOD__
. ": " .
1137 "{$this->connsOpened}+ connections made (master=$masterName)" );
1140 $server['srvCache'] = $this->srvCache
;
1141 // Set loggers and profilers
1142 $server['connLogger'] = $this->connLogger
;
1143 $server['queryLogger'] = $this->queryLogger
;
1144 $server['errorLogger'] = $this->errorLogger
;
1145 $server['deprecationLogger'] = $this->deprecationLogger
;
1146 $server['profiler'] = $this->profiler
;
1147 $server['trxProfiler'] = $this->trxProfiler
;
1148 // Use the same agent and PHP mode for all DB handles
1149 $server['cliMode'] = $this->cliMode
;
1150 $server['agent'] = $this->agent
;
1151 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1152 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1153 $server['flags'] = $server['flags'] ?? IDatabase
::DBO_DEFAULT
;
1155 // Create a live connection object
1157 $db = Database
::factory( $server['type'], $server );
1158 } catch ( DBConnectionError
$e ) {
1159 // FIXME: This is probably the ugliest thing I have ever done to
1160 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1164 $db->setLBInfo( $server );
1165 $db->setLazyMasterHandle(
1166 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1168 $db->setTableAliases( $this->tableAliases
);
1169 $db->setIndexAliases( $this->indexAliases
);
1171 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1172 if ( $this->trxRoundId
!== false ) {
1173 $this->applyTransactionRoundFlags( $db );
1175 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1176 $db->setTransactionListener( $name, $callback );
1184 * @throws DBConnectionError
1186 private function reportConnectionError() {
1187 $conn = $this->errorConnection
; // the connection which caused the error
1189 'method' => __METHOD__
,
1190 'last_error' => $this->lastError
,
1193 if ( $conn instanceof IDatabase
) {
1194 $context['db_server'] = $conn->getServer();
1195 $this->connLogger
->warning(
1196 __METHOD__
. ": connection error: {last_error} ({db_server})",
1200 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1202 // No last connection, probably due to all servers being too busy
1203 $this->connLogger
->error(
1205 ": LB failure with no last connection. Connection error: {last_error}",
1209 // If all servers were busy, "lastError" will contain something sensible
1210 throw new DBConnectionError( null, $this->lastError
);
1214 public function getWriterIndex() {
1218 public function haveIndex( $i ) {
1219 return array_key_exists( $i, $this->servers
);
1222 public function isNonZeroLoad( $i ) {
1223 return array_key_exists( $i, $this->servers
) && $this->loads
[$i] != 0;
1226 public function getServerCount() {
1227 return count( $this->servers
);
1230 public function getServerName( $i ) {
1231 $name = $this->servers
[$i]['hostName'] ??
$this->servers
[$i]['host'] ??
'';
1233 return ( $name != '' ) ?
$name : 'localhost';
1236 public function getServerInfo( $i ) {
1237 return $this->servers
[$i] ??
false;
1240 public function getServerType( $i ) {
1241 return $this->servers
[$i]['type'] ??
'unknown';
1244 public function getMasterPos() {
1245 # If this entire request was served from a replica DB without opening a connection to the
1246 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1247 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1248 if ( !$masterConn ) {
1249 $serverCount = count( $this->servers
);
1250 for ( $i = 1; $i < $serverCount; $i++
) {
1251 $conn = $this->getAnyOpenConnection( $i );
1253 return $conn->getReplicaPos();
1257 return $masterConn->getMasterPos();
1263 public function disable() {
1265 $this->disabled
= true;
1268 public function closeAll() {
1269 $fname = __METHOD__
;
1270 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( $fname ) {
1271 $host = $conn->getServer();
1272 $this->connLogger
->debug(
1273 $fname . ": closing connection to database '$host'." );
1278 self
::KEY_LOCAL
=> [],
1279 self
::KEY_FOREIGN_INUSE
=> [],
1280 self
::KEY_FOREIGN_FREE
=> [],
1281 self
::KEY_LOCAL_NOROUND
=> [],
1282 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1283 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1285 $this->connsOpened
= 0;
1288 public function closeConnection( IDatabase
$conn ) {
1289 if ( $conn instanceof DBConnRef
) {
1290 // Avoid calling close() but still leaving the handle in the pool
1291 throw new RuntimeException( __METHOD__
. ': got DBConnRef instance.' );
1294 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1295 foreach ( $this->conns
as $type => $connsByServer ) {
1296 if ( !isset( $connsByServer[$serverIndex] ) ) {
1300 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1301 if ( $conn === $trackedConn ) {
1302 $host = $this->getServerName( $i );
1303 $this->connLogger
->debug(
1304 __METHOD__
. ": closing connection to database $i at '$host'." );
1305 unset( $this->conns
[$type][$serverIndex][$i] );
1306 --$this->connsOpened
;
1315 public function commitAll( $fname = __METHOD__
) {
1316 $this->commitMasterChanges( $fname );
1317 $this->flushMasterSnapshots( $fname );
1318 $this->flushReplicaSnapshots( $fname );
1321 public function finalizeMasterChanges() {
1322 $this->assertTransactionRoundStage( [ self
::ROUND_CURSORY
, self
::ROUND_FINALIZED
] );
1324 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1325 // Loop until callbacks stop adding callbacks on other connections
1328 $count = 0; // callbacks execution attempts
1329 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$count ) {
1330 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1331 // Any error should cause all (peer) transactions to be rolled back together.
1332 $count +
= $conn->runOnTransactionPreCommitCallbacks();
1335 } while ( $count > 0 );
1336 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1337 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1338 $conn->setTrxEndCallbackSuppression( true );
1340 $this->trxRoundStage
= self
::ROUND_FINALIZED
;
1345 public function approveMasterChanges( array $options ) {
1346 $this->assertTransactionRoundStage( self
::ROUND_FINALIZED
);
1348 $limit = $options['maxWriteDuration'] ??
0;
1350 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1351 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1352 // If atomic sections or explicit transactions are still open, some caller must have
1353 // caught an exception but failed to properly rollback any changes. Detect that and
1354 // throw and error (causing rollback).
1355 $conn->assertNoOpenTransactions();
1356 // Assert that the time to replicate the transaction will be sane.
1357 // If this fails, then all DB transactions will be rollback back together.
1358 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1359 if ( $limit > 0 && $time > $limit ) {
1360 throw new DBTransactionSizeError(
1362 "Transaction spent $time second(s) in writes, exceeding the limit of $limit.",
1366 // If a connection sits idle while slow queries execute on another, that connection
1367 // may end up dropped before the commit round is reached. Ping servers to detect this.
1368 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1369 throw new DBTransactionError(
1371 "A connection to the {$conn->getDBname()} database was lost before commit."
1375 $this->trxRoundStage
= self
::ROUND_APPROVED
;
1378 public function beginMasterChanges( $fname = __METHOD__
) {
1379 if ( $this->trxRoundId
!== false ) {
1380 throw new DBTransactionError(
1382 "$fname: Transaction round '{$this->trxRoundId}' already started."
1385 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
1387 // Clear any empty transactions (no writes/callbacks) from the implicit round
1388 $this->flushMasterSnapshots( $fname );
1390 $this->trxRoundId
= $fname;
1391 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1392 // Mark applicable handles as participating in this explicit transaction round.
1393 // For each of these handles, any writes and callbacks will be tied to a single
1394 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1395 // are part of an en masse commit or an en masse rollback.
1396 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1397 $this->applyTransactionRoundFlags( $conn );
1399 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1402 public function commitMasterChanges( $fname = __METHOD__
) {
1403 $this->assertTransactionRoundStage( self
::ROUND_APPROVED
);
1407 /** @noinspection PhpUnusedLocalVariableInspection */
1408 $scope = ScopedCallback
::newScopedIgnoreUserAbort(); // try to ignore client aborts
1410 $restore = ( $this->trxRoundId
!== false );
1411 $this->trxRoundId
= false;
1412 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1413 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1414 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1415 $this->forEachOpenMasterConnection(
1416 function ( IDatabase
$conn ) use ( $fname, &$failures ) {
1418 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1419 } catch ( DBError
$e ) {
1420 ( $this->errorLogger
)( $e );
1421 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1426 throw new DBTransactionError(
1428 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1432 // Unmark handles as participating in this explicit transaction round
1433 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1434 $this->undoTransactionRoundFlags( $conn );
1437 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
1440 public function runMasterTransactionIdleCallbacks() {
1441 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1442 $type = IDatabase
::TRIGGER_COMMIT
;
1443 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1444 $type = IDatabase
::TRIGGER_ROLLBACK
;
1446 throw new DBTransactionError(
1448 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1452 $oldStage = $this->trxRoundStage
;
1453 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1455 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1456 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1457 $conn->setTrxEndCallbackSuppression( false );
1460 $e = null; // first exception
1461 $fname = __METHOD__
;
1462 // Loop until callbacks stop adding callbacks on other connections
1464 // Run any pending callbacks for each connection...
1465 $count = 0; // callback execution attempts
1466 $this->forEachOpenMasterConnection(
1467 function ( Database
$conn ) use ( $type, &$e, &$count ) {
1468 if ( $conn->trxLevel() ) {
1469 return; // retry in the next iteration, after commit() is called
1472 $count +
= $conn->runOnTransactionIdleCallbacks( $type );
1473 } catch ( Exception
$ex ) {
1478 // Clear out any active transactions left over from callbacks...
1479 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$e, $fname ) {
1480 if ( $conn->writesPending() ) {
1481 // A callback from another handle wrote to this one and DBO_TRX is set
1482 $this->queryLogger
->warning( $fname . ": found writes pending." );
1483 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1484 $this->queryLogger
->warning(
1485 $fname . ": found writes pending ($fnames).",
1487 'db_server' => $conn->getServer(),
1488 'db_name' => $conn->getDBname()
1491 } elseif ( $conn->trxLevel() ) {
1492 // A callback from another handle read from this one and DBO_TRX is set,
1493 // which can easily happen if there is only one DB (no replicas)
1494 $this->queryLogger
->debug( $fname . ": found empty transaction." );
1497 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1498 } catch ( Exception
$ex ) {
1502 } while ( $count > 0 );
1504 $this->trxRoundStage
= $oldStage;
1509 public function runMasterTransactionListenerCallbacks() {
1510 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1511 $type = IDatabase
::TRIGGER_COMMIT
;
1512 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1513 $type = IDatabase
::TRIGGER_ROLLBACK
;
1515 throw new DBTransactionError(
1517 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1523 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1524 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1526 $conn->runTransactionListenerCallbacks( $type );
1527 } catch ( Exception
$ex ) {
1531 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1536 public function rollbackMasterChanges( $fname = __METHOD__
) {
1537 $restore = ( $this->trxRoundId
!== false );
1538 $this->trxRoundId
= false;
1539 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1540 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1541 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1544 // Unmark handles as participating in this explicit transaction round
1545 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1546 $this->undoTransactionRoundFlags( $conn );
1549 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
1553 * @param string|string[] $stage
1555 private function assertTransactionRoundStage( $stage ) {
1556 $stages = (array)$stage;
1558 if ( !in_array( $this->trxRoundStage
, $stages, true ) ) {
1559 $stageList = implode(
1561 array_map( function ( $v ) {
1565 throw new DBTransactionError(
1567 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1573 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1575 * Some servers may have neither flag enabled, meaning that they opt out of such
1576 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1577 * when a DB server is used for something like simple key/value storage.
1579 * @param Database $conn
1581 private function applyTransactionRoundFlags( Database
$conn ) {
1582 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1583 return; // transaction rounds do not apply to these connections
1586 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1587 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1588 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1589 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1592 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1593 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1598 * @param Database $conn
1600 private function undoTransactionRoundFlags( Database
$conn ) {
1601 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1602 return; // transaction rounds do not apply to these connections
1605 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1606 $conn->setLBInfo( 'trxRoundId', false );
1609 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1610 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1614 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1615 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) use ( $fname ) {
1616 $conn->flushSnapshot( $fname );
1620 public function flushMasterSnapshots( $fname = __METHOD__
) {
1621 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1622 $conn->flushSnapshot( $fname );
1630 public function getTransactionRoundStage() {
1631 return $this->trxRoundStage
;
1634 public function hasMasterConnection() {
1635 return $this->isOpen( $this->getWriterIndex() );
1638 public function hasMasterChanges() {
1640 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1641 $pending |
= $conn->writesOrCallbacksPending();
1644 return (bool)$pending;
1647 public function lastMasterChangeTimestamp() {
1649 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1650 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1656 public function hasOrMadeRecentMasterChanges( $age = null ) {
1657 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1659 return ( $this->hasMasterChanges()
1660 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1663 public function pendingMasterChangeCallers() {
1665 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1666 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1672 public function getLaggedReplicaMode( $domain = false ) {
1673 // No-op if there is only one DB (also avoids recursion)
1674 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1676 // See if laggedReplicaMode gets set
1677 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1678 $this->reuseConnection( $conn );
1679 } catch ( DBConnectionError
$e ) {
1680 // Avoid expensive re-connect attempts and failures
1681 $this->allReplicasDownMode
= true;
1682 $this->laggedReplicaMode
= true;
1686 return $this->laggedReplicaMode
;
1689 public function laggedReplicaUsed() {
1690 return $this->laggedReplicaMode
;
1696 * @deprecated Since 1.28; use laggedReplicaUsed()
1698 public function laggedSlaveUsed() {
1699 return $this->laggedReplicaUsed();
1702 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1703 if ( $this->readOnlyReason
!== false ) {
1704 return $this->readOnlyReason
;
1705 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1706 if ( $this->allReplicasDownMode
) {
1707 return 'The database has been automatically locked ' .
1708 'until the replica database servers become available';
1710 return 'The database has been automatically locked ' .
1711 'while the replica database servers catch up to the master.';
1713 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1714 return 'The database master is running in read-only mode.';
1721 * @param string $domain Domain ID, or false for the current domain
1722 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1725 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1726 $cache = $this->wanCache
;
1727 $masterServer = $this->getServerName( $this->getWriterIndex() );
1729 return (bool)$cache->getWithSetCallback(
1730 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1731 self
::TTL_CACHE_READONLY
,
1732 function () use ( $domain, $conn ) {
1733 $old = $this->trxProfiler
->setSilenced( true );
1735 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1736 $readOnly = (int)$dbw->serverIsReadOnly();
1738 $this->reuseConnection( $dbw );
1740 } catch ( DBError
$e ) {
1743 $this->trxProfiler
->setSilenced( $old );
1746 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1750 public function allowLagged( $mode = null ) {
1751 if ( $mode === null ) {
1752 return $this->allowLagged
;
1754 $this->allowLagged
= $mode;
1756 return $this->allowLagged
;
1759 public function pingAll() {
1761 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1762 if ( !$conn->ping() ) {
1770 public function forEachOpenConnection( $callback, array $params = [] ) {
1771 foreach ( $this->conns
as $connsByServer ) {
1772 foreach ( $connsByServer as $serverConns ) {
1773 foreach ( $serverConns as $conn ) {
1774 $callback( $conn, ...$params );
1780 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1781 $masterIndex = $this->getWriterIndex();
1782 foreach ( $this->conns
as $connsByServer ) {
1783 if ( isset( $connsByServer[$masterIndex] ) ) {
1784 /** @var IDatabase $conn */
1785 foreach ( $connsByServer[$masterIndex] as $conn ) {
1786 $callback( $conn, ...$params );
1792 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1793 foreach ( $this->conns
as $connsByServer ) {
1794 foreach ( $connsByServer as $i => $serverConns ) {
1795 if ( $i === $this->getWriterIndex() ) {
1796 continue; // skip master
1798 foreach ( $serverConns as $conn ) {
1799 $callback( $conn, ...$params );
1805 public function getMaxLag( $domain = false ) {
1810 if ( $this->getServerCount() <= 1 ) {
1811 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1814 $lagTimes = $this->getLagTimes( $domain );
1815 foreach ( $lagTimes as $i => $lag ) {
1816 if ( $this->loads
[$i] > 0 && $lag > $maxLag ) {
1818 $host = $this->servers
[$i]['host'];
1823 return [ $host, $maxLag, $maxIndex ];
1826 public function getLagTimes( $domain = false ) {
1827 if ( $this->getServerCount() <= 1 ) {
1828 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1831 $knownLagTimes = []; // map of (server index => 0 seconds)
1832 $indexesWithLag = [];
1833 foreach ( $this->servers
as $i => $server ) {
1834 if ( empty( $server['is static'] ) ) {
1835 $indexesWithLag[] = $i; // DB server might have replication lag
1837 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1841 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1844 public function safeGetLag( IDatabase
$conn ) {
1845 if ( $this->getServerCount() <= 1 ) {
1848 return $conn->getLag();
1852 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
1853 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
1855 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1856 return true; // server is not a replica DB
1860 // Get the current master position, opening a connection if needed
1861 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1862 if ( $masterConn ) {
1863 $pos = $masterConn->getMasterPos();
1865 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1866 if ( !$masterConn ) {
1867 throw new DBReplicationWaitError(
1869 "Could not obtain a master database connection to get the position"
1872 $pos = $masterConn->getMasterPos();
1873 $this->closeConnection( $masterConn );
1877 if ( $pos instanceof DBMasterPos
) {
1878 $result = $conn->masterPosWait( $pos, $timeout );
1879 if ( $result == -1 ||
is_null( $result ) ) {
1880 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos}';
1881 $this->replLogger
->warning( $msg, [
1882 'host' => $conn->getServer(),
1884 'trace' => ( new RuntimeException() )->getTraceAsString()
1888 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
1892 $ok = false; // something is misconfigured
1893 $this->replLogger
->error(
1894 __METHOD__
. ': could not get master pos for {host}',
1896 'host' => $conn->getServer(),
1897 'trace' => ( new RuntimeException() )->getTraceAsString()
1905 public function setTransactionListener( $name, callable
$callback = null ) {
1907 $this->trxRecurringCallbacks
[$name] = $callback;
1909 unset( $this->trxRecurringCallbacks
[$name] );
1911 $this->forEachOpenMasterConnection(
1912 function ( IDatabase
$conn ) use ( $name, $callback ) {
1913 $conn->setTransactionListener( $name, $callback );
1918 public function setTableAliases( array $aliases ) {
1919 $this->tableAliases
= $aliases;
1922 public function setIndexAliases( array $aliases ) {
1923 $this->indexAliases
= $aliases;
1927 * @param string $prefix
1928 * @deprecated Since 1.33
1930 public function setDomainPrefix( $prefix ) {
1931 $this->setLocalDomainPrefix( $prefix );
1934 public function setLocalDomainPrefix( $prefix ) {
1935 // Find connections to explicit foreign domains still marked as in-use...
1937 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
1938 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1939 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1940 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1941 $domainsInUse[] = $conn->getDomainID();
1945 // Do not switch connections to explicit foreign domains unless marked as safe
1946 if ( $domainsInUse ) {
1947 $domains = implode( ', ', $domainsInUse );
1948 throw new DBUnexpectedError( null,
1949 "Foreign domain connections are still in use ($domains)." );
1952 $this->setLocalDomain( new DatabaseDomain(
1953 $this->localDomain
->getDatabase(),
1954 $this->localDomain
->getSchema(),
1958 // Update the prefix for all local connections...
1959 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1960 if ( !$db->getLBInfo( 'foreign' ) ) {
1961 $db->tablePrefix( $prefix );
1966 public function redefineLocalDomain( $domain ) {
1969 $this->setLocalDomain( DatabaseDomain
::newFromId( $domain ) );
1973 * @param DatabaseDomain $domain
1975 private function setLocalDomain( DatabaseDomain
$domain ) {
1976 $this->localDomain
= $domain;
1977 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
1978 // always true, gracefully handle the case when they fail to account for escaping.
1979 if ( $this->localDomain
->getTablePrefix() != '' ) {
1980 $this->localDomainIdAlias
=
1981 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
1983 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
1987 function __destruct() {
1988 // Avoid connection leaks for sanity
1994 * @deprecated since 1.29
1996 class_alias( LoadBalancer
::class, 'LoadBalancer' );