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 InvalidArgumentException
;
36 * Database connection, tracking, load balancing, and transaction manager for a cluster
40 class LoadBalancer
implements ILoadBalancer
{
41 /** @var ILoadMonitor */
43 /** @var callable|null Callback to run before the first connection attempt */
44 private $chronologyCallback;
47 /** @var WANObjectCache */
49 /** @var object|string Class name or object With profileIn/profileOut methods */
51 /** @var TransactionProfiler */
53 /** @var LoggerInterface */
55 /** @var LoggerInterface */
57 /** @var LoggerInterface */
59 /** @var LoggerInterface */
61 /** @var callable Exception logger */
63 /** @var callable Deprecation logger */
64 private $deprecationLogger;
66 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
69 /** @var Database[][][] Map of (connection category => server index => IDatabase[]) */
72 /** @var array[] Map of (server index => server config array) */
74 /** @var float[] Map of (server index => weight) */
76 /** @var array[] Map of (group => server index => weight) */
78 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
80 /** @var int Seconds to spend waiting on replica DB lag to resolve */
82 /** @var array The LoadMonitor configuration */
83 private $loadMonitorConfig;
84 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
85 private $localDomainIdAlias;
87 private $maxLag = self
::MAX_LAG_DEFAULT
;
89 /** @var string Current server name */
91 /** @var bool Whether this PHP instance is for a CLI script */
93 /** @var string Agent name for query profiling */
96 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
97 private $tableAliases = [];
98 /** @var string[] Map of (index alias => index) */
99 private $indexAliases = [];
100 /** @var array[] Map of (name => callable) */
101 private $trxRecurringCallbacks = [];
103 /** @var Database DB connection object that caused a problem */
104 private $errorConnection;
105 /** @var int The generic (not query grouped) replica DB index (of $mServers) */
107 /** @var bool|DBMasterPos False if not set */
109 /** @var bool Whether the generic reader fell back to a lagged replica DB */
110 private $laggedReplicaMode = false;
111 /** @var bool Whether the generic reader fell back to a lagged replica DB */
112 private $allReplicasDownMode = false;
113 /** @var string The last DB selection or connection error */
114 private $lastError = 'Unknown error';
115 /** @var string|bool Reason the LB is read-only or false if not */
116 private $readOnlyReason = false;
117 /** @var int Total connections opened */
118 private $connsOpened = 0;
120 private $disabled = false;
121 /** @var bool Whether any connection has been attempted yet */
122 private $connectionAttempted = false;
124 /** @var string|bool String if a requested DBO_TRX transaction round is active */
125 private $trxRoundId = false;
126 /** @var string Stage of the current transaction round in the transaction round life-cycle */
127 private $trxRoundStage = self
::ROUND_CURSORY
;
129 /** @var string|null */
130 private $defaultGroup = null;
132 /** @var int Warn when this many connection are held */
133 const CONN_HELD_WARN_THRESHOLD
= 10;
135 /** @var int Default 'maxLag' when unspecified */
136 const MAX_LAG_DEFAULT
= 10;
137 /** @var int Default 'waitTimeout' when unspecified */
138 const MAX_WAIT_DEFAULT
= 10;
139 /** @var int Seconds to cache master server read-only status */
140 const TTL_CACHE_READONLY
= 5;
142 const KEY_LOCAL
= 'local';
143 const KEY_FOREIGN_FREE
= 'foreignFree';
144 const KEY_FOREIGN_INUSE
= 'foreignInUse';
146 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
147 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
148 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
150 /** @var string Transaction round, explicit or implicit, has not finished writing */
151 const ROUND_CURSORY
= 'cursory';
152 /** @var string Transaction round writes are complete and ready for pre-commit checks */
153 const ROUND_FINALIZED
= 'finalized';
154 /** @var string Transaction round passed final pre-commit checks */
155 const ROUND_APPROVED
= 'approved';
156 /** @var string Transaction round was committed and post-commit callbacks must be run */
157 const ROUND_COMMIT_CALLBACKS
= 'commit-callbacks';
158 /** @var string Transaction round was rolled back and post-rollback callbacks must be run */
159 const ROUND_ROLLBACK_CALLBACKS
= 'rollback-callbacks';
160 /** @var string Transaction round encountered an error */
161 const ROUND_ERROR
= 'error';
163 public function __construct( array $params ) {
164 if ( !isset( $params['servers'] ) ) {
165 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
167 $this->servers
= $params['servers'];
168 foreach ( $this->servers
as $i => $server ) {
170 $this->servers
[$i]['master'] = true;
172 $this->servers
[$i]['replica'] = true;
176 $localDomain = isset( $params['localDomain'] )
177 ? DatabaseDomain
::newFromId( $params['localDomain'] )
178 : DatabaseDomain
::newUnspecified();
179 $this->setLocalDomain( $localDomain );
181 $this->waitTimeout
= $params['waitTimeout'] ?? self
::MAX_WAIT_DEFAULT
;
183 $this->readIndex
= -1;
185 // Connection were transaction rounds may be applied
186 self
::KEY_LOCAL
=> [],
187 self
::KEY_FOREIGN_INUSE
=> [],
188 self
::KEY_FOREIGN_FREE
=> [],
189 // Auto-committing counterpart connections that ignore transaction rounds
190 self
::KEY_LOCAL_NOROUND
=> [],
191 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
192 self
::KEY_FOREIGN_FREE_NOROUND
=> []
195 $this->waitForPos
= false;
196 $this->allowLagged
= false;
198 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
199 $this->readOnlyReason
= $params['readOnlyReason'];
202 if ( isset( $params['maxLag'] ) ) {
203 $this->maxLag
= $params['maxLag'];
206 if ( isset( $params['loadMonitor'] ) ) {
207 $this->loadMonitorConfig
= $params['loadMonitor'];
209 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
211 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
213 foreach ( $params['servers'] as $i => $server ) {
214 $this->loads
[$i] = $server['load'];
215 if ( isset( $server['groupLoads'] ) ) {
216 foreach ( $server['groupLoads'] as $group => $ratio ) {
217 if ( !isset( $this->groupLoads
[$group] ) ) {
218 $this->groupLoads
[$group] = [];
220 $this->groupLoads
[$group][$i] = $ratio;
225 if ( isset( $params['srvCache'] ) ) {
226 $this->srvCache
= $params['srvCache'];
228 $this->srvCache
= new EmptyBagOStuff();
230 if ( isset( $params['wanCache'] ) ) {
231 $this->wanCache
= $params['wanCache'];
233 $this->wanCache
= WANObjectCache
::newEmpty();
235 $this->profiler
= $params['profiler'] ??
null;
236 if ( isset( $params['trxProfiler'] ) ) {
237 $this->trxProfiler
= $params['trxProfiler'];
239 $this->trxProfiler
= new TransactionProfiler();
242 $this->errorLogger
= $params['errorLogger'] ??
function ( Exception
$e ) {
243 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
245 $this->deprecationLogger
= $params['deprecationLogger'] ??
function ( $msg ) {
246 trigger_error( $msg, E_USER_DEPRECATED
);
249 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
250 $this->$key = $params[$key] ??
new NullLogger();
253 $this->hostname
= $params['hostname'] ??
( gethostname() ?
: 'unknown' );
254 $this->cliMode
= $params['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
255 $this->agent
= $params['agent'] ??
'';
257 if ( isset( $params['chronologyCallback'] ) ) {
258 $this->chronologyCallback
= $params['chronologyCallback'];
261 if ( isset( $params['roundStage'] ) ) {
262 if ( $params['roundStage'] === self
::STAGE_POSTCOMMIT_CALLBACKS
) {
263 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
264 } elseif ( $params['roundStage'] === self
::STAGE_POSTROLLBACK_CALLBACKS
) {
265 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
269 $this->defaultGroup
= $params['defaultGroup'] ??
null;
273 * Get the local (and default) database domain ID of connection handles
275 * @see DatabaseDomain
276 * @return string Database domain ID; this specifies DB name, schema, and table prefix
279 public function getLocalDomainID() {
280 return $this->localDomain
->getId();
284 * Get a LoadMonitor instance
286 * @return ILoadMonitor
288 private function getLoadMonitor() {
289 if ( !isset( $this->loadMonitor
) ) {
291 'LoadMonitor' => LoadMonitor
::class,
292 'LoadMonitorNull' => LoadMonitorNull
::class,
293 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
296 $class = $this->loadMonitorConfig
['class'];
297 if ( isset( $compat[$class] ) ) {
298 $class = $compat[$class];
301 $this->loadMonitor
= new $class(
302 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
303 $this->loadMonitor
->setLogger( $this->replLogger
);
306 return $this->loadMonitor
;
310 * @param array $loads
311 * @param bool|string $domain Domain to get non-lagged for
312 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
313 * @return bool|int|string
315 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
316 $lags = $this->getLagTimes( $domain );
318 # Unset excessively lagged servers
319 foreach ( $lags as $i => $lag ) {
321 # How much lag this server nominally is allowed to have
322 $maxServerLag = $this->servers
[$i]['max lag'] ??
$this->maxLag
; // default
323 # Constrain that futher by $maxLag argument
324 $maxServerLag = min( $maxServerLag, $maxLag );
326 $host = $this->getServerName( $i );
327 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
328 $this->replLogger
->error(
330 ": server {host} is not replicating?", [ 'host' => $host ] );
332 } elseif ( $lag > $maxServerLag ) {
333 $this->replLogger
->info(
335 ": server {host} has {lag} seconds of lag (>= {maxlag})",
336 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
343 # Find out if all the replica DBs with non-zero load are lagged
345 foreach ( $loads as $load ) {
349 # No appropriate DB servers except maybe the master and some replica DBs with zero load
350 # Do NOT use the master
351 # Instead, this function will return false, triggering read-only mode,
352 # and a lagged replica DB will be used instead.
356 if ( count( $loads ) == 0 ) {
360 # Return a random representative of the remainder
361 return ArrayUtils
::pickRandom( $loads );
364 public function getReaderIndex( $group = false, $domain = false ) {
365 if ( count( $this->servers
) == 1 ) {
366 // Skip the load balancing if there's only one server
367 return $this->getWriterIndex();
368 } elseif ( $group === false && $this->readIndex
>= 0 ) {
369 // Shortcut if the generic reader index was already cached
370 return $this->readIndex
;
373 if ( $group !== false ) {
374 // Use the server weight array for this load group
375 if ( isset( $this->groupLoads
[$group] ) ) {
376 $loads = $this->groupLoads
[$group];
378 // No loads for this group, return false and the caller can use some other group
379 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
384 // Use the generic load group
385 $loads = $this->loads
;
388 // Scale the configured load ratios according to each server's load and state
389 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
391 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
392 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
393 if ( $i === false ) {
394 // Replica DB connection unsuccessful
398 if ( $this->waitForPos
&& $i != $this->getWriterIndex() ) {
399 // Before any data queries are run, wait for the server to catch up to the
400 // specified position. This is used to improve session consistency. Note that
401 // when LoadBalancer::waitFor() sets "waitForPos", the waiting triggers here,
402 // so update laggedReplicaMode as needed for consistency.
403 if ( !$this->doWait( $i ) ) {
404 $laggedReplicaMode = true;
408 if ( $this->readIndex
<= 0 && $this->loads
[$i] > 0 && $group === false ) {
409 // Cache the generic reader index for future ungrouped DB_REPLICA handles
410 $this->readIndex
= $i;
411 // Record if the generic reader index is in "lagged replica DB" mode
412 if ( $laggedReplicaMode ) {
413 $this->laggedReplicaMode
= true;
417 $serverName = $this->getServerName( $i );
418 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
424 * @param array $loads List of server weights
425 * @param string|bool $domain
426 * @return array (reader index, lagged replica mode) or false on failure
428 private function pickReaderIndex( array $loads, $domain = false ) {
429 if ( !count( $loads ) ) {
430 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
433 /** @var int|bool $i Index of selected server */
435 /** @var bool $laggedReplicaMode Whether server is considered lagged */
436 $laggedReplicaMode = false;
438 // Quickly look through the available servers for a server that meets criteria...
439 $currentLoads = $loads;
440 while ( count( $currentLoads ) ) {
441 if ( $this->allowLagged ||
$laggedReplicaMode ) {
442 $i = ArrayUtils
::pickRandom( $currentLoads );
445 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
446 // "chronologyCallback" sets "waitForPos" for session consistency.
447 // This triggers doWait() after connect, so it's especially good to
448 // avoid lagged servers so as to avoid excessive delay in that method.
449 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
450 // Aim for <= 1 second of waiting (being too picky can backfire)
451 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
453 if ( $i === false ) {
454 // Any server with less lag than it's 'max lag' param is preferable
455 $i = $this->getRandomNonLagged( $currentLoads, $domain );
457 if ( $i === false && count( $currentLoads ) != 0 ) {
458 // All replica DBs lagged. Switch to read-only mode
459 $this->replLogger
->error(
460 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
461 $i = ArrayUtils
::pickRandom( $currentLoads );
462 $laggedReplicaMode = true;
466 if ( $i === false ) {
467 // pickRandom() returned false.
468 // This is permanent and means the configuration or the load monitor
469 // wants us to return false.
470 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
472 return [ false, false ];
475 $serverName = $this->getServerName( $i );
476 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
478 $conn = $this->openConnection( $i, $domain );
480 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
481 unset( $currentLoads[$i] ); // avoid this server next iteration
486 // Decrement reference counter, we are finished with this connection.
487 // It will be incremented for the caller later.
488 if ( $domain !== false ) {
489 $this->reuseConnection( $conn );
492 // Return this server
496 // If all servers were down, quit now
497 if ( !count( $currentLoads ) ) {
498 $this->connLogger
->error( __METHOD__
. ": all servers down" );
501 return [ $i, $laggedReplicaMode ];
504 public function waitFor( $pos ) {
505 $oldPos = $this->waitForPos
;
507 $this->waitForPos
= $pos;
508 // If a generic reader connection was already established, then wait now
509 $i = $this->readIndex
;
511 if ( !$this->doWait( $i ) ) {
512 $this->laggedReplicaMode
= true;
516 // Restore the older position if it was higher since this is used for lag-protection
517 $this->setWaitForPositionIfHigher( $oldPos );
521 public function waitForOne( $pos, $timeout = null ) {
522 $oldPos = $this->waitForPos
;
524 $this->waitForPos
= $pos;
526 $i = $this->readIndex
;
528 // Pick a generic replica DB if there isn't one yet
529 $readLoads = $this->loads
;
530 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
531 $readLoads = array_filter( $readLoads ); // with non-zero load
532 $i = ArrayUtils
::pickRandom( $readLoads );
536 $ok = $this->doWait( $i, true, $timeout );
538 $ok = true; // no applicable loads
541 # Restore the old position, as this is not used for lag-protection but for throttling
542 $this->waitForPos
= $oldPos;
548 public function waitForAll( $pos, $timeout = null ) {
549 $timeout = $timeout ?
: $this->waitTimeout
;
551 $oldPos = $this->waitForPos
;
553 $this->waitForPos
= $pos;
554 $serverCount = count( $this->servers
);
557 for ( $i = 1; $i < $serverCount; $i++
) {
558 if ( $this->loads
[$i] > 0 ) {
559 $start = microtime( true );
560 $ok = $this->doWait( $i, true, $timeout ) && $ok;
561 $timeout -= intval( microtime( true ) - $start );
562 if ( $timeout <= 0 ) {
563 break; // timeout reached
568 # Restore the old position, as this is not used for lag-protection but for throttling
569 $this->waitForPos
= $oldPos;
576 * @param DBMasterPos|bool $pos
578 private function setWaitForPositionIfHigher( $pos ) {
583 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
584 $this->waitForPos
= $pos;
588 public function getAnyOpenConnection( $i, $flags = 0 ) {
589 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
590 foreach ( $this->conns
as $connsByServer ) {
591 if ( !isset( $connsByServer[$i] ) ) {
595 foreach ( $connsByServer[$i] as $conn ) {
596 if ( !$autocommit ||
$conn->getLBInfo( 'autoCommitOnly' ) ) {
606 * Wait for a given replica DB to catch up to the master pos stored in $this
607 * @param int $index Server index
608 * @param bool $open Check the server even if a new connection has to be made
609 * @param int $timeout Max seconds to wait; default is "waitTimeout" given to __construct()
612 protected function doWait( $index, $open = false, $timeout = null ) {
613 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
615 // Check if we already know that the DB has reached this point
616 $server = $this->getServerName( $index );
617 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
618 /** @var DBMasterPos $knownReachedPos */
619 $knownReachedPos = $this->srvCache
->get( $key );
621 $knownReachedPos instanceof DBMasterPos
&&
622 $knownReachedPos->hasReached( $this->waitForPos
)
624 $this->replLogger
->debug(
626 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
627 [ 'dbserver' => $server ]
632 // Find a connection to wait on, creating one if needed and allowed
633 $close = false; // close the connection afterwards
634 $conn = $this->getAnyOpenConnection( $index );
637 $this->replLogger
->debug(
638 __METHOD__
. ': no connection open for {dbserver}',
639 [ 'dbserver' => $server ]
644 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
646 $this->replLogger
->warning(
647 __METHOD__
. ': failed to connect to {dbserver}',
648 [ 'dbserver' => $server ]
653 // Avoid connection spam in waitForAll() when connections
654 // are made just for the sake of doing this lag check.
659 $this->replLogger
->info(
661 ': waiting for replica DB {dbserver} to catch up...',
662 [ 'dbserver' => $server ]
665 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
667 if ( $result === null ) {
668 $this->replLogger
->warning(
669 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
672 'pos' => $this->waitForPos
,
673 'trace' => ( new RuntimeException() )->getTraceAsString()
677 } elseif ( $result == -1 ) {
678 $this->replLogger
->warning(
679 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
682 'pos' => $this->waitForPos
,
683 'trace' => ( new RuntimeException() )->getTraceAsString()
688 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
690 // Remember that the DB reached this point
691 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
695 $this->closeConnection( $conn );
701 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
702 if ( $i === null ||
$i === false ) {
703 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
704 ' with invalid server index' );
707 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
708 $domain = false; // local connection requested
711 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) === self
::CONN_TRX_AUTOCOMMIT
) {
712 // Assuming all servers are of the same type (or similar), which is overwhelmingly
713 // the case, use the master server information to get the attributes. The information
714 // for $i cannot be used since it might be DB_REPLICA, which might require connection
715 // attempts in order to be resolved into a real server index.
716 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
717 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
718 // Callers sometimes want to (a) escape REPEATABLE-READ stateness without locking
719 // rows (e.g. FOR UPDATE) or (b) make small commits during a larger transactions
720 // to reduce lock contention. None of these apply for sqlite and using separate
721 // connections just causes self-deadlocks.
722 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
723 $this->connLogger
->info( __METHOD__
.
724 ': ignoring CONN_TRX_AUTOCOMMIT to avoid deadlocks.' );
728 // Check one "group" per default: the generic pool
729 $defaultGroups = $this->defaultGroup ?
[ $this->defaultGroup
] : [ false ];
731 $groups = ( $groups === false ||
$groups === [] )
735 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
736 $oldConnsOpened = $this->connsOpened
; // connections open now
738 if ( $i == self
::DB_MASTER
) {
739 $i = $this->getWriterIndex();
740 } elseif ( $i == self
::DB_REPLICA
) {
741 # Try to find an available server in any the query groups (in order)
742 foreach ( $groups as $group ) {
743 $groupIndex = $this->getReaderIndex( $group, $domain );
744 if ( $groupIndex !== false ) {
751 # Operation-based index
752 if ( $i == self
::DB_REPLICA
) {
753 $this->lastError
= 'Unknown error'; // reset error string
754 # Try the general server pool if $groups are unavailable.
755 $i = ( $groups === [ false ] )
756 ?
false // don't bother with this if that is what was tried above
757 : $this->getReaderIndex( false, $domain );
758 # Couldn't find a working server in getReaderIndex()?
759 if ( $i === false ) {
760 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
761 // Throw an exception
762 $this->reportConnectionError();
763 return null; // not reached
767 # Now we have an explicit index into the servers array
768 $conn = $this->openConnection( $i, $domain, $flags );
770 // Throw an exception
771 $this->reportConnectionError();
772 return null; // not reached
775 # Profile any new connections that happen
776 if ( $this->connsOpened
> $oldConnsOpened ) {
777 $host = $conn->getServer();
778 $dbname = $conn->getDBname();
779 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
783 # Make master-requested DB handles inherit any read-only mode setting
784 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
790 public function reuseConnection( IDatabase
$conn ) {
791 $serverIndex = $conn->getLBInfo( 'serverIndex' );
792 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
793 if ( $serverIndex === null ||
$refCount === null ) {
795 * This can happen in code like:
796 * foreach ( $dbs as $db ) {
797 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
799 * $lb->reuseConnection( $conn );
801 * When a connection to the local DB is opened in this way, reuseConnection()
805 } elseif ( $conn instanceof DBConnRef
) {
806 // DBConnRef already handles calling reuseConnection() and only passes the live
807 // Database instance to this method. Any caller passing in a DBConnRef is broken.
808 $this->connLogger
->error(
809 __METHOD__
. ": got DBConnRef instance.\n" .
810 ( new RuntimeException() )->getTraceAsString() );
815 if ( $this->disabled
) {
816 return; // DBConnRef handle probably survived longer than the LoadBalancer
819 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
820 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
821 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
823 $connFreeKey = self
::KEY_FOREIGN_FREE
;
824 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
827 $domain = $conn->getDomainID();
828 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
829 throw new InvalidArgumentException( __METHOD__
.
830 ": connection $serverIndex/$domain not found; it may have already been freed." );
831 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
832 throw new InvalidArgumentException( __METHOD__
.
833 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
836 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
837 if ( $refCount <= 0 ) {
838 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
839 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
840 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
841 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
843 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
845 $this->connLogger
->debug( __METHOD__
.
846 ": reference count for $serverIndex/$domain reduced to $refCount" );
850 public function getConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
851 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
853 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain, $flags ) );
856 public function getLazyConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
857 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
859 return new DBConnRef( $this, [ $db, $groups, $domain, $flags ] );
862 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
863 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
865 return new MaintainableDBConnRef(
866 $this, $this->getConnection( $db, $groups, $domain, $flags ) );
869 public function openConnection( $i, $domain = false, $flags = 0 ) {
870 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
871 $domain = false; // local connection requested
874 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
875 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
876 // Load any "waitFor" positions before connecting so that doWait() is triggered
877 $this->connectionAttempted
= true;
878 ( $this->chronologyCallback
)( $this );
881 // Check if an auto-commit connection is being requested. If so, it will not reuse the
882 // main set of DB connections but rather its own pool since:
883 // a) those are usually set to implicitly use transaction rounds via DBO_TRX
884 // b) those must support the use of explicit transaction rounds via beginMasterChanges()
885 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
887 if ( $domain !== false ) {
888 // Connection is to a foreign domain
889 $conn = $this->openForeignConnection( $i, $domain, $flags );
891 // Connection is to the local domain
892 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
893 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
894 $conn = $this->conns
[$connKey][$i][0];
896 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
897 throw new InvalidArgumentException( "No server with index '$i'." );
899 // Open a new connection
900 $server = $this->servers
[$i];
901 $server['serverIndex'] = $i;
902 $server['autoCommitOnly'] = $autoCommit;
903 if ( $this->localDomain
->getDatabase() !== null ) {
904 // Use the local domain table prefix if the local domain is specified
905 $server['tablePrefix'] = $this->localDomain
->getTablePrefix();
907 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
908 $host = $this->getServerName( $i );
909 if ( $conn->isOpen() ) {
910 $this->connLogger
->debug(
911 __METHOD__
. ": connected to database $i at '$host'." );
912 $this->conns
[$connKey][$i][0] = $conn;
914 $this->connLogger
->warning(
915 __METHOD__
. ": failed to connect to database $i at '$host'." );
916 $this->errorConnection
= $conn;
922 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
923 // Connection was made but later unrecoverably lost for some reason.
924 // Do not return a handle that will just throw exceptions on use,
925 // but let the calling code (e.g. getReaderIndex) try another server.
926 // See DatabaseMyslBase::ping() for how this can happen.
927 $this->errorConnection
= $conn;
931 if ( $autoCommit && $conn instanceof IDatabase
) {
932 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
939 * Open a connection to a foreign DB, or return one if it is already open.
941 * Increments a reference count on the returned connection which locks the
942 * connection to the requested domain. This reference count can be
943 * decremented by calling reuseConnection().
945 * If a connection is open to the appropriate server already, but with the wrong
946 * database, it will be switched to the right database and returned, as long as
947 * it has been freed first with reuseConnection().
949 * On error, returns false, and the connection which caused the
950 * error will be available via $this->errorConnection.
952 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
954 * @param int $i Server index
955 * @param string $domain Domain ID to open
956 * @param int $flags Class CONN_* constant bitfield
959 private function openForeignConnection( $i, $domain, $flags = 0 ) {
960 $domainInstance = DatabaseDomain
::newFromId( $domain );
961 $dbName = $domainInstance->getDatabase();
962 $prefix = $domainInstance->getTablePrefix();
963 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
966 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
967 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
969 $connFreeKey = self
::KEY_FOREIGN_FREE
;
970 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
973 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
974 // Reuse an in-use connection for the same domain
975 $conn = $this->conns
[$connInUseKey][$i][$domain];
976 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
977 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
978 // Reuse a free connection for the same domain
979 $conn = $this->conns
[$connFreeKey][$i][$domain];
980 unset( $this->conns
[$connFreeKey][$i][$domain] );
981 $this->conns
[$connInUseKey][$i][$domain] = $conn;
982 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
983 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
984 // Reuse a free connection from another domain
985 $conn = reset( $this->conns
[$connFreeKey][$i] );
986 $oldDomain = key( $this->conns
[$connFreeKey][$i] );
987 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
988 $this->lastError
= "Error selecting database '$dbName' on server " .
989 $conn->getServer() . " from client host {$this->hostname}";
990 $this->errorConnection
= $conn;
993 $conn->tablePrefix( $prefix );
994 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
995 // Note that if $domain is an empty string, getDomainID() might not match it
996 $this->conns
[$connInUseKey][$i][$conn->getDomainId()] = $conn;
997 $this->connLogger
->debug( __METHOD__
.
998 ": reusing free connection from $oldDomain for $domain" );
1001 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
1002 throw new InvalidArgumentException( "No server with index '$i'." );
1004 // Open a new connection
1005 $server = $this->servers
[$i];
1006 $server['serverIndex'] = $i;
1007 $server['foreignPoolRefCount'] = 0;
1008 $server['foreign'] = true;
1009 $server['autoCommitOnly'] = $autoCommit;
1010 $conn = $this->reallyOpenConnection( $server, $domainInstance );
1011 if ( !$conn->isOpen() ) {
1012 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
1013 $this->errorConnection
= $conn;
1016 $conn->tablePrefix( $prefix ); // as specified
1017 // Note that if $domain is an empty string, getDomainID() might not match it
1018 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1019 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1023 // Increment reference count
1024 if ( $conn instanceof IDatabase
) {
1025 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1026 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1032 public function getServerAttributes( $i ) {
1033 return Database
::attributesFromType(
1034 $this->getServerType( $i ),
1035 $this->servers
[$i]['driver'] ??
null
1040 * Test if the specified index represents an open connection
1042 * @param int $index Server index
1046 private function isOpen( $index ) {
1047 if ( !is_int( $index ) ) {
1051 return (bool)$this->getAnyOpenConnection( $index );
1055 * Open a new network connection to a server (uncached)
1057 * Returns a Database object whether or not the connection was successful.
1059 * @param array $server
1060 * @param DatabaseDomain $domainOverride Use an unspecified domain to not select any database
1062 * @throws DBAccessError
1063 * @throws InvalidArgumentException
1065 protected function reallyOpenConnection( array $server, DatabaseDomain
$domainOverride ) {
1066 if ( $this->disabled
) {
1067 throw new DBAccessError();
1070 // Handle $domainOverride being a specified or an unspecified domain
1071 if ( $domainOverride->getDatabase() === null ) {
1072 // Normally, an RDBMS requires a DB name specified on connection and the $server
1073 // configuration array is assumed to already specify an appropriate DB name.
1074 if ( $server['type'] === 'mysql' ) {
1075 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1076 // and the DB name in $server might not exist due to legacy reasons (the default
1077 // domain used to ignore the local LB domain, even when mismatched).
1078 $server['dbname'] = null;
1081 $server['dbname'] = $domainOverride->getDatabase();
1082 $server['schema'] = $domainOverride->getSchema();
1085 // Let the handle know what the cluster master is (e.g. "db1052")
1086 $masterName = $this->getServerName( $this->getWriterIndex() );
1087 $server['clusterMasterHost'] = $masterName;
1089 // Log when many connection are made on requests
1090 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
1091 $this->perfLogger
->warning( __METHOD__
. ": " .
1092 "{$this->connsOpened}+ connections made (master=$masterName)" );
1095 $server['srvCache'] = $this->srvCache
;
1096 // Set loggers and profilers
1097 $server['connLogger'] = $this->connLogger
;
1098 $server['queryLogger'] = $this->queryLogger
;
1099 $server['errorLogger'] = $this->errorLogger
;
1100 $server['deprecationLogger'] = $this->deprecationLogger
;
1101 $server['profiler'] = $this->profiler
;
1102 $server['trxProfiler'] = $this->trxProfiler
;
1103 // Use the same agent and PHP mode for all DB handles
1104 $server['cliMode'] = $this->cliMode
;
1105 $server['agent'] = $this->agent
;
1106 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1107 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1108 $server['flags'] = $server['flags'] ?? IDatabase
::DBO_DEFAULT
;
1110 // Create a live connection object
1112 $db = Database
::factory( $server['type'], $server );
1113 } catch ( DBConnectionError
$e ) {
1114 // FIXME: This is probably the ugliest thing I have ever done to
1115 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1119 $db->setLBInfo( $server );
1120 $db->setLazyMasterHandle(
1121 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1123 $db->setTableAliases( $this->tableAliases
);
1124 $db->setIndexAliases( $this->indexAliases
);
1126 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1127 if ( $this->trxRoundId
!== false ) {
1128 $this->applyTransactionRoundFlags( $db );
1130 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1131 $db->setTransactionListener( $name, $callback );
1139 * @throws DBConnectionError
1141 private function reportConnectionError() {
1142 $conn = $this->errorConnection
; // the connection which caused the error
1144 'method' => __METHOD__
,
1145 'last_error' => $this->lastError
,
1148 if ( $conn instanceof IDatabase
) {
1149 $context['db_server'] = $conn->getServer();
1150 $this->connLogger
->warning(
1151 __METHOD__
. ": connection error: {last_error} ({db_server})",
1155 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1157 // No last connection, probably due to all servers being too busy
1158 $this->connLogger
->error(
1160 ": LB failure with no last connection. Connection error: {last_error}",
1164 // If all servers were busy, "lastError" will contain something sensible
1165 throw new DBConnectionError( null, $this->lastError
);
1169 public function getWriterIndex() {
1173 public function haveIndex( $i ) {
1174 return array_key_exists( $i, $this->servers
);
1177 public function isNonZeroLoad( $i ) {
1178 return array_key_exists( $i, $this->servers
) && $this->loads
[$i] != 0;
1181 public function getServerCount() {
1182 return count( $this->servers
);
1185 public function getServerName( $i ) {
1186 if ( isset( $this->servers
[$i]['hostName'] ) ) {
1187 $name = $this->servers
[$i]['hostName'];
1188 } elseif ( isset( $this->servers
[$i]['host'] ) ) {
1189 $name = $this->servers
[$i]['host'];
1194 return ( $name != '' ) ?
$name : 'localhost';
1197 public function getServerInfo( $i ) {
1198 if ( isset( $this->servers
[$i] ) ) {
1199 return $this->servers
[$i];
1205 public function getServerType( $i ) {
1206 return $this->servers
[$i]['type'] ??
'unknown';
1209 public function getMasterPos() {
1210 # If this entire request was served from a replica DB without opening a connection to the
1211 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1212 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1213 if ( !$masterConn ) {
1214 $serverCount = count( $this->servers
);
1215 for ( $i = 1; $i < $serverCount; $i++
) {
1216 $conn = $this->getAnyOpenConnection( $i );
1218 return $conn->getReplicaPos();
1222 return $masterConn->getMasterPos();
1228 public function disable() {
1230 $this->disabled
= true;
1233 public function closeAll() {
1234 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1235 $host = $conn->getServer();
1236 $this->connLogger
->debug(
1237 __METHOD__
. ": closing connection to database '$host'." );
1242 self
::KEY_LOCAL
=> [],
1243 self
::KEY_FOREIGN_INUSE
=> [],
1244 self
::KEY_FOREIGN_FREE
=> [],
1245 self
::KEY_LOCAL_NOROUND
=> [],
1246 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1247 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1249 $this->connsOpened
= 0;
1252 public function closeConnection( IDatabase
$conn ) {
1253 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1254 foreach ( $this->conns
as $type => $connsByServer ) {
1255 if ( !isset( $connsByServer[$serverIndex] ) ) {
1259 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1260 if ( $conn === $trackedConn ) {
1261 $host = $this->getServerName( $i );
1262 $this->connLogger
->debug(
1263 __METHOD__
. ": closing connection to database $i at '$host'." );
1264 unset( $this->conns
[$type][$serverIndex][$i] );
1265 --$this->connsOpened
;
1274 public function commitAll( $fname = __METHOD__
) {
1275 $this->commitMasterChanges( $fname );
1276 $this->flushMasterSnapshots( $fname );
1277 $this->flushReplicaSnapshots( $fname );
1280 public function finalizeMasterChanges() {
1281 $this->assertTransactionRoundStage( [ self
::ROUND_CURSORY
, self
::ROUND_FINALIZED
] );
1283 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1284 // Loop until callbacks stop adding callbacks on other connections
1287 $count = 0; // callbacks execution attempts
1288 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$count ) {
1289 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1290 // Any error should cause all (peer) transactions to be rolled back together.
1291 $count +
= $conn->runOnTransactionPreCommitCallbacks();
1294 } while ( $count > 0 );
1295 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1296 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1297 $conn->setTrxEndCallbackSuppression( true );
1299 $this->trxRoundStage
= self
::ROUND_FINALIZED
;
1304 public function approveMasterChanges( array $options ) {
1305 $this->assertTransactionRoundStage( self
::ROUND_FINALIZED
);
1307 $limit = $options['maxWriteDuration'] ??
0;
1309 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1310 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1311 // If atomic sections or explicit transactions are still open, some caller must have
1312 // caught an exception but failed to properly rollback any changes. Detect that and
1313 // throw and error (causing rollback).
1314 if ( $conn->explicitTrxActive() ) {
1315 throw new DBTransactionError(
1317 "Explicit transaction still active. A caller may have caught an error."
1320 // Assert that the time to replicate the transaction will be sane.
1321 // If this fails, then all DB transactions will be rollback back together.
1322 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1323 if ( $limit > 0 && $time > $limit ) {
1324 throw new DBTransactionSizeError(
1326 "Transaction spent $time second(s) in writes, exceeding the limit of $limit.",
1330 // If a connection sits idle while slow queries execute on another, that connection
1331 // may end up dropped before the commit round is reached. Ping servers to detect this.
1332 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1333 throw new DBTransactionError(
1335 "A connection to the {$conn->getDBname()} database was lost before commit."
1339 $this->trxRoundStage
= self
::ROUND_APPROVED
;
1342 public function beginMasterChanges( $fname = __METHOD__
) {
1343 if ( $this->trxRoundId
!== false ) {
1344 throw new DBTransactionError(
1346 "$fname: Transaction round '{$this->trxRoundId}' already started."
1349 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
1351 // Clear any empty transactions (no writes/callbacks) from the implicit round
1352 $this->flushMasterSnapshots( $fname );
1354 $this->trxRoundId
= $fname;
1355 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1356 // Mark applicable handles as participating in this explicit transaction round.
1357 // For each of these handles, any writes and callbacks will be tied to a single
1358 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1359 // are part of an en masse commit or an en masse rollback.
1360 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1361 $this->applyTransactionRoundFlags( $conn );
1363 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1366 public function commitMasterChanges( $fname = __METHOD__
) {
1367 $this->assertTransactionRoundStage( self
::ROUND_APPROVED
);
1371 /** @noinspection PhpUnusedLocalVariableInspection */
1372 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1374 $restore = ( $this->trxRoundId
!== false );
1375 $this->trxRoundId
= false;
1376 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1377 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1378 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1379 $this->forEachOpenMasterConnection(
1380 function ( IDatabase
$conn ) use ( $fname, &$failures ) {
1382 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1383 } catch ( DBError
$e ) {
1384 ( $this->errorLogger
)( $e );
1385 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1390 throw new DBTransactionError(
1392 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1396 // Unmark handles as participating in this explicit transaction round
1397 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1398 $this->undoTransactionRoundFlags( $conn );
1401 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
1404 public function runMasterTransactionIdleCallbacks() {
1405 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1406 $type = IDatabase
::TRIGGER_COMMIT
;
1407 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1408 $type = IDatabase
::TRIGGER_ROLLBACK
;
1410 throw new DBTransactionError(
1412 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1416 $oldStage = $this->trxRoundStage
;
1417 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1419 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1420 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1421 $conn->setTrxEndCallbackSuppression( false );
1424 $e = null; // first exception
1425 // Loop until callbacks stop adding callbacks on other connections
1427 // Run any pending callbacks for each connection...
1428 $count = 0; // callback execution attempts
1429 $this->forEachOpenMasterConnection(
1430 function ( Database
$conn ) use ( $type, &$e, &$count ) {
1431 if ( $conn->trxLevel() ) {
1432 return; // retry in the next iteration, after commit() is called
1435 $count +
= $conn->runOnTransactionIdleCallbacks( $type );
1436 } catch ( Exception
$ex ) {
1441 // Clear out any active transactions left over from callbacks...
1442 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$e ) {
1443 if ( $conn->writesPending() ) {
1444 // A callback from another handle wrote to this one and DBO_TRX is set
1445 $this->queryLogger
->warning( __METHOD__
. ": found writes pending." );
1446 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1447 $this->queryLogger
->warning(
1448 __METHOD__
. ": found writes pending ($fnames).",
1450 'db_server' => $conn->getServer(),
1451 'db_name' => $conn->getDBname()
1454 } elseif ( $conn->trxLevel() ) {
1455 // A callback from another handle read from this one and DBO_TRX is set,
1456 // which can easily happen if there is only one DB (no replicas)
1457 $this->queryLogger
->debug( __METHOD__
. ": found empty transaction." );
1460 $conn->commit( __METHOD__
, $conn::FLUSHING_ALL_PEERS
);
1461 } catch ( Exception
$ex ) {
1465 } while ( $count > 0 );
1467 $this->trxRoundStage
= $oldStage;
1472 public function runMasterTransactionListenerCallbacks() {
1473 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1474 $type = IDatabase
::TRIGGER_COMMIT
;
1475 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1476 $type = IDatabase
::TRIGGER_ROLLBACK
;
1478 throw new DBTransactionError(
1480 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1486 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1487 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1489 $conn->runTransactionListenerCallbacks( $type );
1490 } catch ( Exception
$ex ) {
1494 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1499 public function rollbackMasterChanges( $fname = __METHOD__
) {
1500 $restore = ( $this->trxRoundId
!== false );
1501 $this->trxRoundId
= false;
1502 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1503 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1504 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1507 // Unmark handles as participating in this explicit transaction round
1508 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1509 $this->undoTransactionRoundFlags( $conn );
1512 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
1516 * @param string|string[] $stage
1518 private function assertTransactionRoundStage( $stage ) {
1519 $stages = (array)$stage;
1521 if ( !in_array( $this->trxRoundStage
, $stages, true ) ) {
1522 $stageList = implode(
1524 array_map( function ( $v ) {
1528 throw new DBTransactionError(
1530 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1536 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1538 * Some servers may have neither flag enabled, meaning that they opt out of such
1539 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1540 * when a DB server is used for something like simple key/value storage.
1542 * @param Database $conn
1544 private function applyTransactionRoundFlags( Database
$conn ) {
1545 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1546 return; // transaction rounds do not apply to these connections
1549 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1550 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1551 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1552 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1555 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1556 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1561 * @param Database $conn
1563 private function undoTransactionRoundFlags( Database
$conn ) {
1564 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1565 return; // transaction rounds do not apply to these connections
1568 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1569 $conn->setLBInfo( 'trxRoundId', false );
1572 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1573 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1577 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1578 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) use ( $fname ) {
1579 $conn->flushSnapshot( $fname );
1583 public function flushMasterSnapshots( $fname = __METHOD__
) {
1584 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1585 $conn->flushSnapshot( $fname );
1593 public function getTransactionRoundStage() {
1594 return $this->trxRoundStage
;
1597 public function hasMasterConnection() {
1598 return $this->isOpen( $this->getWriterIndex() );
1601 public function hasMasterChanges() {
1603 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1604 $pending |
= $conn->writesOrCallbacksPending();
1607 return (bool)$pending;
1610 public function lastMasterChangeTimestamp() {
1612 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1613 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1619 public function hasOrMadeRecentMasterChanges( $age = null ) {
1620 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1622 return ( $this->hasMasterChanges()
1623 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1626 public function pendingMasterChangeCallers() {
1628 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1629 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1635 public function getLaggedReplicaMode( $domain = false ) {
1636 // No-op if there is only one DB (also avoids recursion)
1637 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1639 // See if laggedReplicaMode gets set
1640 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1641 $this->reuseConnection( $conn );
1642 } catch ( DBConnectionError
$e ) {
1643 // Avoid expensive re-connect attempts and failures
1644 $this->allReplicasDownMode
= true;
1645 $this->laggedReplicaMode
= true;
1649 return $this->laggedReplicaMode
;
1652 public function laggedReplicaUsed() {
1653 return $this->laggedReplicaMode
;
1659 * @deprecated Since 1.28; use laggedReplicaUsed()
1661 public function laggedSlaveUsed() {
1662 return $this->laggedReplicaUsed();
1665 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1666 if ( $this->readOnlyReason
!== false ) {
1667 return $this->readOnlyReason
;
1668 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1669 if ( $this->allReplicasDownMode
) {
1670 return 'The database has been automatically locked ' .
1671 'until the replica database servers become available';
1673 return 'The database has been automatically locked ' .
1674 'while the replica database servers catch up to the master.';
1676 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1677 return 'The database master is running in read-only mode.';
1684 * @param string $domain Domain ID, or false for the current domain
1685 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1688 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1689 $cache = $this->wanCache
;
1690 $masterServer = $this->getServerName( $this->getWriterIndex() );
1692 return (bool)$cache->getWithSetCallback(
1693 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1694 self
::TTL_CACHE_READONLY
,
1695 function () use ( $domain, $conn ) {
1696 $old = $this->trxProfiler
->setSilenced( true );
1698 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1699 $readOnly = (int)$dbw->serverIsReadOnly();
1701 $this->reuseConnection( $dbw );
1703 } catch ( DBError
$e ) {
1706 $this->trxProfiler
->setSilenced( $old );
1709 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1713 public function allowLagged( $mode = null ) {
1714 if ( $mode === null ) {
1715 return $this->allowLagged
;
1717 $this->allowLagged
= $mode;
1719 return $this->allowLagged
;
1722 public function pingAll() {
1724 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1725 if ( !$conn->ping() ) {
1733 public function forEachOpenConnection( $callback, array $params = [] ) {
1734 foreach ( $this->conns
as $connsByServer ) {
1735 foreach ( $connsByServer as $serverConns ) {
1736 foreach ( $serverConns as $conn ) {
1737 $callback( $conn, ...$params );
1743 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1744 $masterIndex = $this->getWriterIndex();
1745 foreach ( $this->conns
as $connsByServer ) {
1746 if ( isset( $connsByServer[$masterIndex] ) ) {
1747 /** @var IDatabase $conn */
1748 foreach ( $connsByServer[$masterIndex] as $conn ) {
1749 $callback( $conn, ...$params );
1755 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1756 foreach ( $this->conns
as $connsByServer ) {
1757 foreach ( $connsByServer as $i => $serverConns ) {
1758 if ( $i === $this->getWriterIndex() ) {
1759 continue; // skip master
1761 foreach ( $serverConns as $conn ) {
1762 $callback( $conn, ...$params );
1768 public function getMaxLag( $domain = false ) {
1773 if ( $this->getServerCount() <= 1 ) {
1774 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1777 $lagTimes = $this->getLagTimes( $domain );
1778 foreach ( $lagTimes as $i => $lag ) {
1779 if ( $this->loads
[$i] > 0 && $lag > $maxLag ) {
1781 $host = $this->servers
[$i]['host'];
1786 return [ $host, $maxLag, $maxIndex ];
1789 public function getLagTimes( $domain = false ) {
1790 if ( $this->getServerCount() <= 1 ) {
1791 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1794 $knownLagTimes = []; // map of (server index => 0 seconds)
1795 $indexesWithLag = [];
1796 foreach ( $this->servers
as $i => $server ) {
1797 if ( empty( $server['is static'] ) ) {
1798 $indexesWithLag[] = $i; // DB server might have replication lag
1800 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1804 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1807 public function safeGetLag( IDatabase
$conn ) {
1808 if ( $this->getServerCount() <= 1 ) {
1811 return $conn->getLag();
1816 * @param IDatabase $conn
1817 * @param DBMasterPos|bool $pos
1818 * @param int|null $timeout
1821 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
1822 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
1824 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1825 return true; // server is not a replica DB
1829 // Get the current master position, opening a connection if needed
1830 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1831 if ( $masterConn ) {
1832 $pos = $masterConn->getMasterPos();
1834 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1835 $pos = $masterConn->getMasterPos();
1836 $this->closeConnection( $masterConn );
1840 if ( $pos instanceof DBMasterPos
) {
1841 $result = $conn->masterPosWait( $pos, $timeout );
1842 if ( $result == -1 ||
is_null( $result ) ) {
1843 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos}';
1844 $this->replLogger
->warning( $msg, [
1845 'host' => $conn->getServer(),
1847 'trace' => ( new RuntimeException() )->getTraceAsString()
1851 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
1855 $ok = false; // something is misconfigured
1856 $this->replLogger
->error(
1857 __METHOD__
. ': could not get master pos for {host}',
1859 'host' => $conn->getServer(),
1860 'trace' => ( new RuntimeException() )->getTraceAsString()
1868 public function setTransactionListener( $name, callable
$callback = null ) {
1870 $this->trxRecurringCallbacks
[$name] = $callback;
1872 unset( $this->trxRecurringCallbacks
[$name] );
1874 $this->forEachOpenMasterConnection(
1875 function ( IDatabase
$conn ) use ( $name, $callback ) {
1876 $conn->setTransactionListener( $name, $callback );
1881 public function setTableAliases( array $aliases ) {
1882 $this->tableAliases
= $aliases;
1885 public function setIndexAliases( array $aliases ) {
1886 $this->indexAliases
= $aliases;
1889 public function setDomainPrefix( $prefix ) {
1890 // Find connections to explicit foreign domains still marked as in-use...
1892 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
1893 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1894 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1895 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1896 $domainsInUse[] = $conn->getDomainID();
1900 // Do not switch connections to explicit foreign domains unless marked as safe
1901 if ( $domainsInUse ) {
1902 $domains = implode( ', ', $domainsInUse );
1903 throw new DBUnexpectedError( null,
1904 "Foreign domain connections are still in use ($domains)." );
1907 $oldDomain = $this->localDomain
->getId();
1908 $this->setLocalDomain( new DatabaseDomain(
1909 $this->localDomain
->getDatabase(),
1910 $this->localDomain
->getSchema(),
1914 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix, $oldDomain ) {
1915 if ( !$db->getLBInfo( 'foreign' ) ) {
1916 $db->tablePrefix( $prefix );
1922 * @param DatabaseDomain $domain
1924 private function setLocalDomain( DatabaseDomain
$domain ) {
1925 $this->localDomain
= $domain;
1926 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
1927 // always true, gracefully handle the case when they fail to account for escaping.
1928 if ( $this->localDomain
->getTablePrefix() != '' ) {
1929 $this->localDomainIdAlias
=
1930 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
1932 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
1937 * Make PHP ignore user aborts/disconnects until the returned
1938 * value leaves scope. This returns null and does nothing in CLI mode.
1940 * @return ScopedCallback|null
1942 final protected function getScopedPHPBehaviorForCommit() {
1943 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1944 $old = ignore_user_abort( true ); // avoid half-finished operations
1945 return new ScopedCallback( function () use ( $old ) {
1946 ignore_user_abort( $old );
1953 function __destruct() {
1954 // Avoid connection leaks for sanity
1960 * @deprecated since 1.29
1962 class_alias( LoadBalancer
::class, 'LoadBalancer' );