3 * Generator and manager of database load balancing objects
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
24 namespace Wikimedia\Rdbms
;
26 use Psr\Log\LoggerInterface
;
27 use Wikimedia\ScopedCallback
;
36 * An interface for generating database load balancers
39 abstract class LBFactory
implements ILBFactory
{
40 /** @var ChronologyProtector */
42 /** @var object|string Class name or object With profileIn/profileOut methods */
44 /** @var TransactionProfiler */
45 protected $trxProfiler;
46 /** @var LoggerInterface */
47 protected $replLogger;
48 /** @var LoggerInterface */
49 protected $connLogger;
50 /** @var LoggerInterface */
51 protected $queryLogger;
52 /** @var LoggerInterface */
53 protected $perfLogger;
54 /** @var callable Error logger */
55 protected $errorLogger;
56 /** @var callable Deprecation logger */
57 protected $deprecationLogger;
62 /** @var WANObjectCache */
65 /** @var DatabaseDomain Local domain */
66 protected $localDomain;
67 /** @var string Local hostname of the app server */
69 /** @var array Web request information about the client */
70 protected $requestInfo;
74 /** @var string|bool String if a requested DBO_TRX transaction round is active */
75 protected $trxRoundId = false;
76 /** @var string|bool Reason all LBs are read-only or false if not */
77 protected $readOnlyReason = false;
78 /** @var callable[] */
79 protected $replicationWaitCallbacks = [];
81 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
82 protected $tableAliases = [];
83 /** @var string[] Map of (index alias => index) */
84 protected $indexAliases = [];
86 /** @var bool Whether this PHP instance is for a CLI script */
88 /** @var string Agent name for query profiling */
91 /** @var string One of the ROUND_* class constants */
92 private $trxRoundStage = self
::ROUND_CURSORY
;
94 const ROUND_CURSORY
= 'cursory';
95 const ROUND_BEGINNING
= 'within-begin';
96 const ROUND_COMMITTING
= 'within-commit';
97 const ROUND_ROLLING_BACK
= 'within-rollback';
98 const ROUND_COMMIT_CALLBACKS
= 'within-commit-callbacks';
99 const ROUND_ROLLBACK_CALLBACKS
= 'within-rollback-callbacks';
101 private static $loggerFields =
102 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
104 public function __construct( array $conf ) {
105 $this->localDomain
= isset( $conf['localDomain'] )
106 ? DatabaseDomain
::newFromId( $conf['localDomain'] )
107 : DatabaseDomain
::newUnspecified();
109 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
110 $this->readOnlyReason
= $conf['readOnlyReason'];
113 $this->srvCache
= $conf['srvCache'] ??
new EmptyBagOStuff();
114 $this->memStash
= $conf['memStash'] ??
new EmptyBagOStuff();
115 $this->wanCache
= $conf['wanCache'] ?? WANObjectCache
::newEmpty();
117 foreach ( self
::$loggerFields as $key ) {
118 $this->$key = $conf[$key] ??
new \Psr\Log\
NullLogger();
120 $this->errorLogger
= $conf['errorLogger'] ??
function ( Exception
$e ) {
121 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
123 $this->deprecationLogger
= $conf['deprecationLogger'] ??
function ( $msg ) {
124 trigger_error( $msg, E_USER_DEPRECATED
);
127 $this->profiler
= $conf['profiler'] ??
null;
128 $this->trxProfiler
= $conf['trxProfiler'] ??
new TransactionProfiler();
130 $this->requestInfo
= [
131 'IPAddress' => $_SERVER[ 'REMOTE_ADDR' ] ??
'',
132 'UserAgent' => $_SERVER['HTTP_USER_AGENT'] ??
'',
133 'ChronologyProtection' => 'true',
134 // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals -- library can't use $wgRequest
135 'ChronologyPositionIndex' => $_GET['cpPosIndex'] ??
null
138 $this->cliMode
= $conf['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
139 $this->hostname
= $conf['hostname'] ??
gethostname();
140 $this->agent
= $conf['agent'] ??
'';
142 $this->ticket
= mt_rand();
145 public function destroy() {
146 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
147 $this->forEachLBCallMethod( 'disable' );
150 public function shutdown(
151 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null, &$cpIndex = null
153 $chronProt = $this->getChronologyProtector();
154 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
155 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync', $cpIndex );
156 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
157 $this->shutdownChronologyProtector( $chronProt, null, 'async', $cpIndex );
160 $this->commitMasterChanges( __METHOD__
); // sanity
164 * @see ILBFactory::newMainLB()
165 * @param bool $domain
166 * @return ILoadBalancer
168 abstract public function newMainLB( $domain = false );
171 * @see ILBFactory::getMainLB()
172 * @param bool $domain
173 * @return ILoadBalancer
175 abstract public function getMainLB( $domain = false );
178 * @see ILBFactory::newExternalLB()
179 * @param string $cluster
180 * @return ILoadBalancer
182 abstract public function newExternalLB( $cluster );
185 * @see ILBFactory::getExternalLB()
186 * @param string $cluster
187 * @return ILoadBalancer
189 abstract public function getExternalLB( $cluster );
192 * Call a method of each tracked load balancer
194 * @param string $methodName
197 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
199 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
200 call_user_func_array( [ $loadBalancer, $methodName ], $args );
202 [ $methodName, $args ]
206 public function flushReplicaSnapshots( $fname = __METHOD__
) {
207 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
210 final public function commitAll( $fname = __METHOD__
, array $options = [] ) {
211 $this->commitMasterChanges( $fname, $options );
212 $this->forEachLBCallMethod( 'flushMasterSnapshots', [ $fname ] );
213 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
216 final public function beginMasterChanges( $fname = __METHOD__
) {
217 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
218 $this->trxRoundStage
= self
::ROUND_BEGINNING
;
219 if ( $this->trxRoundId
!== false ) {
220 throw new DBTransactionError(
222 "$fname: transaction round '{$this->trxRoundId}' already started."
225 $this->trxRoundId
= $fname;
226 // Set DBO_TRX flags on all appropriate DBs
227 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
228 $this->trxRoundStage
= self
::ROUND_CURSORY
;
231 final public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
232 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
233 $this->trxRoundStage
= self
::ROUND_COMMITTING
;
234 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
235 throw new DBTransactionError(
237 "$fname: transaction round '{$this->trxRoundId}' still running."
240 /** @noinspection PhpUnusedLocalVariableInspection */
241 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
242 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
244 $count = 0; // number of callbacks executed this iteration
245 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$count ) {
246 $count +
= $lb->finalizeMasterChanges();
248 } while ( $count > 0 );
249 $this->trxRoundId
= false;
250 // Perform pre-commit checks, aborting on failure
251 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
252 // Log the DBs and methods involved in multi-DB transactions
253 $this->logIfMultiDbTransaction();
254 // Actually perform the commit on all master DB connections and revert DBO_TRX
255 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
256 // Run all post-commit callbacks in a separate step
257 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
258 $e = $this->executePostTransactionCallbacks();
259 $this->trxRoundStage
= self
::ROUND_CURSORY
;
260 // Throw any last post-commit callback error
261 if ( $e instanceof Exception
) {
266 final public function rollbackMasterChanges( $fname = __METHOD__
) {
267 $this->trxRoundStage
= self
::ROUND_ROLLING_BACK
;
268 $this->trxRoundId
= false;
269 // Actually perform the rollback on all master DB connections and revert DBO_TRX
270 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
271 // Run all post-commit callbacks in a separate step
272 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
273 $this->executePostTransactionCallbacks();
274 $this->trxRoundStage
= self
::ROUND_CURSORY
;
278 * @return Exception|null
280 private function executePostTransactionCallbacks() {
281 // Run all post-commit callbacks until new ones stop getting added
282 $e = null; // first callback exception
284 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
285 $ex = $lb->runMasterTransactionIdleCallbacks();
288 } while ( $this->hasMasterChanges() );
289 // Run all listener callbacks once
290 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
291 $ex = $lb->runMasterTransactionListenerCallbacks();
298 public function hasTransactionRound() {
299 return ( $this->trxRoundId
!== false );
302 public function isReadyForRoundOperations() {
303 return ( $this->trxRoundStage
=== self
::ROUND_CURSORY
);
307 * Log query info if multi DB transactions are going to be committed now
309 private function logIfMultiDbTransaction() {
311 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
312 $masterName = $lb->getServerName( $lb->getWriterIndex() );
313 $callers = $lb->pendingMasterChangeCallers();
315 $callersByDB[$masterName] = $callers;
319 if ( count( $callersByDB ) >= 2 ) {
320 $dbs = implode( ', ', array_keys( $callersByDB ) );
321 $msg = "Multi-DB transaction [{$dbs}]:\n";
322 foreach ( $callersByDB as $db => $callers ) {
323 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
325 $this->queryLogger
->info( $msg );
329 public function hasMasterChanges() {
331 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
332 $ret = $ret ||
$lb->hasMasterChanges();
338 public function laggedReplicaUsed() {
340 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
341 $ret = $ret ||
$lb->laggedReplicaUsed();
347 public function hasOrMadeRecentMasterChanges( $age = null ) {
349 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
350 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
355 public function waitForReplication( array $opts = [] ) {
359 'timeout' => $this->cliMode ?
60 : 10,
360 'ifWritesSince' => null
363 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
364 $opts['domain'] = $opts['wiki']; // b/c
367 // Figure out which clusters need to be checked
368 /** @var ILoadBalancer[] $lbs */
370 if ( $opts['cluster'] !== false ) {
371 $lbs[] = $this->getExternalLB( $opts['cluster'] );
372 } elseif ( $opts['domain'] !== false ) {
373 $lbs[] = $this->getMainLB( $opts['domain'] );
375 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
379 return; // nothing actually used
383 // Get all the master positions of applicable DBs right now.
384 // This can be faster since waiting on one cluster reduces the
385 // time needed to wait on the next clusters.
386 $masterPositions = array_fill( 0, count( $lbs ), false );
387 foreach ( $lbs as $i => $lb ) {
388 if ( $lb->getServerCount() <= 1 ) {
389 // T29975 - Don't try to wait for replica DBs if there are none
390 // Prevents permission error when getting master position
392 } elseif ( $opts['ifWritesSince']
393 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
395 continue; // no writes since the last wait
397 $masterPositions[$i] = $lb->getMasterPos();
400 // Run any listener callbacks *after* getting the DB positions. The more
401 // time spent in the callbacks, the less time is spent in waitForAll().
402 foreach ( $this->replicationWaitCallbacks
as $callback ) {
407 foreach ( $lbs as $i => $lb ) {
408 if ( $masterPositions[$i] ) {
409 // The RDBMS may not support getMasterPos()
410 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
411 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
417 throw new DBReplicationWaitError(
419 "Could not wait for replica DBs to catch up to " .
420 implode( ', ', $failed )
425 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
427 $this->replicationWaitCallbacks
[$name] = $callback;
429 unset( $this->replicationWaitCallbacks
[$name] );
433 public function getEmptyTransactionTicket( $fname ) {
434 if ( $this->hasMasterChanges() ) {
435 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
436 ( new RuntimeException() )->getTraceAsString() );
441 return $this->ticket
;
444 final public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
445 if ( $ticket !== $this->ticket
) {
446 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
447 ( new RuntimeException() )->getTraceAsString() );
452 // The transaction owner and any caller with the empty transaction ticket can commit
453 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
454 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
455 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
456 $fnameEffective = $this->trxRoundId
;
458 $fnameEffective = $fname;
461 $this->commitMasterChanges( $fnameEffective );
462 $this->waitForReplication( $opts );
463 // If a nested caller committed on behalf of $fname, start another empty $fname
464 // transaction, leaving the caller with the same empty transaction state as before.
465 if ( $fnameEffective !== $fname ) {
466 $this->beginMasterChanges( $fnameEffective );
470 public function getChronologyProtectorTouched( $dbName ) {
471 return $this->getChronologyProtector()->getTouched( $dbName );
474 public function disableChronologyProtection() {
475 $this->getChronologyProtector()->setEnabled( false );
479 * @return ChronologyProtector
481 protected function getChronologyProtector() {
482 if ( $this->chronProt
) {
483 return $this->chronProt
;
486 $this->chronProt
= new ChronologyProtector(
489 'ip' => $this->requestInfo
['IPAddress'],
490 'agent' => $this->requestInfo
['UserAgent'],
492 $this->requestInfo
['ChronologyPositionIndex']
494 $this->chronProt
->setLogger( $this->replLogger
);
496 if ( $this->cliMode
) {
497 $this->chronProt
->setEnabled( false );
498 } elseif ( $this->requestInfo
['ChronologyProtection'] === 'false' ) {
499 // Request opted out of using position wait logic. This is useful for requests
500 // done by the job queue or background ETL that do not have a meaningful session.
501 $this->chronProt
->setWaitEnabled( false );
504 $this->replLogger
->debug( __METHOD__
. ': using request info ' .
505 json_encode( $this->requestInfo
, JSON_PRETTY_PRINT
) );
507 return $this->chronProt
;
511 * Get and record all of the staged DB positions into persistent memory storage
513 * @param ChronologyProtector $cp
514 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
515 * @param string $mode One of (sync, async); whether to wait on remote datacenters
516 * @param int|null &$cpIndex DB position key write counter; incremented on update
518 protected function shutdownChronologyProtector(
519 ChronologyProtector
$cp, $workCallback, $mode, &$cpIndex = null
521 // Record all the master positions needed
522 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
523 $cp->shutdownLB( $lb );
525 // Write them to the persistent stash. Try to do something useful by running $work
526 // while ChronologyProtector waits for the stash write to replicate to all DCs.
527 $unsavedPositions = $cp->shutdown( $workCallback, $mode, $cpIndex );
528 if ( $unsavedPositions && $workCallback ) {
529 // Invoke callback in case it did not cache the result yet
530 $workCallback(); // work now to block for less time in waitForAll()
532 // If the positions failed to write to the stash, at least wait on local datacenter
533 // replica DBs to catch up before responding. Even if there are several DCs, this increases
534 // the chance that the user will see their own changes immediately afterwards. As long
535 // as the sticky DC cookie applies (same domain), this is not even an issue.
536 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
537 $masterName = $lb->getServerName( $lb->getWriterIndex() );
538 if ( isset( $unsavedPositions[$masterName] ) ) {
539 $lb->waitForAll( $unsavedPositions[$masterName] );
545 * Base parameters to ILoadBalancer::__construct()
548 final protected function baseLoadBalancerParams() {
549 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
550 $initStage = ILoadBalancer
::STAGE_POSTCOMMIT_CALLBACKS
;
551 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
552 $initStage = ILoadBalancer
::STAGE_POSTROLLBACK_CALLBACKS
;
558 'localDomain' => $this->localDomain
,
559 'readOnlyReason' => $this->readOnlyReason
,
560 'srvCache' => $this->srvCache
,
561 'wanCache' => $this->wanCache
,
562 'profiler' => $this->profiler
,
563 'trxProfiler' => $this->trxProfiler
,
564 'queryLogger' => $this->queryLogger
,
565 'connLogger' => $this->connLogger
,
566 'replLogger' => $this->replLogger
,
567 'errorLogger' => $this->errorLogger
,
568 'deprecationLogger' => $this->deprecationLogger
,
569 'hostname' => $this->hostname
,
570 'cliMode' => $this->cliMode
,
571 'agent' => $this->agent
,
572 'chronologyCallback' => function ( ILoadBalancer
$lb ) {
573 // Defer ChronologyProtector construction in case setRequestInfo() ends up
574 // being called later (but before the first connection attempt) (T192611)
575 $this->getChronologyProtector()->initLB( $lb );
577 'roundStage' => $initStage
582 * @param ILoadBalancer $lb
584 protected function initLoadBalancer( ILoadBalancer
$lb ) {
585 if ( $this->trxRoundId
!== false ) {
586 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
589 $lb->setTableAliases( $this->tableAliases
);
590 $lb->setIndexAliases( $this->indexAliases
);
593 public function setTableAliases( array $aliases ) {
594 $this->tableAliases
= $aliases;
597 public function setIndexAliases( array $aliases ) {
598 $this->indexAliases
= $aliases;
601 public function setDomainPrefix( $prefix ) {
602 $this->localDomain
= new DatabaseDomain(
603 $this->localDomain
->getDatabase(),
608 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $prefix ) {
609 $lb->setDomainPrefix( $prefix );
613 public function closeAll() {
614 $this->forEachLBCallMethod( 'closeAll', [] );
617 public function setAgentName( $agent ) {
618 $this->agent
= $agent;
621 public function appendShutdownCPIndexAsQuery( $url, $index ) {
623 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$usedCluster ) {
624 $usedCluster |
= ( $lb->getServerCount() > 1 );
627 if ( !$usedCluster ) {
628 return $url; // no master/replica clusters touched
631 return strpos( $url, '?' ) === false ?
"$url?cpPosIndex=$index" : "$url&cpPosIndex=$index";
635 * @param int $index Write index
636 * @param int $time UNIX timestamp
637 * @return string Timestamp-qualified write index of the form "<index>.<timestamp>"
640 public static function makeCookieValueFromCPIndex( $index, $time ) {
641 return $index . '@' . $time;
645 * @param string $value String possibly of the form "<index>" or "<index>@<timestamp>"
646 * @param int $minTimestamp Lowest UNIX timestamp of non-expired values (if present)
647 * @return int|null Write index or null if $value is empty or expired
650 public static function getCPIndexFromCookieValue( $value, $minTimestamp ) {
651 if ( !preg_match( '/^(\d+)(?:@(\d+))?$/', $value, $m ) ) {
657 if ( isset( $m[2] ) && $m[2] !== '' && (int)$m[2] < $minTimestamp ) {
658 return null; // expired
661 return ( $index > 0 ) ?
$index : null;
664 public function setRequestInfo( array $info ) {
665 if ( $this->chronProt
) {
666 throw new LogicException( 'ChronologyProtector already initialized.' );
669 $this->requestInfo
= $info +
$this->requestInfo
;
673 * @param string $stage
675 private function assertTransactionRoundStage( $stage ) {
676 if ( $this->trxRoundStage
!== $stage ) {
677 throw new DBTransactionError(
679 "Transaction round stage must be '$stage' (not '{$this->trxRoundStage}')"
685 * Make PHP ignore user aborts/disconnects until the returned
686 * value leaves scope. This returns null and does nothing in CLI mode.
688 * @return ScopedCallback|null
690 final protected function getScopedPHPBehaviorForCommit() {
691 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
692 $old = ignore_user_abort( true ); // avoid half-finished operations
693 return new ScopedCallback( function () use ( $old ) {
694 ignore_user_abort( $old );
701 function __destruct() {
707 * @deprecated since 1.29
709 class_alias( LBFactory
::class, 'LBFactory' );