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 array[] Map of (server index => server config array) */
43 /** @var Database[][][] Map of (connection category => server index => IDatabase[]) */
45 /** @var float[] Map of (server index => weight) */
47 /** @var array[] Map of (group => server index => weight) */
49 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
51 /** @var int Seconds to spend waiting on replica DB lag to resolve */
53 /** @var array The LoadMonitor configuration */
54 private $loadMonitorConfig;
55 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
56 private $tableAliases = [];
57 /** @var string[] Map of (index alias => index) */
58 private $indexAliases = [];
60 /** @var ILoadMonitor */
62 /** @var callable|null Callback to run before the first connection attempt */
63 private $chronologyCallback;
66 /** @var WANObjectCache */
68 /** @var object|string Class name or object With profileIn/profileOut methods */
70 /** @var TransactionProfiler */
71 protected $trxProfiler;
72 /** @var LoggerInterface */
73 protected $replLogger;
74 /** @var LoggerInterface */
75 protected $connLogger;
76 /** @var LoggerInterface */
77 protected $queryLogger;
78 /** @var LoggerInterface */
79 protected $perfLogger;
81 /** @var Database DB connection object that caused a problem */
82 private $errorConnection;
83 /** @var int The generic (not query grouped) replica DB index (of $mServers) */
85 /** @var bool|DBMasterPos False if not set */
87 /** @var bool Whether the generic reader fell back to a lagged replica DB */
88 private $laggedReplicaMode = false;
89 /** @var bool Whether the generic reader fell back to a lagged replica DB */
90 private $allReplicasDownMode = false;
91 /** @var string The last DB selection or connection error */
92 private $lastError = 'Unknown error';
93 /** @var string|bool Reason the LB is read-only or false if not */
94 private $readOnlyReason = false;
95 /** @var int Total connections opened */
96 private $connsOpened = 0;
97 /** @var string|bool String if a requested DBO_TRX transaction round is active */
98 private $trxRoundId = false;
99 /** @var array[] Map of (name => callable) */
100 private $trxRecurringCallbacks = [];
101 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
102 private $localDomain;
103 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
104 private $localDomainIdAlias;
105 /** @var string Current server name */
107 /** @var bool Whether this PHP instance is for a CLI script */
109 /** @var string Agent name for query profiling */
112 /** @var callable Exception logger */
113 private $errorLogger;
114 /** @var callable Deprecation logger */
115 private $deprecationLogger;
118 private $disabled = false;
119 /** @var bool Whether any connection has been attempted yet */
120 private $connectionAttempted = false;
122 private $maxLag = self
::MAX_LAG_DEFAULT
;
123 /** @var string Stage of the current transaction round in the transaction round life-cycle */
124 private $trxRoundStage = self
::ROUND_CURSORY
;
126 /** @var int Warn when this many connection are held */
127 const CONN_HELD_WARN_THRESHOLD
= 10;
129 /** @var int Default 'maxLag' when unspecified */
130 const MAX_LAG_DEFAULT
= 10;
131 /** @var int Default 'waitTimeout' when unspecified */
132 const MAX_WAIT_DEFAULT
= 10;
133 /** @var int Seconds to cache master server read-only status */
134 const TTL_CACHE_READONLY
= 5;
136 const KEY_LOCAL
= 'local';
137 const KEY_FOREIGN_FREE
= 'foreignFree';
138 const KEY_FOREIGN_INUSE
= 'foreignInUse';
140 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
141 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
142 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
144 /** @var string Transaction round, explicit or implicit, has not finished writing */
145 const ROUND_CURSORY
= 'cursory';
146 /** @var string Transaction round writes are complete and ready for pre-commit checks */
147 const ROUND_FINALIZED
= 'finalized';
148 /** @var string Transaction round passed final pre-commit checks */
149 const ROUND_APPROVED
= 'approved';
150 /** @var string Transaction round was committed and post-commit callbacks must be run */
151 const ROUND_COMMIT_CALLBACKS
= 'commit-callbacks';
152 /** @var string Transaction round was rolled back and post-rollback callbacks must be run */
153 const ROUND_ROLLBACK_CALLBACKS
= 'rollback-callbacks';
154 /** @var string Transaction round encountered an error */
155 const ROUND_ERROR
= 'error';
157 public function __construct( array $params ) {
158 if ( !isset( $params['servers'] ) ) {
159 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
161 $this->servers
= $params['servers'];
162 foreach ( $this->servers
as $i => $server ) {
164 $this->servers
[$i]['master'] = true;
166 $this->servers
[$i]['replica'] = true;
170 $localDomain = isset( $params['localDomain'] )
171 ? DatabaseDomain
::newFromId( $params['localDomain'] )
172 : DatabaseDomain
::newUnspecified();
173 $this->setLocalDomain( $localDomain );
175 $this->waitTimeout
= $params['waitTimeout'] ?? self
::MAX_WAIT_DEFAULT
;
177 $this->readIndex
= -1;
179 // Connection were transaction rounds may be applied
180 self
::KEY_LOCAL
=> [],
181 self
::KEY_FOREIGN_INUSE
=> [],
182 self
::KEY_FOREIGN_FREE
=> [],
183 // Auto-committing counterpart connections that ignore transaction rounds
184 self
::KEY_LOCAL_NOROUND
=> [],
185 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
186 self
::KEY_FOREIGN_FREE_NOROUND
=> []
189 $this->waitForPos
= false;
190 $this->allowLagged
= false;
192 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
193 $this->readOnlyReason
= $params['readOnlyReason'];
196 if ( isset( $params['maxLag'] ) ) {
197 $this->maxLag
= $params['maxLag'];
200 if ( isset( $params['loadMonitor'] ) ) {
201 $this->loadMonitorConfig
= $params['loadMonitor'];
203 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
205 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
207 foreach ( $params['servers'] as $i => $server ) {
208 $this->loads
[$i] = $server['load'];
209 if ( isset( $server['groupLoads'] ) ) {
210 foreach ( $server['groupLoads'] as $group => $ratio ) {
211 if ( !isset( $this->groupLoads
[$group] ) ) {
212 $this->groupLoads
[$group] = [];
214 $this->groupLoads
[$group][$i] = $ratio;
219 if ( isset( $params['srvCache'] ) ) {
220 $this->srvCache
= $params['srvCache'];
222 $this->srvCache
= new EmptyBagOStuff();
224 if ( isset( $params['wanCache'] ) ) {
225 $this->wanCache
= $params['wanCache'];
227 $this->wanCache
= WANObjectCache
::newEmpty();
229 $this->profiler
= $params['profiler'] ??
null;
230 if ( isset( $params['trxProfiler'] ) ) {
231 $this->trxProfiler
= $params['trxProfiler'];
233 $this->trxProfiler
= new TransactionProfiler();
236 $this->errorLogger
= $params['errorLogger'] ??
function ( Exception
$e ) {
237 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
239 $this->deprecationLogger
= $params['deprecationLogger'] ??
function ( $msg ) {
240 trigger_error( $msg, E_USER_DEPRECATED
);
243 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
244 $this->$key = $params[$key] ??
new NullLogger();
247 $this->host
= $params['hostname'] ??
( gethostname() ?
: 'unknown' );
248 $this->cliMode
= $params['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
249 $this->agent
= $params['agent'] ??
'';
251 if ( isset( $params['chronologyCallback'] ) ) {
252 $this->chronologyCallback
= $params['chronologyCallback'];
255 if ( isset( $params['roundStage'] ) ) {
256 if ( $params['roundStage'] === self
::STAGE_POSTCOMMIT_CALLBACKS
) {
257 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
258 } elseif ( $params['roundStage'] === self
::STAGE_POSTROLLBACK_CALLBACKS
) {
259 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
265 * Get the local (and default) database domain ID of connection handles
267 * @see DatabaseDomain
268 * @return string Database domain ID; this specifies DB name, schema, and table prefix
271 public function getLocalDomainID() {
272 return $this->localDomain
->getId();
276 * Get a LoadMonitor instance
278 * @return ILoadMonitor
280 private function getLoadMonitor() {
281 if ( !isset( $this->loadMonitor
) ) {
283 'LoadMonitor' => LoadMonitor
::class,
284 'LoadMonitorNull' => LoadMonitorNull
::class,
285 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
288 $class = $this->loadMonitorConfig
['class'];
289 if ( isset( $compat[$class] ) ) {
290 $class = $compat[$class];
293 $this->loadMonitor
= new $class(
294 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
295 $this->loadMonitor
->setLogger( $this->replLogger
);
298 return $this->loadMonitor
;
302 * @param array $loads
303 * @param bool|string $domain Domain to get non-lagged for
304 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
305 * @return bool|int|string
307 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
308 $lags = $this->getLagTimes( $domain );
310 # Unset excessively lagged servers
311 foreach ( $lags as $i => $lag ) {
313 # How much lag this server nominally is allowed to have
314 $maxServerLag = $this->servers
[$i]['max lag'] ??
$this->maxLag
; // default
315 # Constrain that futher by $maxLag argument
316 $maxServerLag = min( $maxServerLag, $maxLag );
318 $host = $this->getServerName( $i );
319 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
320 $this->replLogger
->error(
322 ": server {host} is not replicating?", [ 'host' => $host ] );
324 } elseif ( $lag > $maxServerLag ) {
325 $this->replLogger
->info(
327 ": server {host} has {lag} seconds of lag (>= {maxlag})",
328 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
335 # Find out if all the replica DBs with non-zero load are lagged
337 foreach ( $loads as $load ) {
341 # No appropriate DB servers except maybe the master and some replica DBs with zero load
342 # Do NOT use the master
343 # Instead, this function will return false, triggering read-only mode,
344 # and a lagged replica DB will be used instead.
348 if ( count( $loads ) == 0 ) {
352 # Return a random representative of the remainder
353 return ArrayUtils
::pickRandom( $loads );
356 public function getReaderIndex( $group = false, $domain = false ) {
357 if ( count( $this->servers
) == 1 ) {
358 // Skip the load balancing if there's only one server
359 return $this->getWriterIndex();
360 } elseif ( $group === false && $this->readIndex
>= 0 ) {
361 // Shortcut if the generic reader index was already cached
362 return $this->readIndex
;
365 if ( $group !== false ) {
366 // Use the server weight array for this load group
367 if ( isset( $this->groupLoads
[$group] ) ) {
368 $loads = $this->groupLoads
[$group];
370 // No loads for this group, return false and the caller can use some other group
371 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
376 // Use the generic load group
377 $loads = $this->loads
;
380 // Scale the configured load ratios according to each server's load and state
381 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
383 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
384 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
385 if ( $i === false ) {
386 // Replica DB connection unsuccessful
390 if ( $this->waitForPos
&& $i != $this->getWriterIndex() ) {
391 // Before any data queries are run, wait for the server to catch up to the
392 // specified position. This is used to improve session consistency. Note that
393 // when LoadBalancer::waitFor() sets "waitForPos", the waiting triggers here,
394 // so update laggedReplicaMode as needed for consistency.
395 if ( !$this->doWait( $i ) ) {
396 $laggedReplicaMode = true;
400 if ( $this->readIndex
<= 0 && $this->loads
[$i] > 0 && $group === false ) {
401 // Cache the generic reader index for future ungrouped DB_REPLICA handles
402 $this->readIndex
= $i;
403 // Record if the generic reader index is in "lagged replica DB" mode
404 if ( $laggedReplicaMode ) {
405 $this->laggedReplicaMode
= true;
409 $serverName = $this->getServerName( $i );
410 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
416 * @param array $loads List of server weights
417 * @param string|bool $domain
418 * @return array (reader index, lagged replica mode) or false on failure
420 private function pickReaderIndex( array $loads, $domain = false ) {
421 if ( !count( $loads ) ) {
422 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
425 /** @var int|bool $i Index of selected server */
427 /** @var bool $laggedReplicaMode Whether server is considered lagged */
428 $laggedReplicaMode = false;
430 // Quickly look through the available servers for a server that meets criteria...
431 $currentLoads = $loads;
432 while ( count( $currentLoads ) ) {
433 if ( $this->allowLagged ||
$laggedReplicaMode ) {
434 $i = ArrayUtils
::pickRandom( $currentLoads );
437 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
438 // "chronologyCallback" sets "waitForPos" for session consistency.
439 // This triggers doWait() after connect, so it's especially good to
440 // avoid lagged servers so as to avoid excessive delay in that method.
441 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
442 // Aim for <= 1 second of waiting (being too picky can backfire)
443 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
445 if ( $i === false ) {
446 // Any server with less lag than it's 'max lag' param is preferable
447 $i = $this->getRandomNonLagged( $currentLoads, $domain );
449 if ( $i === false && count( $currentLoads ) != 0 ) {
450 // All replica DBs lagged. Switch to read-only mode
451 $this->replLogger
->error(
452 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
453 $i = ArrayUtils
::pickRandom( $currentLoads );
454 $laggedReplicaMode = true;
458 if ( $i === false ) {
459 // pickRandom() returned false.
460 // This is permanent and means the configuration or the load monitor
461 // wants us to return false.
462 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
464 return [ false, false ];
467 $serverName = $this->getServerName( $i );
468 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
470 $conn = $this->openConnection( $i, $domain );
472 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
473 unset( $currentLoads[$i] ); // avoid this server next iteration
478 // Decrement reference counter, we are finished with this connection.
479 // It will be incremented for the caller later.
480 if ( $domain !== false ) {
481 $this->reuseConnection( $conn );
484 // Return this server
488 // If all servers were down, quit now
489 if ( !count( $currentLoads ) ) {
490 $this->connLogger
->error( __METHOD__
. ": all servers down" );
493 return [ $i, $laggedReplicaMode ];
496 public function waitFor( $pos ) {
497 $oldPos = $this->waitForPos
;
499 $this->waitForPos
= $pos;
500 // If a generic reader connection was already established, then wait now
501 $i = $this->readIndex
;
503 if ( !$this->doWait( $i ) ) {
504 $this->laggedReplicaMode
= true;
508 // Restore the older position if it was higher since this is used for lag-protection
509 $this->setWaitForPositionIfHigher( $oldPos );
513 public function waitForOne( $pos, $timeout = null ) {
514 $oldPos = $this->waitForPos
;
516 $this->waitForPos
= $pos;
518 $i = $this->readIndex
;
520 // Pick a generic replica DB if there isn't one yet
521 $readLoads = $this->loads
;
522 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
523 $readLoads = array_filter( $readLoads ); // with non-zero load
524 $i = ArrayUtils
::pickRandom( $readLoads );
528 $ok = $this->doWait( $i, true, $timeout );
530 $ok = true; // no applicable loads
533 # Restore the old position, as this is not used for lag-protection but for throttling
534 $this->waitForPos
= $oldPos;
540 public function waitForAll( $pos, $timeout = null ) {
541 $timeout = $timeout ?
: $this->waitTimeout
;
543 $oldPos = $this->waitForPos
;
545 $this->waitForPos
= $pos;
546 $serverCount = count( $this->servers
);
549 for ( $i = 1; $i < $serverCount; $i++
) {
550 if ( $this->loads
[$i] > 0 ) {
551 $start = microtime( true );
552 $ok = $this->doWait( $i, true, $timeout ) && $ok;
553 $timeout -= intval( microtime( true ) - $start );
554 if ( $timeout <= 0 ) {
555 break; // timeout reached
560 # Restore the old position, as this is not used for lag-protection but for throttling
561 $this->waitForPos
= $oldPos;
568 * @param DBMasterPos|bool $pos
570 private function setWaitForPositionIfHigher( $pos ) {
575 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
576 $this->waitForPos
= $pos;
580 public function getAnyOpenConnection( $i, $flags = 0 ) {
581 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
582 foreach ( $this->conns
as $connsByServer ) {
583 if ( !isset( $connsByServer[$i] ) ) {
587 foreach ( $connsByServer[$i] as $conn ) {
588 if ( !$autocommit ||
$conn->getLBInfo( 'autoCommitOnly' ) ) {
598 * Wait for a given replica DB to catch up to the master pos stored in $this
599 * @param int $index Server index
600 * @param bool $open Check the server even if a new connection has to be made
601 * @param int $timeout Max seconds to wait; default is "waitTimeout" given to __construct()
604 protected function doWait( $index, $open = false, $timeout = null ) {
605 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
607 // Check if we already know that the DB has reached this point
608 $server = $this->getServerName( $index );
609 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
610 /** @var DBMasterPos $knownReachedPos */
611 $knownReachedPos = $this->srvCache
->get( $key );
613 $knownReachedPos instanceof DBMasterPos
&&
614 $knownReachedPos->hasReached( $this->waitForPos
)
616 $this->replLogger
->debug(
618 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
619 [ 'dbserver' => $server ]
624 // Find a connection to wait on, creating one if needed and allowed
625 $close = false; // close the connection afterwards
626 $conn = $this->getAnyOpenConnection( $index );
629 $this->replLogger
->debug(
630 __METHOD__
. ': no connection open for {dbserver}',
631 [ 'dbserver' => $server ]
636 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
638 $this->replLogger
->warning(
639 __METHOD__
. ': failed to connect to {dbserver}',
640 [ 'dbserver' => $server ]
645 // Avoid connection spam in waitForAll() when connections
646 // are made just for the sake of doing this lag check.
651 $this->replLogger
->info(
653 ': waiting for replica DB {dbserver} to catch up...',
654 [ 'dbserver' => $server ]
657 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
659 if ( $result === null ) {
660 $this->replLogger
->warning(
661 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
664 'pos' => $this->waitForPos
,
665 'trace' => ( new RuntimeException() )->getTraceAsString()
669 } elseif ( $result == -1 ) {
670 $this->replLogger
->warning(
671 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
674 'pos' => $this->waitForPos
,
675 'trace' => ( new RuntimeException() )->getTraceAsString()
680 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
682 // Remember that the DB reached this point
683 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
687 $this->closeConnection( $conn );
693 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
694 if ( $i === null ||
$i === false ) {
695 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
696 ' with invalid server index' );
699 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
700 $domain = false; // local connection requested
703 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) === self
::CONN_TRX_AUTOCOMMIT
) {
704 // Assuming all servers are of the same type (or similar), which is overwhelmingly
705 // the case, use the master server information to get the attributes. The information
706 // for $i cannot be used since it might be DB_REPLICA, which might require connection
707 // attempts in order to be resolved into a real server index.
708 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
709 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
710 // Callers sometimes want to (a) escape REPEATABLE-READ stateness without locking
711 // rows (e.g. FOR UPDATE) or (b) make small commits during a larger transactions
712 // to reduce lock contention. None of these apply for sqlite and using separate
713 // connections just causes self-deadlocks.
714 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
715 $this->connLogger
->info( __METHOD__
.
716 ': ignoring CONN_TRX_AUTOCOMMIT to avoid deadlocks.' );
720 $groups = ( $groups === false ||
$groups === [] )
721 ?
[ false ] // check one "group": the generic pool
724 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
725 $oldConnsOpened = $this->connsOpened
; // connections open now
727 if ( $i == self
::DB_MASTER
) {
728 $i = $this->getWriterIndex();
729 } elseif ( $i == self
::DB_REPLICA
) {
730 # Try to find an available server in any the query groups (in order)
731 foreach ( $groups as $group ) {
732 $groupIndex = $this->getReaderIndex( $group, $domain );
733 if ( $groupIndex !== false ) {
740 # Operation-based index
741 if ( $i == self
::DB_REPLICA
) {
742 $this->lastError
= 'Unknown error'; // reset error string
743 # Try the general server pool if $groups are unavailable.
744 $i = ( $groups === [ false ] )
745 ?
false // don't bother with this if that is what was tried above
746 : $this->getReaderIndex( false, $domain );
747 # Couldn't find a working server in getReaderIndex()?
748 if ( $i === false ) {
749 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
750 // Throw an exception
751 $this->reportConnectionError();
752 return null; // not reached
756 # Now we have an explicit index into the servers array
757 $conn = $this->openConnection( $i, $domain, $flags );
759 // Throw an exception
760 $this->reportConnectionError();
761 return null; // not reached
764 # Profile any new connections that happen
765 if ( $this->connsOpened
> $oldConnsOpened ) {
766 $host = $conn->getServer();
767 $dbname = $conn->getDBname();
768 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
772 # Make master-requested DB handles inherit any read-only mode setting
773 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
779 public function reuseConnection( IDatabase
$conn ) {
780 $serverIndex = $conn->getLBInfo( 'serverIndex' );
781 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
782 if ( $serverIndex === null ||
$refCount === null ) {
784 * This can happen in code like:
785 * foreach ( $dbs as $db ) {
786 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
788 * $lb->reuseConnection( $conn );
790 * When a connection to the local DB is opened in this way, reuseConnection()
794 } elseif ( $conn instanceof DBConnRef
) {
795 // DBConnRef already handles calling reuseConnection() and only passes the live
796 // Database instance to this method. Any caller passing in a DBConnRef is broken.
797 $this->connLogger
->error(
798 __METHOD__
. ": got DBConnRef instance.\n" .
799 ( new RuntimeException() )->getTraceAsString() );
804 if ( $this->disabled
) {
805 return; // DBConnRef handle probably survived longer than the LoadBalancer
808 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
809 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
810 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
812 $connFreeKey = self
::KEY_FOREIGN_FREE
;
813 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
816 $domain = $conn->getDomainID();
817 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
818 throw new InvalidArgumentException( __METHOD__
.
819 ": connection $serverIndex/$domain not found; it may have already been freed." );
820 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
821 throw new InvalidArgumentException( __METHOD__
.
822 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
825 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
826 if ( $refCount <= 0 ) {
827 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
828 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
829 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
830 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
832 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
834 $this->connLogger
->debug( __METHOD__
.
835 ": reference count for $serverIndex/$domain reduced to $refCount" );
839 public function getConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
840 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
842 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain, $flags ) );
845 public function getLazyConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
846 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
848 return new DBConnRef( $this, [ $db, $groups, $domain, $flags ] );
851 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
852 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
854 return new MaintainableDBConnRef(
855 $this, $this->getConnection( $db, $groups, $domain, $flags ) );
858 public function openConnection( $i, $domain = false, $flags = 0 ) {
859 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
860 $domain = false; // local connection requested
863 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
864 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
865 // Load any "waitFor" positions before connecting so that doWait() is triggered
866 $this->connectionAttempted
= true;
867 call_user_func( $this->chronologyCallback
, $this );
870 // Check if an auto-commit connection is being requested. If so, it will not reuse the
871 // main set of DB connections but rather its own pool since:
872 // a) those are usually set to implicitly use transaction rounds via DBO_TRX
873 // b) those must support the use of explicit transaction rounds via beginMasterChanges()
874 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
876 if ( $domain !== false ) {
877 // Connection is to a foreign domain
878 $conn = $this->openForeignConnection( $i, $domain, $flags );
880 // Connection is to the local domain
881 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
882 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
883 $conn = $this->conns
[$connKey][$i][0];
885 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
886 throw new InvalidArgumentException( "No server with index '$i'." );
888 // Open a new connection
889 $server = $this->servers
[$i];
890 $server['serverIndex'] = $i;
891 $server['autoCommitOnly'] = $autoCommit;
892 if ( $this->localDomain
->getDatabase() !== null ) {
893 // Use the local domain table prefix if the local domain is specified
894 $server['tablePrefix'] = $this->localDomain
->getTablePrefix();
896 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
897 $host = $this->getServerName( $i );
898 if ( $conn->isOpen() ) {
899 $this->connLogger
->debug(
900 __METHOD__
. ": connected to database $i at '$host'." );
901 $this->conns
[$connKey][$i][0] = $conn;
903 $this->connLogger
->warning(
904 __METHOD__
. ": failed to connect to database $i at '$host'." );
905 $this->errorConnection
= $conn;
911 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
912 // Connection was made but later unrecoverably lost for some reason.
913 // Do not return a handle that will just throw exceptions on use,
914 // but let the calling code (e.g. getReaderIndex) try another server.
915 // See DatabaseMyslBase::ping() for how this can happen.
916 $this->errorConnection
= $conn;
920 if ( $autoCommit && $conn instanceof IDatabase
) {
921 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
928 * Open a connection to a foreign DB, or return one if it is already open.
930 * Increments a reference count on the returned connection which locks the
931 * connection to the requested domain. This reference count can be
932 * decremented by calling reuseConnection().
934 * If a connection is open to the appropriate server already, but with the wrong
935 * database, it will be switched to the right database and returned, as long as
936 * it has been freed first with reuseConnection().
938 * On error, returns false, and the connection which caused the
939 * error will be available via $this->errorConnection.
941 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
943 * @param int $i Server index
944 * @param string $domain Domain ID to open
945 * @param int $flags Class CONN_* constant bitfield
948 private function openForeignConnection( $i, $domain, $flags = 0 ) {
949 $domainInstance = DatabaseDomain
::newFromId( $domain );
950 $dbName = $domainInstance->getDatabase();
951 $prefix = $domainInstance->getTablePrefix();
952 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
955 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
956 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
958 $connFreeKey = self
::KEY_FOREIGN_FREE
;
959 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
962 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
963 // Reuse an in-use connection for the same domain
964 $conn = $this->conns
[$connInUseKey][$i][$domain];
965 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
966 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
967 // Reuse a free connection for the same domain
968 $conn = $this->conns
[$connFreeKey][$i][$domain];
969 unset( $this->conns
[$connFreeKey][$i][$domain] );
970 $this->conns
[$connInUseKey][$i][$domain] = $conn;
971 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
972 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
973 // Reuse a free connection from another domain
974 $conn = reset( $this->conns
[$connFreeKey][$i] );
975 $oldDomain = key( $this->conns
[$connFreeKey][$i] );
976 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
977 $this->lastError
= "Error selecting database '$dbName' on server " .
978 $conn->getServer() . " from client host {$this->host}";
979 $this->errorConnection
= $conn;
982 $conn->tablePrefix( $prefix );
983 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
984 // Note that if $domain is an empty string, getDomainID() might not match it
985 $this->conns
[$connInUseKey][$i][$conn->getDomainId()] = $conn;
986 $this->connLogger
->debug( __METHOD__
.
987 ": reusing free connection from $oldDomain for $domain" );
990 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
991 throw new InvalidArgumentException( "No server with index '$i'." );
993 // Open a new connection
994 $server = $this->servers
[$i];
995 $server['serverIndex'] = $i;
996 $server['foreignPoolRefCount'] = 0;
997 $server['foreign'] = true;
998 $server['autoCommitOnly'] = $autoCommit;
999 $conn = $this->reallyOpenConnection( $server, $domainInstance );
1000 if ( !$conn->isOpen() ) {
1001 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
1002 $this->errorConnection
= $conn;
1005 $conn->tablePrefix( $prefix ); // as specified
1006 // Note that if $domain is an empty string, getDomainID() might not match it
1007 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1008 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1012 // Increment reference count
1013 if ( $conn instanceof IDatabase
) {
1014 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1015 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1021 public function getServerAttributes( $i ) {
1022 return Database
::attributesFromType(
1023 $this->getServerType( $i ),
1024 $this->servers
[$i]['driver'] ??
null
1029 * Test if the specified index represents an open connection
1031 * @param int $index Server index
1035 private function isOpen( $index ) {
1036 if ( !is_int( $index ) ) {
1040 return (bool)$this->getAnyOpenConnection( $index );
1044 * Open a new network connection to a server (uncached)
1046 * Returns a Database object whether or not the connection was successful.
1048 * @param array $server
1049 * @param DatabaseDomain $domainOverride Use an unspecified domain to not select any database
1051 * @throws DBAccessError
1052 * @throws InvalidArgumentException
1054 protected function reallyOpenConnection( array $server, DatabaseDomain
$domainOverride ) {
1055 if ( $this->disabled
) {
1056 throw new DBAccessError();
1059 // Handle $domainOverride being a specified or an unspecified domain
1060 if ( $domainOverride->getDatabase() === null ) {
1061 // Normally, an RDBMS requires a DB name specified on connection and the $server
1062 // configuration array is assumed to already specify an appropriate DB name.
1063 if ( $server['type'] === 'mysql' ) {
1064 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1065 // and the DB name in $server might not exist due to legacy reasons (the default
1066 // domain used to ignore the local LB domain, even when mismatched).
1067 $server['dbname'] = null;
1070 $server['dbname'] = $domainOverride->getDatabase();
1071 $server['schema'] = $domainOverride->getSchema();
1074 // Let the handle know what the cluster master is (e.g. "db1052")
1075 $masterName = $this->getServerName( $this->getWriterIndex() );
1076 $server['clusterMasterHost'] = $masterName;
1078 // Log when many connection are made on requests
1079 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
1080 $this->perfLogger
->warning( __METHOD__
. ": " .
1081 "{$this->connsOpened}+ connections made (master=$masterName)" );
1084 $server['srvCache'] = $this->srvCache
;
1085 // Set loggers and profilers
1086 $server['connLogger'] = $this->connLogger
;
1087 $server['queryLogger'] = $this->queryLogger
;
1088 $server['errorLogger'] = $this->errorLogger
;
1089 $server['deprecationLogger'] = $this->deprecationLogger
;
1090 $server['profiler'] = $this->profiler
;
1091 $server['trxProfiler'] = $this->trxProfiler
;
1092 // Use the same agent and PHP mode for all DB handles
1093 $server['cliMode'] = $this->cliMode
;
1094 $server['agent'] = $this->agent
;
1095 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1096 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1097 $server['flags'] = $server['flags'] ?? IDatabase
::DBO_DEFAULT
;
1099 // Create a live connection object
1101 $db = Database
::factory( $server['type'], $server );
1102 } catch ( DBConnectionError
$e ) {
1103 // FIXME: This is probably the ugliest thing I have ever done to
1104 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1108 $db->setLBInfo( $server );
1109 $db->setLazyMasterHandle(
1110 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1112 $db->setTableAliases( $this->tableAliases
);
1113 $db->setIndexAliases( $this->indexAliases
);
1115 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1116 if ( $this->trxRoundId
!== false ) {
1117 $this->applyTransactionRoundFlags( $db );
1119 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1120 $db->setTransactionListener( $name, $callback );
1128 * @throws DBConnectionError
1130 private function reportConnectionError() {
1131 $conn = $this->errorConnection
; // the connection which caused the error
1133 'method' => __METHOD__
,
1134 'last_error' => $this->lastError
,
1137 if ( $conn instanceof IDatabase
) {
1138 $context['db_server'] = $conn->getServer();
1139 $this->connLogger
->warning(
1140 __METHOD__
. ": connection error: {last_error} ({db_server})",
1144 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1146 // No last connection, probably due to all servers being too busy
1147 $this->connLogger
->error(
1149 ": LB failure with no last connection. Connection error: {last_error}",
1153 // If all servers were busy, "lastError" will contain something sensible
1154 throw new DBConnectionError( null, $this->lastError
);
1158 public function getWriterIndex() {
1162 public function haveIndex( $i ) {
1163 return array_key_exists( $i, $this->servers
);
1166 public function isNonZeroLoad( $i ) {
1167 return array_key_exists( $i, $this->servers
) && $this->loads
[$i] != 0;
1170 public function getServerCount() {
1171 return count( $this->servers
);
1174 public function getServerName( $i ) {
1175 if ( isset( $this->servers
[$i]['hostName'] ) ) {
1176 $name = $this->servers
[$i]['hostName'];
1177 } elseif ( isset( $this->servers
[$i]['host'] ) ) {
1178 $name = $this->servers
[$i]['host'];
1183 return ( $name != '' ) ?
$name : 'localhost';
1186 public function getServerInfo( $i ) {
1187 if ( isset( $this->servers
[$i] ) ) {
1188 return $this->servers
[$i];
1194 public function getServerType( $i ) {
1195 return $this->servers
[$i]['type'] ??
'unknown';
1198 public function getMasterPos() {
1199 # If this entire request was served from a replica DB without opening a connection to the
1200 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1201 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1202 if ( !$masterConn ) {
1203 $serverCount = count( $this->servers
);
1204 for ( $i = 1; $i < $serverCount; $i++
) {
1205 $conn = $this->getAnyOpenConnection( $i );
1207 return $conn->getReplicaPos();
1211 return $masterConn->getMasterPos();
1217 public function disable() {
1219 $this->disabled
= true;
1222 public function closeAll() {
1223 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1224 $host = $conn->getServer();
1225 $this->connLogger
->debug(
1226 __METHOD__
. ": closing connection to database '$host'." );
1231 self
::KEY_LOCAL
=> [],
1232 self
::KEY_FOREIGN_INUSE
=> [],
1233 self
::KEY_FOREIGN_FREE
=> [],
1234 self
::KEY_LOCAL_NOROUND
=> [],
1235 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1236 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1238 $this->connsOpened
= 0;
1241 public function closeConnection( IDatabase
$conn ) {
1242 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1243 foreach ( $this->conns
as $type => $connsByServer ) {
1244 if ( !isset( $connsByServer[$serverIndex] ) ) {
1248 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1249 if ( $conn === $trackedConn ) {
1250 $host = $this->getServerName( $i );
1251 $this->connLogger
->debug(
1252 __METHOD__
. ": closing connection to database $i at '$host'." );
1253 unset( $this->conns
[$type][$serverIndex][$i] );
1254 --$this->connsOpened
;
1263 public function commitAll( $fname = __METHOD__
) {
1264 $this->commitMasterChanges( $fname );
1265 $this->flushMasterSnapshots( $fname );
1266 $this->flushReplicaSnapshots( $fname );
1269 public function finalizeMasterChanges() {
1270 $this->assertTransactionRoundStage( [ self
::ROUND_CURSORY
, self
::ROUND_FINALIZED
] );
1272 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1273 // Loop until callbacks stop adding callbacks on other connections
1276 $count = 0; // callbacks execution attempts
1277 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$count ) {
1278 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1279 // Any error should cause all (peer) transactions to be rolled back together.
1280 $count +
= $conn->runOnTransactionPreCommitCallbacks();
1283 } while ( $count > 0 );
1284 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1285 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1286 $conn->setTrxEndCallbackSuppression( true );
1288 $this->trxRoundStage
= self
::ROUND_FINALIZED
;
1293 public function approveMasterChanges( array $options ) {
1294 $this->assertTransactionRoundStage( self
::ROUND_FINALIZED
);
1296 $limit = $options['maxWriteDuration'] ??
0;
1298 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1299 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1300 // If atomic sections or explicit transactions are still open, some caller must have
1301 // caught an exception but failed to properly rollback any changes. Detect that and
1302 // throw and error (causing rollback).
1303 if ( $conn->explicitTrxActive() ) {
1304 throw new DBTransactionError(
1306 "Explicit transaction still active. A caller may have caught an error."
1309 // Assert that the time to replicate the transaction will be sane.
1310 // If this fails, then all DB transactions will be rollback back together.
1311 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1312 if ( $limit > 0 && $time > $limit ) {
1313 throw new DBTransactionSizeError(
1315 "Transaction spent $time second(s) in writes, exceeding the limit of $limit.",
1319 // If a connection sits idle while slow queries execute on another, that connection
1320 // may end up dropped before the commit round is reached. Ping servers to detect this.
1321 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1322 throw new DBTransactionError(
1324 "A connection to the {$conn->getDBname()} database was lost before commit."
1328 $this->trxRoundStage
= self
::ROUND_APPROVED
;
1331 public function beginMasterChanges( $fname = __METHOD__
) {
1332 if ( $this->trxRoundId
!== false ) {
1333 throw new DBTransactionError(
1335 "$fname: Transaction round '{$this->trxRoundId}' already started."
1338 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
1340 // Clear any empty transactions (no writes/callbacks) from the implicit round
1341 $this->flushMasterSnapshots( $fname );
1343 $this->trxRoundId
= $fname;
1344 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1345 // Mark applicable handles as participating in this explicit transaction round.
1346 // For each of these handles, any writes and callbacks will be tied to a single
1347 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1348 // are part of an en masse commit or an en masse rollback.
1349 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1350 $this->applyTransactionRoundFlags( $conn );
1352 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1355 public function commitMasterChanges( $fname = __METHOD__
) {
1356 $this->assertTransactionRoundStage( self
::ROUND_APPROVED
);
1360 /** @noinspection PhpUnusedLocalVariableInspection */
1361 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1363 $restore = ( $this->trxRoundId
!== false );
1364 $this->trxRoundId
= false;
1365 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1366 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1367 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1368 $this->forEachOpenMasterConnection(
1369 function ( IDatabase
$conn ) use ( $fname, &$failures ) {
1371 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1372 } catch ( DBError
$e ) {
1373 call_user_func( $this->errorLogger
, $e );
1374 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1379 throw new DBTransactionError(
1381 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1385 // Unmark handles as participating in this explicit transaction round
1386 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1387 $this->undoTransactionRoundFlags( $conn );
1390 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
1393 public function runMasterTransactionIdleCallbacks() {
1394 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1395 $type = IDatabase
::TRIGGER_COMMIT
;
1396 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1397 $type = IDatabase
::TRIGGER_ROLLBACK
;
1399 throw new DBTransactionError(
1401 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1405 $oldStage = $this->trxRoundStage
;
1406 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1408 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1409 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1410 $conn->setTrxEndCallbackSuppression( false );
1413 $e = null; // first exception
1414 // Loop until callbacks stop adding callbacks on other connections
1416 // Run any pending callbacks for each connection...
1417 $count = 0; // callback execution attempts
1418 $this->forEachOpenMasterConnection(
1419 function ( Database
$conn ) use ( $type, &$e, &$count ) {
1420 if ( $conn->trxLevel() ) {
1421 return; // retry in the next iteration, after commit() is called
1424 $count +
= $conn->runOnTransactionIdleCallbacks( $type );
1425 } catch ( Exception
$ex ) {
1430 // Clear out any active transactions left over from callbacks...
1431 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$e ) {
1432 if ( $conn->writesPending() ) {
1433 // A callback from another handle wrote to this one and DBO_TRX is set
1434 $this->queryLogger
->warning( __METHOD__
. ": found writes pending." );
1435 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1436 $this->queryLogger
->warning(
1437 __METHOD__
. ": found writes pending ($fnames).",
1439 'db_server' => $conn->getServer(),
1440 'db_name' => $conn->getDBname()
1443 } elseif ( $conn->trxLevel() ) {
1444 // A callback from another handle read from this one and DBO_TRX is set,
1445 // which can easily happen if there is only one DB (no replicas)
1446 $this->queryLogger
->debug( __METHOD__
. ": found empty transaction." );
1449 $conn->commit( __METHOD__
, $conn::FLUSHING_ALL_PEERS
);
1450 } catch ( Exception
$ex ) {
1454 } while ( $count > 0 );
1456 $this->trxRoundStage
= $oldStage;
1461 public function runMasterTransactionListenerCallbacks() {
1462 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1463 $type = IDatabase
::TRIGGER_COMMIT
;
1464 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1465 $type = IDatabase
::TRIGGER_ROLLBACK
;
1467 throw new DBTransactionError(
1469 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1475 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1476 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1478 $conn->runTransactionListenerCallbacks( $type );
1479 } catch ( Exception
$ex ) {
1483 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1488 public function rollbackMasterChanges( $fname = __METHOD__
) {
1489 $restore = ( $this->trxRoundId
!== false );
1490 $this->trxRoundId
= false;
1491 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1492 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1493 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1496 // Unmark handles as participating in this explicit transaction round
1497 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1498 $this->undoTransactionRoundFlags( $conn );
1501 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
1505 * @param string|string[] $stage
1507 private function assertTransactionRoundStage( $stage ) {
1508 $stages = (array)$stage;
1510 if ( !in_array( $this->trxRoundStage
, $stages, true ) ) {
1511 $stageList = implode(
1513 array_map( function ( $v ) {
1517 throw new DBTransactionError(
1519 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1525 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1527 * Some servers may have neither flag enabled, meaning that they opt out of such
1528 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1529 * when a DB server is used for something like simple key/value storage.
1531 * @param Database $conn
1533 private function applyTransactionRoundFlags( Database
$conn ) {
1534 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1535 return; // transaction rounds do not apply to these connections
1538 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1539 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1540 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1541 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1544 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1545 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1550 * @param Database $conn
1552 private function undoTransactionRoundFlags( Database
$conn ) {
1553 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1554 return; // transaction rounds do not apply to these connections
1557 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1558 $conn->setLBInfo( 'trxRoundId', false );
1561 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1562 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1566 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1567 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) use ( $fname ) {
1568 $conn->flushSnapshot( $fname );
1572 public function flushMasterSnapshots( $fname = __METHOD__
) {
1573 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1574 $conn->flushSnapshot( $fname );
1582 public function getTransactionRoundStage() {
1583 return $this->trxRoundStage
;
1586 public function hasMasterConnection() {
1587 return $this->isOpen( $this->getWriterIndex() );
1590 public function hasMasterChanges() {
1592 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1593 $pending |
= $conn->writesOrCallbacksPending();
1596 return (bool)$pending;
1599 public function lastMasterChangeTimestamp() {
1601 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1602 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1608 public function hasOrMadeRecentMasterChanges( $age = null ) {
1609 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1611 return ( $this->hasMasterChanges()
1612 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1615 public function pendingMasterChangeCallers() {
1617 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1618 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1624 public function getLaggedReplicaMode( $domain = false ) {
1625 // No-op if there is only one DB (also avoids recursion)
1626 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1628 // See if laggedReplicaMode gets set
1629 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1630 $this->reuseConnection( $conn );
1631 } catch ( DBConnectionError
$e ) {
1632 // Avoid expensive re-connect attempts and failures
1633 $this->allReplicasDownMode
= true;
1634 $this->laggedReplicaMode
= true;
1638 return $this->laggedReplicaMode
;
1641 public function laggedReplicaUsed() {
1642 return $this->laggedReplicaMode
;
1648 * @deprecated Since 1.28; use laggedReplicaUsed()
1650 public function laggedSlaveUsed() {
1651 return $this->laggedReplicaUsed();
1654 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1655 if ( $this->readOnlyReason
!== false ) {
1656 return $this->readOnlyReason
;
1657 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1658 if ( $this->allReplicasDownMode
) {
1659 return 'The database has been automatically locked ' .
1660 'until the replica database servers become available';
1662 return 'The database has been automatically locked ' .
1663 'while the replica database servers catch up to the master.';
1665 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1666 return 'The database master is running in read-only mode.';
1673 * @param string $domain Domain ID, or false for the current domain
1674 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1677 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1678 $cache = $this->wanCache
;
1679 $masterServer = $this->getServerName( $this->getWriterIndex() );
1681 return (bool)$cache->getWithSetCallback(
1682 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1683 self
::TTL_CACHE_READONLY
,
1684 function () use ( $domain, $conn ) {
1685 $old = $this->trxProfiler
->setSilenced( true );
1687 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1688 $readOnly = (int)$dbw->serverIsReadOnly();
1690 $this->reuseConnection( $dbw );
1692 } catch ( DBError
$e ) {
1695 $this->trxProfiler
->setSilenced( $old );
1698 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1702 public function allowLagged( $mode = null ) {
1703 if ( $mode === null ) {
1704 return $this->allowLagged
;
1706 $this->allowLagged
= $mode;
1708 return $this->allowLagged
;
1711 public function pingAll() {
1713 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1714 if ( !$conn->ping() ) {
1722 public function forEachOpenConnection( $callback, array $params = [] ) {
1723 foreach ( $this->conns
as $connsByServer ) {
1724 foreach ( $connsByServer as $serverConns ) {
1725 foreach ( $serverConns as $conn ) {
1726 $mergedParams = array_merge( [ $conn ], $params );
1727 call_user_func_array( $callback, $mergedParams );
1733 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1734 $masterIndex = $this->getWriterIndex();
1735 foreach ( $this->conns
as $connsByServer ) {
1736 if ( isset( $connsByServer[$masterIndex] ) ) {
1737 /** @var IDatabase $conn */
1738 foreach ( $connsByServer[$masterIndex] as $conn ) {
1739 $mergedParams = array_merge( [ $conn ], $params );
1740 call_user_func_array( $callback, $mergedParams );
1746 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1747 foreach ( $this->conns
as $connsByServer ) {
1748 foreach ( $connsByServer as $i => $serverConns ) {
1749 if ( $i === $this->getWriterIndex() ) {
1750 continue; // skip master
1752 foreach ( $serverConns as $conn ) {
1753 $mergedParams = array_merge( [ $conn ], $params );
1754 call_user_func_array( $callback, $mergedParams );
1760 public function getMaxLag( $domain = false ) {
1765 if ( $this->getServerCount() <= 1 ) {
1766 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1769 $lagTimes = $this->getLagTimes( $domain );
1770 foreach ( $lagTimes as $i => $lag ) {
1771 if ( $this->loads
[$i] > 0 && $lag > $maxLag ) {
1773 $host = $this->servers
[$i]['host'];
1778 return [ $host, $maxLag, $maxIndex ];
1781 public function getLagTimes( $domain = false ) {
1782 if ( $this->getServerCount() <= 1 ) {
1783 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1786 $knownLagTimes = []; // map of (server index => 0 seconds)
1787 $indexesWithLag = [];
1788 foreach ( $this->servers
as $i => $server ) {
1789 if ( empty( $server['is static'] ) ) {
1790 $indexesWithLag[] = $i; // DB server might have replication lag
1792 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1796 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1799 public function safeGetLag( IDatabase
$conn ) {
1800 if ( $this->getServerCount() <= 1 ) {
1803 return $conn->getLag();
1808 * @param IDatabase $conn
1809 * @param DBMasterPos|bool $pos
1810 * @param int|null $timeout
1813 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
1814 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
1816 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1817 return true; // server is not a replica DB
1821 // Get the current master position, opening a connection if needed
1822 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1823 if ( $masterConn ) {
1824 $pos = $masterConn->getMasterPos();
1826 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1827 $pos = $masterConn->getMasterPos();
1828 $this->closeConnection( $masterConn );
1832 if ( $pos instanceof DBMasterPos
) {
1833 $result = $conn->masterPosWait( $pos, $timeout );
1834 if ( $result == -1 ||
is_null( $result ) ) {
1835 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos}';
1836 $this->replLogger
->warning( $msg, [
1837 'host' => $conn->getServer(),
1839 'trace' => ( new RuntimeException() )->getTraceAsString()
1843 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
1847 $ok = false; // something is misconfigured
1848 $this->replLogger
->error(
1849 __METHOD__
. ': could not get master pos for {host}',
1851 'host' => $conn->getServer(),
1852 'trace' => ( new RuntimeException() )->getTraceAsString()
1860 public function setTransactionListener( $name, callable
$callback = null ) {
1862 $this->trxRecurringCallbacks
[$name] = $callback;
1864 unset( $this->trxRecurringCallbacks
[$name] );
1866 $this->forEachOpenMasterConnection(
1867 function ( IDatabase
$conn ) use ( $name, $callback ) {
1868 $conn->setTransactionListener( $name, $callback );
1873 public function setTableAliases( array $aliases ) {
1874 $this->tableAliases
= $aliases;
1877 public function setIndexAliases( array $aliases ) {
1878 $this->indexAliases
= $aliases;
1881 public function setDomainPrefix( $prefix ) {
1882 // Find connections to explicit foreign domains still marked as in-use...
1884 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
1885 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1886 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1887 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1888 $domainsInUse[] = $conn->getDomainID();
1892 // Do not switch connections to explicit foreign domains unless marked as safe
1893 if ( $domainsInUse ) {
1894 $domains = implode( ', ', $domainsInUse );
1895 throw new DBUnexpectedError( null,
1896 "Foreign domain connections are still in use ($domains)." );
1899 $oldDomain = $this->localDomain
->getId();
1900 $this->setLocalDomain( new DatabaseDomain(
1901 $this->localDomain
->getDatabase(),
1902 $this->localDomain
->getSchema(),
1906 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix, $oldDomain ) {
1907 if ( !$db->getLBInfo( 'foreign' ) ) {
1908 $db->tablePrefix( $prefix );
1914 * @param DatabaseDomain $domain
1916 private function setLocalDomain( DatabaseDomain
$domain ) {
1917 $this->localDomain
= $domain;
1918 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
1919 // always true, gracefully handle the case when they fail to account for escaping.
1920 if ( $this->localDomain
->getTablePrefix() != '' ) {
1921 $this->localDomainIdAlias
=
1922 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
1924 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
1929 * Make PHP ignore user aborts/disconnects until the returned
1930 * value leaves scope. This returns null and does nothing in CLI mode.
1932 * @return ScopedCallback|null
1934 final protected function getScopedPHPBehaviorForCommit() {
1935 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1936 $old = ignore_user_abort( true ); // avoid half-finished operations
1937 return new ScopedCallback( function () use ( $old ) {
1938 ignore_user_abort( $old );
1945 function __destruct() {
1946 // Avoid connection leaks for sanity
1952 * @deprecated since 1.29
1954 class_alias( LoadBalancer
::class, 'LoadBalancer' );