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 object|string 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;
88 private $maxLag = self
::MAX_LAG_DEFAULT
;
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
= 10;
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 if ( isset( $params['maxLag'] ) ) {
204 $this->maxLag
= $params['maxLag'];
207 if ( isset( $params['loadMonitor'] ) ) {
208 $this->loadMonitorConfig
= $params['loadMonitor'];
210 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
212 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
214 foreach ( $params['servers'] as $i => $server ) {
215 $this->loads
[$i] = $server['load'];
216 if ( isset( $server['groupLoads'] ) ) {
217 foreach ( $server['groupLoads'] as $group => $ratio ) {
218 if ( !isset( $this->groupLoads
[$group] ) ) {
219 $this->groupLoads
[$group] = [];
221 $this->groupLoads
[$group][$i] = $ratio;
226 if ( isset( $params['srvCache'] ) ) {
227 $this->srvCache
= $params['srvCache'];
229 $this->srvCache
= new EmptyBagOStuff();
231 if ( isset( $params['wanCache'] ) ) {
232 $this->wanCache
= $params['wanCache'];
234 $this->wanCache
= WANObjectCache
::newEmpty();
236 $this->profiler
= $params['profiler'] ??
null;
237 if ( isset( $params['trxProfiler'] ) ) {
238 $this->trxProfiler
= $params['trxProfiler'];
240 $this->trxProfiler
= new TransactionProfiler();
243 $this->errorLogger
= $params['errorLogger'] ??
function ( Exception
$e ) {
244 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
246 $this->deprecationLogger
= $params['deprecationLogger'] ??
function ( $msg ) {
247 trigger_error( $msg, E_USER_DEPRECATED
);
250 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
251 $this->$key = $params[$key] ??
new NullLogger();
254 $this->hostname
= $params['hostname'] ??
( gethostname() ?
: 'unknown' );
255 $this->cliMode
= $params['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
256 $this->agent
= $params['agent'] ??
'';
258 if ( isset( $params['chronologyCallback'] ) ) {
259 $this->chronologyCallback
= $params['chronologyCallback'];
262 if ( isset( $params['roundStage'] ) ) {
263 if ( $params['roundStage'] === self
::STAGE_POSTCOMMIT_CALLBACKS
) {
264 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
265 } elseif ( $params['roundStage'] === self
::STAGE_POSTROLLBACK_CALLBACKS
) {
266 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
270 $this->defaultGroup
= $params['defaultGroup'] ??
null;
273 public function getLocalDomainID() {
274 return $this->localDomain
->getId();
277 public function resolveDomainID( $domain ) {
278 return ( $domain !== false ) ?
(string)$domain : $this->getLocalDomainID();
282 * Get a LoadMonitor instance
284 * @return ILoadMonitor
286 private function getLoadMonitor() {
287 if ( !isset( $this->loadMonitor
) ) {
289 'LoadMonitor' => LoadMonitor
::class,
290 'LoadMonitorNull' => LoadMonitorNull
::class,
291 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
294 $class = $this->loadMonitorConfig
['class'];
295 if ( isset( $compat[$class] ) ) {
296 $class = $compat[$class];
299 $this->loadMonitor
= new $class(
300 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
301 $this->loadMonitor
->setLogger( $this->replLogger
);
304 return $this->loadMonitor
;
308 * @param array $loads
309 * @param bool|string $domain Domain to get non-lagged for
310 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
311 * @return bool|int|string
313 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
314 $lags = $this->getLagTimes( $domain );
316 # Unset excessively lagged servers
317 foreach ( $lags as $i => $lag ) {
319 # How much lag this server nominally is allowed to have
320 $maxServerLag = $this->servers
[$i]['max lag'] ??
$this->maxLag
; // default
321 # Constrain that futher by $maxLag argument
322 $maxServerLag = min( $maxServerLag, $maxLag );
324 $host = $this->getServerName( $i );
325 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
326 $this->replLogger
->error(
328 ": server {host} is not replicating?", [ 'host' => $host ] );
330 } elseif ( $lag > $maxServerLag ) {
331 $this->replLogger
->info(
333 ": server {host} has {lag} seconds of lag (>= {maxlag})",
334 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
341 # Find out if all the replica DBs with non-zero load are lagged
343 foreach ( $loads as $load ) {
347 # No appropriate DB servers except maybe the master and some replica DBs with zero load
348 # Do NOT use the master
349 # Instead, this function will return false, triggering read-only mode,
350 # and a lagged replica DB will be used instead.
354 if ( count( $loads ) == 0 ) {
358 # Return a random representative of the remainder
359 return ArrayUtils
::pickRandom( $loads );
362 public function getReaderIndex( $group = false, $domain = false ) {
363 if ( count( $this->servers
) == 1 ) {
364 // Skip the load balancing if there's only one server
365 return $this->getWriterIndex();
366 } elseif ( $group === false && $this->readIndex
>= 0 ) {
367 // Shortcut if the generic reader index was already cached
368 return $this->readIndex
;
371 if ( $group !== false ) {
372 // Use the server weight array for this load group
373 if ( isset( $this->groupLoads
[$group] ) ) {
374 $loads = $this->groupLoads
[$group];
376 // No loads for this group, return false and the caller can use some other group
377 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
382 // Use the generic load group
383 $loads = $this->loads
;
386 // Scale the configured load ratios according to each server's load and state
387 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
389 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
390 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
391 if ( $i === false ) {
392 // Replica DB connection unsuccessful
396 if ( $this->waitForPos
&& $i != $this->getWriterIndex() ) {
397 // Before any data queries are run, wait for the server to catch up to the
398 // specified position. This is used to improve session consistency. Note that
399 // when LoadBalancer::waitFor() sets "waitForPos", the waiting triggers here,
400 // so update laggedReplicaMode as needed for consistency.
401 if ( !$this->doWait( $i ) ) {
402 $laggedReplicaMode = true;
406 if ( $this->readIndex
<= 0 && $this->loads
[$i] > 0 && $group === false ) {
407 // Cache the generic reader index for future ungrouped DB_REPLICA handles
408 $this->readIndex
= $i;
409 // Record if the generic reader index is in "lagged replica DB" mode
410 if ( $laggedReplicaMode ) {
411 $this->laggedReplicaMode
= true;
415 $serverName = $this->getServerName( $i );
416 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
422 * @param array $loads List of server weights
423 * @param string|bool $domain
424 * @return array (reader index, lagged replica mode) or false on failure
426 private function pickReaderIndex( array $loads, $domain = false ) {
427 if ( !count( $loads ) ) {
428 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
431 /** @var int|bool $i Index of selected server */
433 /** @var bool $laggedReplicaMode Whether server is considered lagged */
434 $laggedReplicaMode = false;
436 // Quickly look through the available servers for a server that meets criteria...
437 $currentLoads = $loads;
438 while ( count( $currentLoads ) ) {
439 if ( $this->allowLagged ||
$laggedReplicaMode ) {
440 $i = ArrayUtils
::pickRandom( $currentLoads );
443 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
444 // "chronologyCallback" sets "waitForPos" for session consistency.
445 // This triggers doWait() after connect, so it's especially good to
446 // avoid lagged servers so as to avoid excessive delay in that method.
447 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
448 // Aim for <= 1 second of waiting (being too picky can backfire)
449 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
451 if ( $i === false ) {
452 // Any server with less lag than it's 'max lag' param is preferable
453 $i = $this->getRandomNonLagged( $currentLoads, $domain );
455 if ( $i === false && count( $currentLoads ) != 0 ) {
456 // All replica DBs lagged. Switch to read-only mode
457 $this->replLogger
->error(
458 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
459 $i = ArrayUtils
::pickRandom( $currentLoads );
460 $laggedReplicaMode = true;
464 if ( $i === false ) {
465 // pickRandom() returned false.
466 // This is permanent and means the configuration or the load monitor
467 // wants us to return false.
468 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
470 return [ false, false ];
473 $serverName = $this->getServerName( $i );
474 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
476 $conn = $this->openConnection( $i, $domain );
478 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
479 unset( $currentLoads[$i] ); // avoid this server next iteration
484 // Decrement reference counter, we are finished with this connection.
485 // It will be incremented for the caller later.
486 if ( $domain !== false ) {
487 $this->reuseConnection( $conn );
490 // Return this server
494 // If all servers were down, quit now
495 if ( !count( $currentLoads ) ) {
496 $this->connLogger
->error( __METHOD__
. ": all servers down" );
499 return [ $i, $laggedReplicaMode ];
502 public function waitFor( $pos ) {
503 $oldPos = $this->waitForPos
;
505 $this->waitForPos
= $pos;
506 // If a generic reader connection was already established, then wait now
507 $i = $this->readIndex
;
509 if ( !$this->doWait( $i ) ) {
510 $this->laggedReplicaMode
= true;
514 // Restore the older position if it was higher since this is used for lag-protection
515 $this->setWaitForPositionIfHigher( $oldPos );
519 public function waitForOne( $pos, $timeout = null ) {
520 $oldPos = $this->waitForPos
;
522 $this->waitForPos
= $pos;
524 $i = $this->readIndex
;
526 // Pick a generic replica DB if there isn't one yet
527 $readLoads = $this->loads
;
528 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
529 $readLoads = array_filter( $readLoads ); // with non-zero load
530 $i = ArrayUtils
::pickRandom( $readLoads );
534 $ok = $this->doWait( $i, true, $timeout );
536 $ok = true; // no applicable loads
539 # Restore the old position, as this is not used for lag-protection but for throttling
540 $this->waitForPos
= $oldPos;
546 public function waitForAll( $pos, $timeout = null ) {
547 $timeout = $timeout ?
: $this->waitTimeout
;
549 $oldPos = $this->waitForPos
;
551 $this->waitForPos
= $pos;
552 $serverCount = count( $this->servers
);
555 for ( $i = 1; $i < $serverCount; $i++
) {
556 if ( $this->loads
[$i] > 0 ) {
557 $start = microtime( true );
558 $ok = $this->doWait( $i, true, $timeout ) && $ok;
559 $timeout -= intval( microtime( true ) - $start );
560 if ( $timeout <= 0 ) {
561 break; // timeout reached
566 # Restore the old position, as this is not used for lag-protection but for throttling
567 $this->waitForPos
= $oldPos;
574 * @param DBMasterPos|bool $pos
576 private function setWaitForPositionIfHigher( $pos ) {
581 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
582 $this->waitForPos
= $pos;
586 public function getAnyOpenConnection( $i, $flags = 0 ) {
587 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
588 foreach ( $this->conns
as $connsByServer ) {
589 if ( !isset( $connsByServer[$i] ) ) {
593 foreach ( $connsByServer[$i] as $conn ) {
594 if ( !$autocommit ||
$conn->getLBInfo( 'autoCommitOnly' ) ) {
604 * Wait for a given replica DB to catch up to the master pos stored in $this
605 * @param int $index Server index
606 * @param bool $open Check the server even if a new connection has to be made
607 * @param int|null $timeout Max seconds to wait; default is "waitTimeout" given to __construct()
610 protected function doWait( $index, $open = false, $timeout = null ) {
611 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
613 // Check if we already know that the DB has reached this point
614 $server = $this->getServerName( $index );
615 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
616 /** @var DBMasterPos $knownReachedPos */
617 $knownReachedPos = $this->srvCache
->get( $key );
619 $knownReachedPos instanceof DBMasterPos
&&
620 $knownReachedPos->hasReached( $this->waitForPos
)
622 $this->replLogger
->debug(
624 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
625 [ 'dbserver' => $server ]
630 // Find a connection to wait on, creating one if needed and allowed
631 $close = false; // close the connection afterwards
632 $conn = $this->getAnyOpenConnection( $index );
635 $this->replLogger
->debug(
636 __METHOD__
. ': no connection open for {dbserver}',
637 [ 'dbserver' => $server ]
642 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
644 $this->replLogger
->warning(
645 __METHOD__
. ': failed to connect to {dbserver}',
646 [ 'dbserver' => $server ]
651 // Avoid connection spam in waitForAll() when connections
652 // are made just for the sake of doing this lag check.
657 $this->replLogger
->info(
659 ': waiting for replica DB {dbserver} to catch up...',
660 [ 'dbserver' => $server ]
663 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
665 if ( $result === null ) {
666 $this->replLogger
->warning(
667 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
670 'pos' => $this->waitForPos
,
671 'trace' => ( new RuntimeException() )->getTraceAsString()
675 } elseif ( $result == -1 ) {
676 $this->replLogger
->warning(
677 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
680 'pos' => $this->waitForPos
,
681 'trace' => ( new RuntimeException() )->getTraceAsString()
686 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
688 // Remember that the DB reached this point
689 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
693 $this->closeConnection( $conn );
699 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
700 if ( $i === null ||
$i === false ) {
701 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
702 ' with invalid server index' );
705 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
706 $domain = false; // local connection requested
709 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) === self
::CONN_TRX_AUTOCOMMIT
) {
710 // Assuming all servers are of the same type (or similar), which is overwhelmingly
711 // the case, use the master server information to get the attributes. The information
712 // for $i cannot be used since it might be DB_REPLICA, which might require connection
713 // attempts in order to be resolved into a real server index.
714 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
715 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
716 // Callers sometimes want to (a) escape REPEATABLE-READ stateness without locking
717 // rows (e.g. FOR UPDATE) or (b) make small commits during a larger transactions
718 // to reduce lock contention. None of these apply for sqlite and using separate
719 // connections just causes self-deadlocks.
720 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
721 $this->connLogger
->info( __METHOD__
.
722 ': ignoring CONN_TRX_AUTOCOMMIT to avoid deadlocks.' );
726 // Check one "group" per default: the generic pool
727 $defaultGroups = $this->defaultGroup ?
[ $this->defaultGroup
] : [ false ];
729 $groups = ( $groups === false ||
$groups === [] )
733 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
734 $oldConnsOpened = $this->connsOpened
; // connections open now
736 if ( $i == self
::DB_MASTER
) {
737 $i = $this->getWriterIndex();
738 } elseif ( $i == self
::DB_REPLICA
) {
739 # Try to find an available server in any the query groups (in order)
740 foreach ( $groups as $group ) {
741 $groupIndex = $this->getReaderIndex( $group, $domain );
742 if ( $groupIndex !== false ) {
749 # Operation-based index
750 if ( $i == self
::DB_REPLICA
) {
751 $this->lastError
= 'Unknown error'; // reset error string
752 # Try the general server pool if $groups are unavailable.
753 $i = ( $groups === [ false ] )
754 ?
false // don't bother with this if that is what was tried above
755 : $this->getReaderIndex( false, $domain );
756 # Couldn't find a working server in getReaderIndex()?
757 if ( $i === false ) {
758 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
759 // Throw an exception
760 $this->reportConnectionError();
761 return null; // not reached
765 # Now we have an explicit index into the servers array
766 $conn = $this->openConnection( $i, $domain, $flags );
768 // Throw an exception
769 $this->reportConnectionError();
770 return null; // not reached
773 # Profile any new connections that happen
774 if ( $this->connsOpened
> $oldConnsOpened ) {
775 $host = $conn->getServer();
776 $dbname = $conn->getDBname();
777 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
781 # Make master-requested DB handles inherit any read-only mode setting
782 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
788 public function reuseConnection( IDatabase
$conn ) {
789 $serverIndex = $conn->getLBInfo( 'serverIndex' );
790 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
791 if ( $serverIndex === null ||
$refCount === null ) {
793 * This can happen in code like:
794 * foreach ( $dbs as $db ) {
795 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
797 * $lb->reuseConnection( $conn );
799 * When a connection to the local DB is opened in this way, reuseConnection()
803 } elseif ( $conn instanceof DBConnRef
) {
804 // DBConnRef already handles calling reuseConnection() and only passes the live
805 // Database instance to this method. Any caller passing in a DBConnRef is broken.
806 $this->connLogger
->error(
807 __METHOD__
. ": got DBConnRef instance.\n" .
808 ( new RuntimeException() )->getTraceAsString() );
813 if ( $this->disabled
) {
814 return; // DBConnRef handle probably survived longer than the LoadBalancer
817 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
818 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
819 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
821 $connFreeKey = self
::KEY_FOREIGN_FREE
;
822 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
825 $domain = $conn->getDomainID();
826 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
827 throw new InvalidArgumentException( __METHOD__
.
828 ": connection $serverIndex/$domain not found; it may have already been freed." );
829 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
830 throw new InvalidArgumentException( __METHOD__
.
831 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
834 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
835 if ( $refCount <= 0 ) {
836 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
837 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
838 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
839 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
841 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
843 $this->connLogger
->debug( __METHOD__
.
844 ": reference count for $serverIndex/$domain reduced to $refCount" );
848 public function getConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
849 $domain = $this->resolveDomainID( $domain );
851 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain, $flags ) );
854 public function getLazyConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
855 $domain = $this->resolveDomainID( $domain );
857 return new DBConnRef( $this, [ $db, $groups, $domain, $flags ] );
860 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
861 $domain = $this->resolveDomainID( $domain );
863 return new MaintainableDBConnRef(
864 $this, $this->getConnection( $db, $groups, $domain, $flags ) );
867 public function openConnection( $i, $domain = false, $flags = 0 ) {
868 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
869 $domain = false; // local connection requested
872 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
873 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
874 // Load any "waitFor" positions before connecting so that doWait() is triggered
875 $this->connectionAttempted
= true;
876 ( $this->chronologyCallback
)( $this );
879 // Check if an auto-commit connection is being requested. If so, it will not reuse the
880 // main set of DB connections but rather its own pool since:
881 // a) those are usually set to implicitly use transaction rounds via DBO_TRX
882 // b) those must support the use of explicit transaction rounds via beginMasterChanges()
883 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
885 if ( $domain !== false ) {
886 // Connection is to a foreign domain
887 $conn = $this->openForeignConnection( $i, $domain, $flags );
889 // Connection is to the local domain
890 $conn = $this->openLocalConnection( $i, $flags );
893 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
894 // Connection was made but later unrecoverably lost for some reason.
895 // Do not return a handle that will just throw exceptions on use,
896 // but let the calling code (e.g. getReaderIndex) try another server.
897 // See DatabaseMyslBase::ping() for how this can happen.
898 $this->errorConnection
= $conn;
902 if ( $autoCommit && $conn instanceof IDatabase
) {
903 if ( $conn->trxLevel() ) { // sanity
904 throw new DBUnexpectedError(
906 __METHOD__
. ': CONN_TRX_AUTOCOMMIT handle has a transaction.'
910 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
917 * Open a connection to a local DB, or return one if it is already open.
919 * On error, returns false, and the connection which caused the
920 * error will be available via $this->errorConnection.
922 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
924 * @param int $i Server index
925 * @param int $flags Class CONN_* constant bitfield
928 private function openLocalConnection( $i, $flags = 0 ) {
929 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
931 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
932 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
933 $conn = $this->conns
[$connKey][$i][0];
935 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
936 throw new InvalidArgumentException( "No server with index '$i'." );
938 // Open a new connection
939 $server = $this->servers
[$i];
940 $server['serverIndex'] = $i;
941 $server['autoCommitOnly'] = $autoCommit;
942 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
943 $host = $this->getServerName( $i );
944 if ( $conn->isOpen() ) {
945 $this->connLogger
->debug(
946 __METHOD__
. ": connected to database $i at '$host'." );
947 $this->conns
[$connKey][$i][0] = $conn;
949 $this->connLogger
->warning(
950 __METHOD__
. ": failed to connect to database $i at '$host'." );
951 $this->errorConnection
= $conn;
956 // Final sanity check to make sure the right domain is selected
958 $conn instanceof IDatabase
&&
959 !$this->localDomain
->isCompatible( $conn->getDomainID() )
961 throw new UnexpectedValueException(
962 "Got connection to '{$conn->getDomainID()}', " .
963 "but expected local domain ('{$this->localDomain}')." );
970 * Open a connection to a foreign DB, or return one if it is already open.
972 * Increments a reference count on the returned connection which locks the
973 * connection to the requested domain. This reference count can be
974 * decremented by calling reuseConnection().
976 * If a connection is open to the appropriate server already, but with the wrong
977 * database, it will be switched to the right database and returned, as long as
978 * it has been freed first with reuseConnection().
980 * On error, returns false, and the connection which caused the
981 * error will be available via $this->errorConnection.
983 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
985 * @param int $i Server index
986 * @param string $domain Domain ID to open
987 * @param int $flags Class CONN_* constant bitfield
988 * @return Database|bool Returns false on connection error
989 * @throws DBError When database selection fails
991 private function openForeignConnection( $i, $domain, $flags = 0 ) {
992 $domainInstance = DatabaseDomain
::newFromId( $domain );
993 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
996 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
997 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
999 $connFreeKey = self
::KEY_FOREIGN_FREE
;
1000 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
1003 /** @var Database $conn */
1006 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
1007 // Reuse an in-use connection for the same domain
1008 $conn = $this->conns
[$connInUseKey][$i][$domain];
1009 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
1010 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
1011 // Reuse a free connection for the same domain
1012 $conn = $this->conns
[$connFreeKey][$i][$domain];
1013 unset( $this->conns
[$connFreeKey][$i][$domain] );
1014 $this->conns
[$connInUseKey][$i][$domain] = $conn;
1015 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
1016 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
1017 // Reuse a free connection from another domain if possible
1018 foreach ( $this->conns
[$connFreeKey][$i] as $oldDomain => $conn ) {
1019 if ( $domainInstance->getDatabase() !== null ) {
1020 // Check if changing the database will require a new connection.
1021 // In that case, leave the connection handle alone and keep looking.
1022 // This prevents connections from being closed mid-transaction and can
1023 // also avoid overhead if the same database will later be requested.
1025 $conn->databasesAreIndependent() &&
1026 $conn->getDBname() !== $domainInstance->getDatabase()
1030 // Select the new database, schema, and prefix
1031 $conn->selectDomain( $domainInstance );
1033 // Stay on the current database, but update the schema/prefix
1034 $conn->dbSchema( $domainInstance->getSchema() );
1035 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1037 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
1038 // Note that if $domain is an empty string, getDomainID() might not match it
1039 $this->conns
[$connInUseKey][$i][$conn->getDomainId()] = $conn;
1040 $this->connLogger
->debug( __METHOD__
.
1041 ": reusing free connection from $oldDomain for $domain" );
1047 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
1048 throw new InvalidArgumentException( "No server with index '$i'." );
1050 // Open a new connection
1051 $server = $this->servers
[$i];
1052 $server['serverIndex'] = $i;
1053 $server['foreignPoolRefCount'] = 0;
1054 $server['foreign'] = true;
1055 $server['autoCommitOnly'] = $autoCommit;
1056 $conn = $this->reallyOpenConnection( $server, $domainInstance );
1057 if ( !$conn->isOpen() ) {
1058 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
1059 $this->errorConnection
= $conn;
1062 // Note that if $domain is an empty string, getDomainID() might not match it
1063 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1064 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1068 if ( $conn instanceof IDatabase
) {
1069 // Final sanity check to make sure the right domain is selected
1070 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1071 throw new UnexpectedValueException(
1072 "Got connection to '{$conn->getDomainID()}', but expected '$domain'." );
1074 // Increment reference count
1075 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1076 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1082 public function getServerAttributes( $i ) {
1083 return Database
::attributesFromType(
1084 $this->getServerType( $i ),
1085 $this->servers
[$i]['driver'] ??
null
1090 * Test if the specified index represents an open connection
1092 * @param int $index Server index
1096 private function isOpen( $index ) {
1097 if ( !is_int( $index ) ) {
1101 return (bool)$this->getAnyOpenConnection( $index );
1105 * Open a new network connection to a server (uncached)
1107 * Returns a Database object whether or not the connection was successful.
1109 * @param array $server
1110 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
1112 * @throws DBAccessError
1113 * @throws InvalidArgumentException
1115 protected function reallyOpenConnection( array $server, DatabaseDomain
$domain ) {
1116 if ( $this->disabled
) {
1117 throw new DBAccessError();
1120 if ( $domain->getDatabase() === null ) {
1121 // The database domain does not specify a DB name and some database systems require a
1122 // valid DB specified on connection. The $server configuration array contains a default
1123 // DB name to use for connections in such cases.
1124 if ( $server['type'] === 'mysql' ) {
1125 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1126 // and the DB name in $server might not exist due to legacy reasons (the default
1127 // domain used to ignore the local LB domain, even when mismatched).
1128 $server['dbname'] = null;
1131 $server['dbname'] = $domain->getDatabase();
1134 if ( $domain->getSchema() !== null ) {
1135 $server['schema'] = $domain->getSchema();
1138 // It is always possible to connect with any prefix, even the empty string
1139 $server['tablePrefix'] = $domain->getTablePrefix();
1141 // Let the handle know what the cluster master is (e.g. "db1052")
1142 $masterName = $this->getServerName( $this->getWriterIndex() );
1143 $server['clusterMasterHost'] = $masterName;
1145 // Log when many connection are made on requests
1146 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
1147 $this->perfLogger
->warning( __METHOD__
. ": " .
1148 "{$this->connsOpened}+ connections made (master=$masterName)" );
1151 $server['srvCache'] = $this->srvCache
;
1152 // Set loggers and profilers
1153 $server['connLogger'] = $this->connLogger
;
1154 $server['queryLogger'] = $this->queryLogger
;
1155 $server['errorLogger'] = $this->errorLogger
;
1156 $server['deprecationLogger'] = $this->deprecationLogger
;
1157 $server['profiler'] = $this->profiler
;
1158 $server['trxProfiler'] = $this->trxProfiler
;
1159 // Use the same agent and PHP mode for all DB handles
1160 $server['cliMode'] = $this->cliMode
;
1161 $server['agent'] = $this->agent
;
1162 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1163 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1164 $server['flags'] = $server['flags'] ?? IDatabase
::DBO_DEFAULT
;
1166 // Create a live connection object
1168 $db = Database
::factory( $server['type'], $server );
1169 } catch ( DBConnectionError
$e ) {
1170 // FIXME: This is probably the ugliest thing I have ever done to
1171 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1175 $db->setLBInfo( $server );
1176 $db->setLazyMasterHandle(
1177 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1179 $db->setTableAliases( $this->tableAliases
);
1180 $db->setIndexAliases( $this->indexAliases
);
1182 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1183 if ( $this->trxRoundId
!== false ) {
1184 $this->applyTransactionRoundFlags( $db );
1186 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1187 $db->setTransactionListener( $name, $callback );
1195 * @throws DBConnectionError
1197 private function reportConnectionError() {
1198 $conn = $this->errorConnection
; // the connection which caused the error
1200 'method' => __METHOD__
,
1201 'last_error' => $this->lastError
,
1204 if ( $conn instanceof IDatabase
) {
1205 $context['db_server'] = $conn->getServer();
1206 $this->connLogger
->warning(
1207 __METHOD__
. ": connection error: {last_error} ({db_server})",
1211 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1213 // No last connection, probably due to all servers being too busy
1214 $this->connLogger
->error(
1216 ": LB failure with no last connection. Connection error: {last_error}",
1220 // If all servers were busy, "lastError" will contain something sensible
1221 throw new DBConnectionError( null, $this->lastError
);
1225 public function getWriterIndex() {
1229 public function haveIndex( $i ) {
1230 return array_key_exists( $i, $this->servers
);
1233 public function isNonZeroLoad( $i ) {
1234 return array_key_exists( $i, $this->servers
) && $this->loads
[$i] != 0;
1237 public function getServerCount() {
1238 return count( $this->servers
);
1241 public function getServerName( $i ) {
1242 if ( isset( $this->servers
[$i]['hostName'] ) ) {
1243 $name = $this->servers
[$i]['hostName'];
1244 } elseif ( isset( $this->servers
[$i]['host'] ) ) {
1245 $name = $this->servers
[$i]['host'];
1250 return ( $name != '' ) ?
$name : 'localhost';
1253 public function getServerInfo( $i ) {
1254 if ( isset( $this->servers
[$i] ) ) {
1255 return $this->servers
[$i];
1261 public function getServerType( $i ) {
1262 return $this->servers
[$i]['type'] ??
'unknown';
1265 public function getMasterPos() {
1266 # If this entire request was served from a replica DB without opening a connection to the
1267 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1268 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1269 if ( !$masterConn ) {
1270 $serverCount = count( $this->servers
);
1271 for ( $i = 1; $i < $serverCount; $i++
) {
1272 $conn = $this->getAnyOpenConnection( $i );
1274 return $conn->getReplicaPos();
1278 return $masterConn->getMasterPos();
1284 public function disable() {
1286 $this->disabled
= true;
1289 public function closeAll() {
1290 $fname = __METHOD__
;
1291 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( $fname ) {
1292 $host = $conn->getServer();
1293 $this->connLogger
->debug(
1294 $fname . ": closing connection to database '$host'." );
1299 self
::KEY_LOCAL
=> [],
1300 self
::KEY_FOREIGN_INUSE
=> [],
1301 self
::KEY_FOREIGN_FREE
=> [],
1302 self
::KEY_LOCAL_NOROUND
=> [],
1303 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1304 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1306 $this->connsOpened
= 0;
1309 public function closeConnection( IDatabase
$conn ) {
1310 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1311 foreach ( $this->conns
as $type => $connsByServer ) {
1312 if ( !isset( $connsByServer[$serverIndex] ) ) {
1316 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1317 if ( $conn === $trackedConn ) {
1318 $host = $this->getServerName( $i );
1319 $this->connLogger
->debug(
1320 __METHOD__
. ": closing connection to database $i at '$host'." );
1321 unset( $this->conns
[$type][$serverIndex][$i] );
1322 --$this->connsOpened
;
1331 public function commitAll( $fname = __METHOD__
) {
1332 $this->commitMasterChanges( $fname );
1333 $this->flushMasterSnapshots( $fname );
1334 $this->flushReplicaSnapshots( $fname );
1337 public function finalizeMasterChanges() {
1338 $this->assertTransactionRoundStage( [ self
::ROUND_CURSORY
, self
::ROUND_FINALIZED
] );
1340 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1341 // Loop until callbacks stop adding callbacks on other connections
1344 $count = 0; // callbacks execution attempts
1345 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$count ) {
1346 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1347 // Any error should cause all (peer) transactions to be rolled back together.
1348 $count +
= $conn->runOnTransactionPreCommitCallbacks();
1351 } while ( $count > 0 );
1352 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1353 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1354 $conn->setTrxEndCallbackSuppression( true );
1356 $this->trxRoundStage
= self
::ROUND_FINALIZED
;
1361 public function approveMasterChanges( array $options ) {
1362 $this->assertTransactionRoundStage( self
::ROUND_FINALIZED
);
1364 $limit = $options['maxWriteDuration'] ??
0;
1366 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1367 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1368 // If atomic sections or explicit transactions are still open, some caller must have
1369 // caught an exception but failed to properly rollback any changes. Detect that and
1370 // throw and error (causing rollback).
1371 $conn->assertNoOpenTransactions();
1372 // Assert that the time to replicate the transaction will be sane.
1373 // If this fails, then all DB transactions will be rollback back together.
1374 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1375 if ( $limit > 0 && $time > $limit ) {
1376 throw new DBTransactionSizeError(
1378 "Transaction spent $time second(s) in writes, exceeding the limit of $limit.",
1382 // If a connection sits idle while slow queries execute on another, that connection
1383 // may end up dropped before the commit round is reached. Ping servers to detect this.
1384 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1385 throw new DBTransactionError(
1387 "A connection to the {$conn->getDBname()} database was lost before commit."
1391 $this->trxRoundStage
= self
::ROUND_APPROVED
;
1394 public function beginMasterChanges( $fname = __METHOD__
) {
1395 if ( $this->trxRoundId
!== false ) {
1396 throw new DBTransactionError(
1398 "$fname: Transaction round '{$this->trxRoundId}' already started."
1401 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
1403 // Clear any empty transactions (no writes/callbacks) from the implicit round
1404 $this->flushMasterSnapshots( $fname );
1406 $this->trxRoundId
= $fname;
1407 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1408 // Mark applicable handles as participating in this explicit transaction round.
1409 // For each of these handles, any writes and callbacks will be tied to a single
1410 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1411 // are part of an en masse commit or an en masse rollback.
1412 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1413 $this->applyTransactionRoundFlags( $conn );
1415 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1418 public function commitMasterChanges( $fname = __METHOD__
) {
1419 $this->assertTransactionRoundStage( self
::ROUND_APPROVED
);
1423 /** @noinspection PhpUnusedLocalVariableInspection */
1424 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1426 $restore = ( $this->trxRoundId
!== false );
1427 $this->trxRoundId
= false;
1428 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1429 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1430 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1431 $this->forEachOpenMasterConnection(
1432 function ( IDatabase
$conn ) use ( $fname, &$failures ) {
1434 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1435 } catch ( DBError
$e ) {
1436 ( $this->errorLogger
)( $e );
1437 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1442 throw new DBTransactionError(
1444 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1448 // Unmark handles as participating in this explicit transaction round
1449 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1450 $this->undoTransactionRoundFlags( $conn );
1453 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
1456 public function runMasterTransactionIdleCallbacks() {
1457 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1458 $type = IDatabase
::TRIGGER_COMMIT
;
1459 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1460 $type = IDatabase
::TRIGGER_ROLLBACK
;
1462 throw new DBTransactionError(
1464 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1468 $oldStage = $this->trxRoundStage
;
1469 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1471 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1472 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1473 $conn->setTrxEndCallbackSuppression( false );
1476 $e = null; // first exception
1477 $fname = __METHOD__
;
1478 // Loop until callbacks stop adding callbacks on other connections
1480 // Run any pending callbacks for each connection...
1481 $count = 0; // callback execution attempts
1482 $this->forEachOpenMasterConnection(
1483 function ( Database
$conn ) use ( $type, &$e, &$count ) {
1484 if ( $conn->trxLevel() ) {
1485 return; // retry in the next iteration, after commit() is called
1488 $count +
= $conn->runOnTransactionIdleCallbacks( $type );
1489 } catch ( Exception
$ex ) {
1494 // Clear out any active transactions left over from callbacks...
1495 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$e, $fname ) {
1496 if ( $conn->writesPending() ) {
1497 // A callback from another handle wrote to this one and DBO_TRX is set
1498 $this->queryLogger
->warning( $fname . ": found writes pending." );
1499 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1500 $this->queryLogger
->warning(
1501 $fname . ": found writes pending ($fnames).",
1503 'db_server' => $conn->getServer(),
1504 'db_name' => $conn->getDBname()
1507 } elseif ( $conn->trxLevel() ) {
1508 // A callback from another handle read from this one and DBO_TRX is set,
1509 // which can easily happen if there is only one DB (no replicas)
1510 $this->queryLogger
->debug( $fname . ": found empty transaction." );
1513 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1514 } catch ( Exception
$ex ) {
1518 } while ( $count > 0 );
1520 $this->trxRoundStage
= $oldStage;
1525 public function runMasterTransactionListenerCallbacks() {
1526 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1527 $type = IDatabase
::TRIGGER_COMMIT
;
1528 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1529 $type = IDatabase
::TRIGGER_ROLLBACK
;
1531 throw new DBTransactionError(
1533 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1539 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1540 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1542 $conn->runTransactionListenerCallbacks( $type );
1543 } catch ( Exception
$ex ) {
1547 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1552 public function rollbackMasterChanges( $fname = __METHOD__
) {
1553 $restore = ( $this->trxRoundId
!== false );
1554 $this->trxRoundId
= false;
1555 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1556 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1557 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1560 // Unmark handles as participating in this explicit transaction round
1561 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1562 $this->undoTransactionRoundFlags( $conn );
1565 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
1569 * @param string|string[] $stage
1571 private function assertTransactionRoundStage( $stage ) {
1572 $stages = (array)$stage;
1574 if ( !in_array( $this->trxRoundStage
, $stages, true ) ) {
1575 $stageList = implode(
1577 array_map( function ( $v ) {
1581 throw new DBTransactionError(
1583 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1589 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1591 * Some servers may have neither flag enabled, meaning that they opt out of such
1592 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1593 * when a DB server is used for something like simple key/value storage.
1595 * @param Database $conn
1597 private function applyTransactionRoundFlags( Database
$conn ) {
1598 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1599 return; // transaction rounds do not apply to these connections
1602 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1603 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1604 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1605 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1608 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1609 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1614 * @param Database $conn
1616 private function undoTransactionRoundFlags( Database
$conn ) {
1617 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1618 return; // transaction rounds do not apply to these connections
1621 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1622 $conn->setLBInfo( 'trxRoundId', false );
1625 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1626 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1630 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1631 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) use ( $fname ) {
1632 $conn->flushSnapshot( $fname );
1636 public function flushMasterSnapshots( $fname = __METHOD__
) {
1637 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1638 $conn->flushSnapshot( $fname );
1646 public function getTransactionRoundStage() {
1647 return $this->trxRoundStage
;
1650 public function hasMasterConnection() {
1651 return $this->isOpen( $this->getWriterIndex() );
1654 public function hasMasterChanges() {
1656 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1657 $pending |
= $conn->writesOrCallbacksPending();
1660 return (bool)$pending;
1663 public function lastMasterChangeTimestamp() {
1665 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1666 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1672 public function hasOrMadeRecentMasterChanges( $age = null ) {
1673 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1675 return ( $this->hasMasterChanges()
1676 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1679 public function pendingMasterChangeCallers() {
1681 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1682 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1688 public function getLaggedReplicaMode( $domain = false ) {
1689 // No-op if there is only one DB (also avoids recursion)
1690 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1692 // See if laggedReplicaMode gets set
1693 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1694 $this->reuseConnection( $conn );
1695 } catch ( DBConnectionError
$e ) {
1696 // Avoid expensive re-connect attempts and failures
1697 $this->allReplicasDownMode
= true;
1698 $this->laggedReplicaMode
= true;
1702 return $this->laggedReplicaMode
;
1705 public function laggedReplicaUsed() {
1706 return $this->laggedReplicaMode
;
1712 * @deprecated Since 1.28; use laggedReplicaUsed()
1714 public function laggedSlaveUsed() {
1715 return $this->laggedReplicaUsed();
1718 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1719 if ( $this->readOnlyReason
!== false ) {
1720 return $this->readOnlyReason
;
1721 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1722 if ( $this->allReplicasDownMode
) {
1723 return 'The database has been automatically locked ' .
1724 'until the replica database servers become available';
1726 return 'The database has been automatically locked ' .
1727 'while the replica database servers catch up to the master.';
1729 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1730 return 'The database master is running in read-only mode.';
1737 * @param string $domain Domain ID, or false for the current domain
1738 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1741 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1742 $cache = $this->wanCache
;
1743 $masterServer = $this->getServerName( $this->getWriterIndex() );
1745 return (bool)$cache->getWithSetCallback(
1746 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1747 self
::TTL_CACHE_READONLY
,
1748 function () use ( $domain, $conn ) {
1749 $old = $this->trxProfiler
->setSilenced( true );
1751 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1752 $readOnly = (int)$dbw->serverIsReadOnly();
1754 $this->reuseConnection( $dbw );
1756 } catch ( DBError
$e ) {
1759 $this->trxProfiler
->setSilenced( $old );
1762 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1766 public function allowLagged( $mode = null ) {
1767 if ( $mode === null ) {
1768 return $this->allowLagged
;
1770 $this->allowLagged
= $mode;
1772 return $this->allowLagged
;
1775 public function pingAll() {
1777 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1778 if ( !$conn->ping() ) {
1786 public function forEachOpenConnection( $callback, array $params = [] ) {
1787 foreach ( $this->conns
as $connsByServer ) {
1788 foreach ( $connsByServer as $serverConns ) {
1789 foreach ( $serverConns as $conn ) {
1790 $callback( $conn, ...$params );
1796 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1797 $masterIndex = $this->getWriterIndex();
1798 foreach ( $this->conns
as $connsByServer ) {
1799 if ( isset( $connsByServer[$masterIndex] ) ) {
1800 /** @var IDatabase $conn */
1801 foreach ( $connsByServer[$masterIndex] as $conn ) {
1802 $callback( $conn, ...$params );
1808 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1809 foreach ( $this->conns
as $connsByServer ) {
1810 foreach ( $connsByServer as $i => $serverConns ) {
1811 if ( $i === $this->getWriterIndex() ) {
1812 continue; // skip master
1814 foreach ( $serverConns as $conn ) {
1815 $callback( $conn, ...$params );
1821 public function getMaxLag( $domain = false ) {
1826 if ( $this->getServerCount() <= 1 ) {
1827 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1830 $lagTimes = $this->getLagTimes( $domain );
1831 foreach ( $lagTimes as $i => $lag ) {
1832 if ( $this->loads
[$i] > 0 && $lag > $maxLag ) {
1834 $host = $this->servers
[$i]['host'];
1839 return [ $host, $maxLag, $maxIndex ];
1842 public function getLagTimes( $domain = false ) {
1843 if ( $this->getServerCount() <= 1 ) {
1844 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1847 $knownLagTimes = []; // map of (server index => 0 seconds)
1848 $indexesWithLag = [];
1849 foreach ( $this->servers
as $i => $server ) {
1850 if ( empty( $server['is static'] ) ) {
1851 $indexesWithLag[] = $i; // DB server might have replication lag
1853 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1857 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1860 public function safeGetLag( IDatabase
$conn ) {
1861 if ( $this->getServerCount() <= 1 ) {
1864 return $conn->getLag();
1869 * @param IDatabase $conn
1870 * @param DBMasterPos|bool $pos
1871 * @param int|null $timeout
1874 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
1875 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
1877 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1878 return true; // server is not a replica DB
1882 // Get the current master position, opening a connection if needed
1883 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1884 if ( $masterConn ) {
1885 $pos = $masterConn->getMasterPos();
1887 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1888 $pos = $masterConn->getMasterPos();
1889 $this->closeConnection( $masterConn );
1893 if ( $pos instanceof DBMasterPos
) {
1894 $result = $conn->masterPosWait( $pos, $timeout );
1895 if ( $result == -1 ||
is_null( $result ) ) {
1896 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos}';
1897 $this->replLogger
->warning( $msg, [
1898 'host' => $conn->getServer(),
1900 'trace' => ( new RuntimeException() )->getTraceAsString()
1904 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
1908 $ok = false; // something is misconfigured
1909 $this->replLogger
->error(
1910 __METHOD__
. ': could not get master pos for {host}',
1912 'host' => $conn->getServer(),
1913 'trace' => ( new RuntimeException() )->getTraceAsString()
1921 public function setTransactionListener( $name, callable
$callback = null ) {
1923 $this->trxRecurringCallbacks
[$name] = $callback;
1925 unset( $this->trxRecurringCallbacks
[$name] );
1927 $this->forEachOpenMasterConnection(
1928 function ( IDatabase
$conn ) use ( $name, $callback ) {
1929 $conn->setTransactionListener( $name, $callback );
1934 public function setTableAliases( array $aliases ) {
1935 $this->tableAliases
= $aliases;
1938 public function setIndexAliases( array $aliases ) {
1939 $this->indexAliases
= $aliases;
1942 public function setDomainPrefix( $prefix ) {
1943 // Find connections to explicit foreign domains still marked as in-use...
1945 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
1946 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1947 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1948 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1949 $domainsInUse[] = $conn->getDomainID();
1953 // Do not switch connections to explicit foreign domains unless marked as safe
1954 if ( $domainsInUse ) {
1955 $domains = implode( ', ', $domainsInUse );
1956 throw new DBUnexpectedError( null,
1957 "Foreign domain connections are still in use ($domains)." );
1960 $this->setLocalDomain( new DatabaseDomain(
1961 $this->localDomain
->getDatabase(),
1962 $this->localDomain
->getSchema(),
1966 // Update the prefix for all local connections...
1967 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1968 if ( !$db->getLBInfo( 'foreign' ) ) {
1969 $db->tablePrefix( $prefix );
1975 * @param DatabaseDomain $domain
1977 private function setLocalDomain( DatabaseDomain
$domain ) {
1978 $this->localDomain
= $domain;
1979 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
1980 // always true, gracefully handle the case when they fail to account for escaping.
1981 if ( $this->localDomain
->getTablePrefix() != '' ) {
1982 $this->localDomainIdAlias
=
1983 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
1985 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
1990 * Make PHP ignore user aborts/disconnects until the returned
1991 * value leaves scope. This returns null and does nothing in CLI mode.
1993 * @return ScopedCallback|null
1995 final protected function getScopedPHPBehaviorForCommit() {
1996 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1997 $old = ignore_user_abort( true ); // avoid half-finished operations
1998 return new ScopedCallback( function () use ( $old ) {
1999 ignore_user_abort( $old );
2006 function __destruct() {
2007 // Avoid connection leaks for sanity
2013 * @deprecated since 1.29
2015 class_alias( LoadBalancer
::class, 'LoadBalancer' );