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;
272 public function getLocalDomainID() {
273 return $this->localDomain
->getId();
276 public function resolveDomainID( $domain ) {
277 return ( $domain !== false ) ?
(string)$domain : $this->getLocalDomainID();
281 * Get a LoadMonitor instance
283 * @return ILoadMonitor
285 private function getLoadMonitor() {
286 if ( !isset( $this->loadMonitor
) ) {
288 'LoadMonitor' => LoadMonitor
::class,
289 'LoadMonitorNull' => LoadMonitorNull
::class,
290 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
293 $class = $this->loadMonitorConfig
['class'];
294 if ( isset( $compat[$class] ) ) {
295 $class = $compat[$class];
298 $this->loadMonitor
= new $class(
299 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
300 $this->loadMonitor
->setLogger( $this->replLogger
);
303 return $this->loadMonitor
;
307 * @param array $loads
308 * @param bool|string $domain Domain to get non-lagged for
309 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
310 * @return bool|int|string
312 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
313 $lags = $this->getLagTimes( $domain );
315 # Unset excessively lagged servers
316 foreach ( $lags as $i => $lag ) {
318 # How much lag this server nominally is allowed to have
319 $maxServerLag = $this->servers
[$i]['max lag'] ??
$this->maxLag
; // default
320 # Constrain that futher by $maxLag argument
321 $maxServerLag = min( $maxServerLag, $maxLag );
323 $host = $this->getServerName( $i );
324 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
325 $this->replLogger
->error(
327 ": server {host} is not replicating?", [ 'host' => $host ] );
329 } elseif ( $lag > $maxServerLag ) {
330 $this->replLogger
->info(
332 ": server {host} has {lag} seconds of lag (>= {maxlag})",
333 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
340 # Find out if all the replica DBs with non-zero load are lagged
342 foreach ( $loads as $load ) {
346 # No appropriate DB servers except maybe the master and some replica DBs with zero load
347 # Do NOT use the master
348 # Instead, this function will return false, triggering read-only mode,
349 # and a lagged replica DB will be used instead.
353 if ( count( $loads ) == 0 ) {
357 # Return a random representative of the remainder
358 return ArrayUtils
::pickRandom( $loads );
361 public function getReaderIndex( $group = false, $domain = false ) {
362 if ( count( $this->servers
) == 1 ) {
363 // Skip the load balancing if there's only one server
364 return $this->getWriterIndex();
365 } elseif ( $group === false && $this->readIndex
>= 0 ) {
366 // Shortcut if the generic reader index was already cached
367 return $this->readIndex
;
370 if ( $group !== false ) {
371 // Use the server weight array for this load group
372 if ( isset( $this->groupLoads
[$group] ) ) {
373 $loads = $this->groupLoads
[$group];
375 // No loads for this group, return false and the caller can use some other group
376 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
381 // Use the generic load group
382 $loads = $this->loads
;
385 // Scale the configured load ratios according to each server's load and state
386 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
388 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
389 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
390 if ( $i === false ) {
391 // Replica DB connection unsuccessful
395 if ( $this->waitForPos
&& $i != $this->getWriterIndex() ) {
396 // Before any data queries are run, wait for the server to catch up to the
397 // specified position. This is used to improve session consistency. Note that
398 // when LoadBalancer::waitFor() sets "waitForPos", the waiting triggers here,
399 // so update laggedReplicaMode as needed for consistency.
400 if ( !$this->doWait( $i ) ) {
401 $laggedReplicaMode = true;
405 if ( $this->readIndex
<= 0 && $this->loads
[$i] > 0 && $group === false ) {
406 // Cache the generic reader index for future ungrouped DB_REPLICA handles
407 $this->readIndex
= $i;
408 // Record if the generic reader index is in "lagged replica DB" mode
409 if ( $laggedReplicaMode ) {
410 $this->laggedReplicaMode
= true;
414 $serverName = $this->getServerName( $i );
415 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
421 * @param array $loads List of server weights
422 * @param string|bool $domain
423 * @return array (reader index, lagged replica mode) or false on failure
425 private function pickReaderIndex( array $loads, $domain = false ) {
426 if ( !count( $loads ) ) {
427 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
430 /** @var int|bool $i Index of selected server */
432 /** @var bool $laggedReplicaMode Whether server is considered lagged */
433 $laggedReplicaMode = false;
435 // Quickly look through the available servers for a server that meets criteria...
436 $currentLoads = $loads;
437 while ( count( $currentLoads ) ) {
438 if ( $this->allowLagged ||
$laggedReplicaMode ) {
439 $i = ArrayUtils
::pickRandom( $currentLoads );
442 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
443 // "chronologyCallback" sets "waitForPos" for session consistency.
444 // This triggers doWait() after connect, so it's especially good to
445 // avoid lagged servers so as to avoid excessive delay in that method.
446 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
447 // Aim for <= 1 second of waiting (being too picky can backfire)
448 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
450 if ( $i === false ) {
451 // Any server with less lag than it's 'max lag' param is preferable
452 $i = $this->getRandomNonLagged( $currentLoads, $domain );
454 if ( $i === false && count( $currentLoads ) != 0 ) {
455 // All replica DBs lagged. Switch to read-only mode
456 $this->replLogger
->error(
457 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
458 $i = ArrayUtils
::pickRandom( $currentLoads );
459 $laggedReplicaMode = true;
463 if ( $i === false ) {
464 // pickRandom() returned false.
465 // This is permanent and means the configuration or the load monitor
466 // wants us to return false.
467 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
469 return [ false, false ];
472 $serverName = $this->getServerName( $i );
473 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
475 $conn = $this->openConnection( $i, $domain );
477 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
478 unset( $currentLoads[$i] ); // avoid this server next iteration
483 // Decrement reference counter, we are finished with this connection.
484 // It will be incremented for the caller later.
485 if ( $domain !== false ) {
486 $this->reuseConnection( $conn );
489 // Return this server
493 // If all servers were down, quit now
494 if ( !count( $currentLoads ) ) {
495 $this->connLogger
->error( __METHOD__
. ": all servers down" );
498 return [ $i, $laggedReplicaMode ];
501 public function waitFor( $pos ) {
502 $oldPos = $this->waitForPos
;
504 $this->waitForPos
= $pos;
505 // If a generic reader connection was already established, then wait now
506 $i = $this->readIndex
;
508 if ( !$this->doWait( $i ) ) {
509 $this->laggedReplicaMode
= true;
513 // Restore the older position if it was higher since this is used for lag-protection
514 $this->setWaitForPositionIfHigher( $oldPos );
518 public function waitForOne( $pos, $timeout = null ) {
519 $oldPos = $this->waitForPos
;
521 $this->waitForPos
= $pos;
523 $i = $this->readIndex
;
525 // Pick a generic replica DB if there isn't one yet
526 $readLoads = $this->loads
;
527 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
528 $readLoads = array_filter( $readLoads ); // with non-zero load
529 $i = ArrayUtils
::pickRandom( $readLoads );
533 $ok = $this->doWait( $i, true, $timeout );
535 $ok = true; // no applicable loads
538 # Restore the old position, as this is not used for lag-protection but for throttling
539 $this->waitForPos
= $oldPos;
545 public function waitForAll( $pos, $timeout = null ) {
546 $timeout = $timeout ?
: $this->waitTimeout
;
548 $oldPos = $this->waitForPos
;
550 $this->waitForPos
= $pos;
551 $serverCount = count( $this->servers
);
554 for ( $i = 1; $i < $serverCount; $i++
) {
555 if ( $this->loads
[$i] > 0 ) {
556 $start = microtime( true );
557 $ok = $this->doWait( $i, true, $timeout ) && $ok;
558 $timeout -= intval( microtime( true ) - $start );
559 if ( $timeout <= 0 ) {
560 break; // timeout reached
565 # Restore the old position, as this is not used for lag-protection but for throttling
566 $this->waitForPos
= $oldPos;
573 * @param DBMasterPos|bool $pos
575 private function setWaitForPositionIfHigher( $pos ) {
580 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
581 $this->waitForPos
= $pos;
585 public function getAnyOpenConnection( $i, $flags = 0 ) {
586 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
587 foreach ( $this->conns
as $connsByServer ) {
588 if ( !isset( $connsByServer[$i] ) ) {
592 foreach ( $connsByServer[$i] as $conn ) {
593 if ( !$autocommit ||
$conn->getLBInfo( 'autoCommitOnly' ) ) {
603 * Wait for a given replica DB to catch up to the master pos stored in $this
604 * @param int $index Server index
605 * @param bool $open Check the server even if a new connection has to be made
606 * @param int|null $timeout Max seconds to wait; default is "waitTimeout" given to __construct()
609 protected function doWait( $index, $open = false, $timeout = null ) {
610 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
612 // Check if we already know that the DB has reached this point
613 $server = $this->getServerName( $index );
614 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
615 /** @var DBMasterPos $knownReachedPos */
616 $knownReachedPos = $this->srvCache
->get( $key );
618 $knownReachedPos instanceof DBMasterPos
&&
619 $knownReachedPos->hasReached( $this->waitForPos
)
621 $this->replLogger
->debug(
623 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
624 [ 'dbserver' => $server ]
629 // Find a connection to wait on, creating one if needed and allowed
630 $close = false; // close the connection afterwards
631 $conn = $this->getAnyOpenConnection( $index );
634 $this->replLogger
->debug(
635 __METHOD__
. ': no connection open for {dbserver}',
636 [ 'dbserver' => $server ]
641 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
643 $this->replLogger
->warning(
644 __METHOD__
. ': failed to connect to {dbserver}',
645 [ 'dbserver' => $server ]
650 // Avoid connection spam in waitForAll() when connections
651 // are made just for the sake of doing this lag check.
656 $this->replLogger
->info(
658 ': waiting for replica DB {dbserver} to catch up...',
659 [ 'dbserver' => $server ]
662 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
664 if ( $result === null ) {
665 $this->replLogger
->warning(
666 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
669 'pos' => $this->waitForPos
,
670 'trace' => ( new RuntimeException() )->getTraceAsString()
674 } elseif ( $result == -1 ) {
675 $this->replLogger
->warning(
676 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
679 'pos' => $this->waitForPos
,
680 'trace' => ( new RuntimeException() )->getTraceAsString()
685 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
687 // Remember that the DB reached this point
688 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
692 $this->closeConnection( $conn );
698 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
699 if ( $i === null ||
$i === false ) {
700 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
701 ' with invalid server index' );
704 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
705 $domain = false; // local connection requested
708 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) === self
::CONN_TRX_AUTOCOMMIT
) {
709 // Assuming all servers are of the same type (or similar), which is overwhelmingly
710 // the case, use the master server information to get the attributes. The information
711 // for $i cannot be used since it might be DB_REPLICA, which might require connection
712 // attempts in order to be resolved into a real server index.
713 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
714 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
715 // Callers sometimes want to (a) escape REPEATABLE-READ stateness without locking
716 // rows (e.g. FOR UPDATE) or (b) make small commits during a larger transactions
717 // to reduce lock contention. None of these apply for sqlite and using separate
718 // connections just causes self-deadlocks.
719 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
720 $this->connLogger
->info( __METHOD__
.
721 ': ignoring CONN_TRX_AUTOCOMMIT to avoid deadlocks.' );
725 // Check one "group" per default: the generic pool
726 $defaultGroups = $this->defaultGroup ?
[ $this->defaultGroup
] : [ false ];
728 $groups = ( $groups === false ||
$groups === [] )
732 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
733 $oldConnsOpened = $this->connsOpened
; // connections open now
735 if ( $i == self
::DB_MASTER
) {
736 $i = $this->getWriterIndex();
737 } elseif ( $i == self
::DB_REPLICA
) {
738 # Try to find an available server in any the query groups (in order)
739 foreach ( $groups as $group ) {
740 $groupIndex = $this->getReaderIndex( $group, $domain );
741 if ( $groupIndex !== false ) {
748 # Operation-based index
749 if ( $i == self
::DB_REPLICA
) {
750 $this->lastError
= 'Unknown error'; // reset error string
751 # Try the general server pool if $groups are unavailable.
752 $i = ( $groups === [ false ] )
753 ?
false // don't bother with this if that is what was tried above
754 : $this->getReaderIndex( false, $domain );
755 # Couldn't find a working server in getReaderIndex()?
756 if ( $i === false ) {
757 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
758 // Throw an exception
759 $this->reportConnectionError();
760 return null; // not reached
764 # Now we have an explicit index into the servers array
765 $conn = $this->openConnection( $i, $domain, $flags );
767 // Throw an exception
768 $this->reportConnectionError();
769 return null; // not reached
772 # Profile any new connections that happen
773 if ( $this->connsOpened
> $oldConnsOpened ) {
774 $host = $conn->getServer();
775 $dbname = $conn->getDBname();
776 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
780 # Make master-requested DB handles inherit any read-only mode setting
781 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
787 public function reuseConnection( IDatabase
$conn ) {
788 $serverIndex = $conn->getLBInfo( 'serverIndex' );
789 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
790 if ( $serverIndex === null ||
$refCount === null ) {
792 * This can happen in code like:
793 * foreach ( $dbs as $db ) {
794 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
796 * $lb->reuseConnection( $conn );
798 * When a connection to the local DB is opened in this way, reuseConnection()
802 } elseif ( $conn instanceof DBConnRef
) {
803 // DBConnRef already handles calling reuseConnection() and only passes the live
804 // Database instance to this method. Any caller passing in a DBConnRef is broken.
805 $this->connLogger
->error(
806 __METHOD__
. ": got DBConnRef instance.\n" .
807 ( new RuntimeException() )->getTraceAsString() );
812 if ( $this->disabled
) {
813 return; // DBConnRef handle probably survived longer than the LoadBalancer
816 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
817 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
818 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
820 $connFreeKey = self
::KEY_FOREIGN_FREE
;
821 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
824 $domain = $conn->getDomainID();
825 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
826 throw new InvalidArgumentException( __METHOD__
.
827 ": connection $serverIndex/$domain not found; it may have already been freed." );
828 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
829 throw new InvalidArgumentException( __METHOD__
.
830 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
833 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
834 if ( $refCount <= 0 ) {
835 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
836 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
837 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
838 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
840 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
842 $this->connLogger
->debug( __METHOD__
.
843 ": reference count for $serverIndex/$domain reduced to $refCount" );
847 public function getConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
848 $domain = $this->resolveDomainID( $domain );
850 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain, $flags ) );
853 public function getLazyConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
854 $domain = $this->resolveDomainID( $domain );
856 return new DBConnRef( $this, [ $db, $groups, $domain, $flags ] );
859 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
860 $domain = $this->resolveDomainID( $domain );
862 return new MaintainableDBConnRef(
863 $this, $this->getConnection( $db, $groups, $domain, $flags ) );
866 public function openConnection( $i, $domain = false, $flags = 0 ) {
867 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
868 $domain = false; // local connection requested
871 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
872 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
873 // Load any "waitFor" positions before connecting so that doWait() is triggered
874 $this->connectionAttempted
= true;
875 ( $this->chronologyCallback
)( $this );
878 // Check if an auto-commit connection is being requested. If so, it will not reuse the
879 // main set of DB connections but rather its own pool since:
880 // a) those are usually set to implicitly use transaction rounds via DBO_TRX
881 // b) those must support the use of explicit transaction rounds via beginMasterChanges()
882 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
884 if ( $domain !== false ) {
885 // Connection is to a foreign domain
886 $conn = $this->openForeignConnection( $i, $domain, $flags );
888 // Connection is to the local domain
889 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
890 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
891 $conn = $this->conns
[$connKey][$i][0];
893 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
894 throw new InvalidArgumentException( "No server with index '$i'." );
896 // Open a new connection
897 $server = $this->servers
[$i];
898 $server['serverIndex'] = $i;
899 $server['autoCommitOnly'] = $autoCommit;
900 if ( $this->localDomain
->getDatabase() !== null ) {
901 // Use the local domain table prefix if the local domain is specified
902 $server['tablePrefix'] = $this->localDomain
->getTablePrefix();
904 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
905 $host = $this->getServerName( $i );
906 if ( $conn->isOpen() ) {
907 $this->connLogger
->debug(
908 __METHOD__
. ": connected to database $i at '$host'." );
909 $this->conns
[$connKey][$i][0] = $conn;
911 $this->connLogger
->warning(
912 __METHOD__
. ": failed to connect to database $i at '$host'." );
913 $this->errorConnection
= $conn;
919 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
920 // Connection was made but later unrecoverably lost for some reason.
921 // Do not return a handle that will just throw exceptions on use,
922 // but let the calling code (e.g. getReaderIndex) try another server.
923 // See DatabaseMyslBase::ping() for how this can happen.
924 $this->errorConnection
= $conn;
928 if ( $autoCommit && $conn instanceof IDatabase
) {
929 if ( $conn->trxLevel() ) { // sanity
930 throw new DBUnexpectedError(
932 __METHOD__
. ': CONN_TRX_AUTOCOMMIT handle has a transaction.'
936 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
943 * Open a connection to a foreign DB, or return one if it is already open.
945 * Increments a reference count on the returned connection which locks the
946 * connection to the requested domain. This reference count can be
947 * decremented by calling reuseConnection().
949 * If a connection is open to the appropriate server already, but with the wrong
950 * database, it will be switched to the right database and returned, as long as
951 * it has been freed first with reuseConnection().
953 * On error, returns false, and the connection which caused the
954 * error will be available via $this->errorConnection.
956 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
958 * @param int $i Server index
959 * @param string $domain Domain ID to open
960 * @param int $flags Class CONN_* constant bitfield
963 private function openForeignConnection( $i, $domain, $flags = 0 ) {
964 $domainInstance = DatabaseDomain
::newFromId( $domain );
965 $dbName = $domainInstance->getDatabase();
966 $prefix = $domainInstance->getTablePrefix();
967 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
970 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
971 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
973 $connFreeKey = self
::KEY_FOREIGN_FREE
;
974 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
977 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
978 // Reuse an in-use connection for the same domain
979 $conn = $this->conns
[$connInUseKey][$i][$domain];
980 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
981 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
982 // Reuse a free connection for the same domain
983 $conn = $this->conns
[$connFreeKey][$i][$domain];
984 unset( $this->conns
[$connFreeKey][$i][$domain] );
985 $this->conns
[$connInUseKey][$i][$domain] = $conn;
986 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
987 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
988 // Reuse a free connection from another domain
989 $conn = reset( $this->conns
[$connFreeKey][$i] );
990 $oldDomain = key( $this->conns
[$connFreeKey][$i] );
991 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
992 $this->lastError
= "Error selecting database '$dbName' on server " .
993 $conn->getServer() . " from client host {$this->hostname}";
994 $this->errorConnection
= $conn;
997 $conn->tablePrefix( $prefix );
998 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
999 // Note that if $domain is an empty string, getDomainID() might not match it
1000 $this->conns
[$connInUseKey][$i][$conn->getDomainId()] = $conn;
1001 $this->connLogger
->debug( __METHOD__
.
1002 ": reusing free connection from $oldDomain for $domain" );
1005 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
1006 throw new InvalidArgumentException( "No server with index '$i'." );
1008 // Open a new connection
1009 $server = $this->servers
[$i];
1010 $server['serverIndex'] = $i;
1011 $server['foreignPoolRefCount'] = 0;
1012 $server['foreign'] = true;
1013 $server['autoCommitOnly'] = $autoCommit;
1014 $conn = $this->reallyOpenConnection( $server, $domainInstance );
1015 if ( !$conn->isOpen() ) {
1016 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
1017 $this->errorConnection
= $conn;
1020 $conn->tablePrefix( $prefix ); // as specified
1021 // Note that if $domain is an empty string, getDomainID() might not match it
1022 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1023 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1027 // Increment reference count
1028 if ( $conn instanceof IDatabase
) {
1029 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1030 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1036 public function getServerAttributes( $i ) {
1037 return Database
::attributesFromType(
1038 $this->getServerType( $i ),
1039 $this->servers
[$i]['driver'] ??
null
1044 * Test if the specified index represents an open connection
1046 * @param int $index Server index
1050 private function isOpen( $index ) {
1051 if ( !is_int( $index ) ) {
1055 return (bool)$this->getAnyOpenConnection( $index );
1059 * Open a new network connection to a server (uncached)
1061 * Returns a Database object whether or not the connection was successful.
1063 * @param array $server
1064 * @param DatabaseDomain $domainOverride Use an unspecified domain to not select any database
1066 * @throws DBAccessError
1067 * @throws InvalidArgumentException
1069 protected function reallyOpenConnection( array $server, DatabaseDomain
$domainOverride ) {
1070 if ( $this->disabled
) {
1071 throw new DBAccessError();
1074 // Handle $domainOverride being a specified or an unspecified domain
1075 if ( $domainOverride->getDatabase() === null ) {
1076 // Normally, an RDBMS requires a DB name specified on connection and the $server
1077 // configuration array is assumed to already specify an appropriate DB name.
1078 if ( $server['type'] === 'mysql' ) {
1079 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1080 // and the DB name in $server might not exist due to legacy reasons (the default
1081 // domain used to ignore the local LB domain, even when mismatched).
1082 $server['dbname'] = null;
1085 $server['dbname'] = $domainOverride->getDatabase();
1086 $server['schema'] = $domainOverride->getSchema();
1089 // Let the handle know what the cluster master is (e.g. "db1052")
1090 $masterName = $this->getServerName( $this->getWriterIndex() );
1091 $server['clusterMasterHost'] = $masterName;
1093 // Log when many connection are made on requests
1094 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
1095 $this->perfLogger
->warning( __METHOD__
. ": " .
1096 "{$this->connsOpened}+ connections made (master=$masterName)" );
1099 $server['srvCache'] = $this->srvCache
;
1100 // Set loggers and profilers
1101 $server['connLogger'] = $this->connLogger
;
1102 $server['queryLogger'] = $this->queryLogger
;
1103 $server['errorLogger'] = $this->errorLogger
;
1104 $server['deprecationLogger'] = $this->deprecationLogger
;
1105 $server['profiler'] = $this->profiler
;
1106 $server['trxProfiler'] = $this->trxProfiler
;
1107 // Use the same agent and PHP mode for all DB handles
1108 $server['cliMode'] = $this->cliMode
;
1109 $server['agent'] = $this->agent
;
1110 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1111 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1112 $server['flags'] = $server['flags'] ?? IDatabase
::DBO_DEFAULT
;
1114 // Create a live connection object
1116 $db = Database
::factory( $server['type'], $server );
1117 } catch ( DBConnectionError
$e ) {
1118 // FIXME: This is probably the ugliest thing I have ever done to
1119 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1123 $db->setLBInfo( $server );
1124 $db->setLazyMasterHandle(
1125 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1127 $db->setTableAliases( $this->tableAliases
);
1128 $db->setIndexAliases( $this->indexAliases
);
1130 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1131 if ( $this->trxRoundId
!== false ) {
1132 $this->applyTransactionRoundFlags( $db );
1134 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1135 $db->setTransactionListener( $name, $callback );
1143 * @throws DBConnectionError
1145 private function reportConnectionError() {
1146 $conn = $this->errorConnection
; // the connection which caused the error
1148 'method' => __METHOD__
,
1149 'last_error' => $this->lastError
,
1152 if ( $conn instanceof IDatabase
) {
1153 $context['db_server'] = $conn->getServer();
1154 $this->connLogger
->warning(
1155 __METHOD__
. ": connection error: {last_error} ({db_server})",
1159 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1161 // No last connection, probably due to all servers being too busy
1162 $this->connLogger
->error(
1164 ": LB failure with no last connection. Connection error: {last_error}",
1168 // If all servers were busy, "lastError" will contain something sensible
1169 throw new DBConnectionError( null, $this->lastError
);
1173 public function getWriterIndex() {
1177 public function haveIndex( $i ) {
1178 return array_key_exists( $i, $this->servers
);
1181 public function isNonZeroLoad( $i ) {
1182 return array_key_exists( $i, $this->servers
) && $this->loads
[$i] != 0;
1185 public function getServerCount() {
1186 return count( $this->servers
);
1189 public function getServerName( $i ) {
1190 if ( isset( $this->servers
[$i]['hostName'] ) ) {
1191 $name = $this->servers
[$i]['hostName'];
1192 } elseif ( isset( $this->servers
[$i]['host'] ) ) {
1193 $name = $this->servers
[$i]['host'];
1198 return ( $name != '' ) ?
$name : 'localhost';
1201 public function getServerInfo( $i ) {
1202 if ( isset( $this->servers
[$i] ) ) {
1203 return $this->servers
[$i];
1209 public function getServerType( $i ) {
1210 return $this->servers
[$i]['type'] ??
'unknown';
1213 public function getMasterPos() {
1214 # If this entire request was served from a replica DB without opening a connection to the
1215 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1216 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1217 if ( !$masterConn ) {
1218 $serverCount = count( $this->servers
);
1219 for ( $i = 1; $i < $serverCount; $i++
) {
1220 $conn = $this->getAnyOpenConnection( $i );
1222 return $conn->getReplicaPos();
1226 return $masterConn->getMasterPos();
1232 public function disable() {
1234 $this->disabled
= true;
1237 public function closeAll() {
1238 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1239 $host = $conn->getServer();
1240 $this->connLogger
->debug(
1241 __METHOD__
. ": closing connection to database '$host'." );
1246 self
::KEY_LOCAL
=> [],
1247 self
::KEY_FOREIGN_INUSE
=> [],
1248 self
::KEY_FOREIGN_FREE
=> [],
1249 self
::KEY_LOCAL_NOROUND
=> [],
1250 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1251 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1253 $this->connsOpened
= 0;
1256 public function closeConnection( IDatabase
$conn ) {
1257 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1258 foreach ( $this->conns
as $type => $connsByServer ) {
1259 if ( !isset( $connsByServer[$serverIndex] ) ) {
1263 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1264 if ( $conn === $trackedConn ) {
1265 $host = $this->getServerName( $i );
1266 $this->connLogger
->debug(
1267 __METHOD__
. ": closing connection to database $i at '$host'." );
1268 unset( $this->conns
[$type][$serverIndex][$i] );
1269 --$this->connsOpened
;
1278 public function commitAll( $fname = __METHOD__
) {
1279 $this->commitMasterChanges( $fname );
1280 $this->flushMasterSnapshots( $fname );
1281 $this->flushReplicaSnapshots( $fname );
1284 public function finalizeMasterChanges() {
1285 $this->assertTransactionRoundStage( [ self
::ROUND_CURSORY
, self
::ROUND_FINALIZED
] );
1287 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1288 // Loop until callbacks stop adding callbacks on other connections
1291 $count = 0; // callbacks execution attempts
1292 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$count ) {
1293 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1294 // Any error should cause all (peer) transactions to be rolled back together.
1295 $count +
= $conn->runOnTransactionPreCommitCallbacks();
1298 } while ( $count > 0 );
1299 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1300 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1301 $conn->setTrxEndCallbackSuppression( true );
1303 $this->trxRoundStage
= self
::ROUND_FINALIZED
;
1308 public function approveMasterChanges( array $options ) {
1309 $this->assertTransactionRoundStage( self
::ROUND_FINALIZED
);
1311 $limit = $options['maxWriteDuration'] ??
0;
1313 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1314 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1315 // If atomic sections or explicit transactions are still open, some caller must have
1316 // caught an exception but failed to properly rollback any changes. Detect that and
1317 // throw and error (causing rollback).
1318 if ( $conn->explicitTrxActive() ) {
1319 throw new DBTransactionError(
1321 "Explicit transaction still active. A caller may have caught an error."
1324 // Assert that the time to replicate the transaction will be sane.
1325 // If this fails, then all DB transactions will be rollback back together.
1326 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1327 if ( $limit > 0 && $time > $limit ) {
1328 throw new DBTransactionSizeError(
1330 "Transaction spent $time second(s) in writes, exceeding the limit of $limit.",
1334 // If a connection sits idle while slow queries execute on another, that connection
1335 // may end up dropped before the commit round is reached. Ping servers to detect this.
1336 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1337 throw new DBTransactionError(
1339 "A connection to the {$conn->getDBname()} database was lost before commit."
1343 $this->trxRoundStage
= self
::ROUND_APPROVED
;
1346 public function beginMasterChanges( $fname = __METHOD__
) {
1347 if ( $this->trxRoundId
!== false ) {
1348 throw new DBTransactionError(
1350 "$fname: Transaction round '{$this->trxRoundId}' already started."
1353 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
1355 // Clear any empty transactions (no writes/callbacks) from the implicit round
1356 $this->flushMasterSnapshots( $fname );
1358 $this->trxRoundId
= $fname;
1359 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1360 // Mark applicable handles as participating in this explicit transaction round.
1361 // For each of these handles, any writes and callbacks will be tied to a single
1362 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1363 // are part of an en masse commit or an en masse rollback.
1364 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1365 $this->applyTransactionRoundFlags( $conn );
1367 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1370 public function commitMasterChanges( $fname = __METHOD__
) {
1371 $this->assertTransactionRoundStage( self
::ROUND_APPROVED
);
1375 /** @noinspection PhpUnusedLocalVariableInspection */
1376 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1378 $restore = ( $this->trxRoundId
!== false );
1379 $this->trxRoundId
= false;
1380 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1381 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1382 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1383 $this->forEachOpenMasterConnection(
1384 function ( IDatabase
$conn ) use ( $fname, &$failures ) {
1386 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1387 } catch ( DBError
$e ) {
1388 ( $this->errorLogger
)( $e );
1389 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1394 throw new DBTransactionError(
1396 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1400 // Unmark handles as participating in this explicit transaction round
1401 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1402 $this->undoTransactionRoundFlags( $conn );
1405 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
1408 public function runMasterTransactionIdleCallbacks() {
1409 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1410 $type = IDatabase
::TRIGGER_COMMIT
;
1411 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1412 $type = IDatabase
::TRIGGER_ROLLBACK
;
1414 throw new DBTransactionError(
1416 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1420 $oldStage = $this->trxRoundStage
;
1421 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1423 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1424 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1425 $conn->setTrxEndCallbackSuppression( false );
1428 $e = null; // first exception
1429 // Loop until callbacks stop adding callbacks on other connections
1431 // Run any pending callbacks for each connection...
1432 $count = 0; // callback execution attempts
1433 $this->forEachOpenMasterConnection(
1434 function ( Database
$conn ) use ( $type, &$e, &$count ) {
1435 if ( $conn->trxLevel() ) {
1436 return; // retry in the next iteration, after commit() is called
1439 $count +
= $conn->runOnTransactionIdleCallbacks( $type );
1440 } catch ( Exception
$ex ) {
1445 // Clear out any active transactions left over from callbacks...
1446 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$e ) {
1447 if ( $conn->writesPending() ) {
1448 // A callback from another handle wrote to this one and DBO_TRX is set
1449 $this->queryLogger
->warning( __METHOD__
. ": found writes pending." );
1450 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1451 $this->queryLogger
->warning(
1452 __METHOD__
. ": found writes pending ($fnames).",
1454 'db_server' => $conn->getServer(),
1455 'db_name' => $conn->getDBname()
1458 } elseif ( $conn->trxLevel() ) {
1459 // A callback from another handle read from this one and DBO_TRX is set,
1460 // which can easily happen if there is only one DB (no replicas)
1461 $this->queryLogger
->debug( __METHOD__
. ": found empty transaction." );
1464 $conn->commit( __METHOD__
, $conn::FLUSHING_ALL_PEERS
);
1465 } catch ( Exception
$ex ) {
1469 } while ( $count > 0 );
1471 $this->trxRoundStage
= $oldStage;
1476 public function runMasterTransactionListenerCallbacks() {
1477 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1478 $type = IDatabase
::TRIGGER_COMMIT
;
1479 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1480 $type = IDatabase
::TRIGGER_ROLLBACK
;
1482 throw new DBTransactionError(
1484 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1490 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1491 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1493 $conn->runTransactionListenerCallbacks( $type );
1494 } catch ( Exception
$ex ) {
1498 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1503 public function rollbackMasterChanges( $fname = __METHOD__
) {
1504 $restore = ( $this->trxRoundId
!== false );
1505 $this->trxRoundId
= false;
1506 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1507 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1508 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1511 // Unmark handles as participating in this explicit transaction round
1512 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1513 $this->undoTransactionRoundFlags( $conn );
1516 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
1520 * @param string|string[] $stage
1522 private function assertTransactionRoundStage( $stage ) {
1523 $stages = (array)$stage;
1525 if ( !in_array( $this->trxRoundStage
, $stages, true ) ) {
1526 $stageList = implode(
1528 array_map( function ( $v ) {
1532 throw new DBTransactionError(
1534 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1540 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1542 * Some servers may have neither flag enabled, meaning that they opt out of such
1543 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1544 * when a DB server is used for something like simple key/value storage.
1546 * @param Database $conn
1548 private function applyTransactionRoundFlags( Database
$conn ) {
1549 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1550 return; // transaction rounds do not apply to these connections
1553 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1554 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1555 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1556 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1559 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1560 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1565 * @param Database $conn
1567 private function undoTransactionRoundFlags( Database
$conn ) {
1568 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1569 return; // transaction rounds do not apply to these connections
1572 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1573 $conn->setLBInfo( 'trxRoundId', false );
1576 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1577 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1581 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1582 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) use ( $fname ) {
1583 $conn->flushSnapshot( $fname );
1587 public function flushMasterSnapshots( $fname = __METHOD__
) {
1588 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1589 $conn->flushSnapshot( $fname );
1597 public function getTransactionRoundStage() {
1598 return $this->trxRoundStage
;
1601 public function hasMasterConnection() {
1602 return $this->isOpen( $this->getWriterIndex() );
1605 public function hasMasterChanges() {
1607 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1608 $pending |
= $conn->writesOrCallbacksPending();
1611 return (bool)$pending;
1614 public function lastMasterChangeTimestamp() {
1616 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1617 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1623 public function hasOrMadeRecentMasterChanges( $age = null ) {
1624 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1626 return ( $this->hasMasterChanges()
1627 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1630 public function pendingMasterChangeCallers() {
1632 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1633 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1639 public function getLaggedReplicaMode( $domain = false ) {
1640 // No-op if there is only one DB (also avoids recursion)
1641 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1643 // See if laggedReplicaMode gets set
1644 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1645 $this->reuseConnection( $conn );
1646 } catch ( DBConnectionError
$e ) {
1647 // Avoid expensive re-connect attempts and failures
1648 $this->allReplicasDownMode
= true;
1649 $this->laggedReplicaMode
= true;
1653 return $this->laggedReplicaMode
;
1656 public function laggedReplicaUsed() {
1657 return $this->laggedReplicaMode
;
1663 * @deprecated Since 1.28; use laggedReplicaUsed()
1665 public function laggedSlaveUsed() {
1666 return $this->laggedReplicaUsed();
1669 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1670 if ( $this->readOnlyReason
!== false ) {
1671 return $this->readOnlyReason
;
1672 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1673 if ( $this->allReplicasDownMode
) {
1674 return 'The database has been automatically locked ' .
1675 'until the replica database servers become available';
1677 return 'The database has been automatically locked ' .
1678 'while the replica database servers catch up to the master.';
1680 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1681 return 'The database master is running in read-only mode.';
1688 * @param string $domain Domain ID, or false for the current domain
1689 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1692 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1693 $cache = $this->wanCache
;
1694 $masterServer = $this->getServerName( $this->getWriterIndex() );
1696 return (bool)$cache->getWithSetCallback(
1697 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1698 self
::TTL_CACHE_READONLY
,
1699 function () use ( $domain, $conn ) {
1700 $old = $this->trxProfiler
->setSilenced( true );
1702 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1703 $readOnly = (int)$dbw->serverIsReadOnly();
1705 $this->reuseConnection( $dbw );
1707 } catch ( DBError
$e ) {
1710 $this->trxProfiler
->setSilenced( $old );
1713 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1717 public function allowLagged( $mode = null ) {
1718 if ( $mode === null ) {
1719 return $this->allowLagged
;
1721 $this->allowLagged
= $mode;
1723 return $this->allowLagged
;
1726 public function pingAll() {
1728 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1729 if ( !$conn->ping() ) {
1737 public function forEachOpenConnection( $callback, array $params = [] ) {
1738 foreach ( $this->conns
as $connsByServer ) {
1739 foreach ( $connsByServer as $serverConns ) {
1740 foreach ( $serverConns as $conn ) {
1741 $callback( $conn, ...$params );
1747 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1748 $masterIndex = $this->getWriterIndex();
1749 foreach ( $this->conns
as $connsByServer ) {
1750 if ( isset( $connsByServer[$masterIndex] ) ) {
1751 /** @var IDatabase $conn */
1752 foreach ( $connsByServer[$masterIndex] as $conn ) {
1753 $callback( $conn, ...$params );
1759 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1760 foreach ( $this->conns
as $connsByServer ) {
1761 foreach ( $connsByServer as $i => $serverConns ) {
1762 if ( $i === $this->getWriterIndex() ) {
1763 continue; // skip master
1765 foreach ( $serverConns as $conn ) {
1766 $callback( $conn, ...$params );
1772 public function getMaxLag( $domain = false ) {
1777 if ( $this->getServerCount() <= 1 ) {
1778 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1781 $lagTimes = $this->getLagTimes( $domain );
1782 foreach ( $lagTimes as $i => $lag ) {
1783 if ( $this->loads
[$i] > 0 && $lag > $maxLag ) {
1785 $host = $this->servers
[$i]['host'];
1790 return [ $host, $maxLag, $maxIndex ];
1793 public function getLagTimes( $domain = false ) {
1794 if ( $this->getServerCount() <= 1 ) {
1795 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1798 $knownLagTimes = []; // map of (server index => 0 seconds)
1799 $indexesWithLag = [];
1800 foreach ( $this->servers
as $i => $server ) {
1801 if ( empty( $server['is static'] ) ) {
1802 $indexesWithLag[] = $i; // DB server might have replication lag
1804 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1808 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1811 public function safeGetLag( IDatabase
$conn ) {
1812 if ( $this->getServerCount() <= 1 ) {
1815 return $conn->getLag();
1820 * @param IDatabase $conn
1821 * @param DBMasterPos|bool $pos
1822 * @param int|null $timeout
1825 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
1826 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
1828 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1829 return true; // server is not a replica DB
1833 // Get the current master position, opening a connection if needed
1834 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1835 if ( $masterConn ) {
1836 $pos = $masterConn->getMasterPos();
1838 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1839 $pos = $masterConn->getMasterPos();
1840 $this->closeConnection( $masterConn );
1844 if ( $pos instanceof DBMasterPos
) {
1845 $result = $conn->masterPosWait( $pos, $timeout );
1846 if ( $result == -1 ||
is_null( $result ) ) {
1847 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos}';
1848 $this->replLogger
->warning( $msg, [
1849 'host' => $conn->getServer(),
1851 'trace' => ( new RuntimeException() )->getTraceAsString()
1855 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
1859 $ok = false; // something is misconfigured
1860 $this->replLogger
->error(
1861 __METHOD__
. ': could not get master pos for {host}',
1863 'host' => $conn->getServer(),
1864 'trace' => ( new RuntimeException() )->getTraceAsString()
1872 public function setTransactionListener( $name, callable
$callback = null ) {
1874 $this->trxRecurringCallbacks
[$name] = $callback;
1876 unset( $this->trxRecurringCallbacks
[$name] );
1878 $this->forEachOpenMasterConnection(
1879 function ( IDatabase
$conn ) use ( $name, $callback ) {
1880 $conn->setTransactionListener( $name, $callback );
1885 public function setTableAliases( array $aliases ) {
1886 $this->tableAliases
= $aliases;
1889 public function setIndexAliases( array $aliases ) {
1890 $this->indexAliases
= $aliases;
1893 public function setDomainPrefix( $prefix ) {
1894 // Find connections to explicit foreign domains still marked as in-use...
1896 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
1897 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1898 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1899 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1900 $domainsInUse[] = $conn->getDomainID();
1904 // Do not switch connections to explicit foreign domains unless marked as safe
1905 if ( $domainsInUse ) {
1906 $domains = implode( ', ', $domainsInUse );
1907 throw new DBUnexpectedError( null,
1908 "Foreign domain connections are still in use ($domains)." );
1911 $oldDomain = $this->localDomain
->getId();
1912 $this->setLocalDomain( new DatabaseDomain(
1913 $this->localDomain
->getDatabase(),
1914 $this->localDomain
->getSchema(),
1918 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix, $oldDomain ) {
1919 if ( !$db->getLBInfo( 'foreign' ) ) {
1920 $db->tablePrefix( $prefix );
1926 * @param DatabaseDomain $domain
1928 private function setLocalDomain( DatabaseDomain
$domain ) {
1929 $this->localDomain
= $domain;
1930 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
1931 // always true, gracefully handle the case when they fail to account for escaping.
1932 if ( $this->localDomain
->getTablePrefix() != '' ) {
1933 $this->localDomainIdAlias
=
1934 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
1936 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
1941 * Make PHP ignore user aborts/disconnects until the returned
1942 * value leaves scope. This returns null and does nothing in CLI mode.
1944 * @return ScopedCallback|null
1946 final protected function getScopedPHPBehaviorForCommit() {
1947 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1948 $old = ignore_user_abort( true ); // avoid half-finished operations
1949 return new ScopedCallback( function () use ( $old ) {
1950 ignore_user_abort( $old );
1957 function __destruct() {
1958 // Avoid connection leaks for sanity
1964 * @deprecated since 1.29
1966 class_alias( LoadBalancer
::class, 'LoadBalancer' );