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
= isset( $conf['srvCache'] ) ?
$conf['srvCache'] : new EmptyBagOStuff();
114 $this->memStash
= isset( $conf['memStash'] ) ?
$conf['memStash'] : new EmptyBagOStuff();
115 $this->wanCache
= isset( $conf['wanCache'] )
117 : WANObjectCache
::newEmpty();
119 foreach ( self
::$loggerFields as $key ) {
120 $this->$key = isset( $conf[$key] ) ?
$conf[$key] : new \Psr\Log\
NullLogger();
122 $this->errorLogger
= isset( $conf['errorLogger'] )
123 ?
$conf['errorLogger']
124 : function ( Exception
$e ) {
125 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
127 $this->deprecationLogger
= isset( $conf['deprecationLogger'] )
128 ?
$conf['deprecationLogger']
129 : function ( $msg ) {
130 trigger_error( $msg, E_USER_DEPRECATED
);
133 $this->profiler
= isset( $conf['profiler'] ) ?
$conf['profiler'] : null;
134 $this->trxProfiler
= isset( $conf['trxProfiler'] )
135 ?
$conf['trxProfiler']
136 : new TransactionProfiler();
138 $this->requestInfo
= [
139 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ?
$_SERVER[ 'REMOTE_ADDR' ] : '',
140 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ?
$_SERVER['HTTP_USER_AGENT'] : '',
141 'ChronologyProtection' => 'true',
142 // phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals -- library can't use $wgRequest
143 'ChronologyPositionIndex' => isset( $_GET['cpPosIndex'] ) ?
$_GET['cpPosIndex'] : null
146 $this->cliMode
= isset( $conf['cliMode'] )
148 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
149 $this->hostname
= isset( $conf['hostname'] ) ?
$conf['hostname'] : gethostname();
150 $this->agent
= isset( $conf['agent'] ) ?
$conf['agent'] : '';
152 $this->ticket
= mt_rand();
155 public function destroy() {
156 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
157 $this->forEachLBCallMethod( 'disable' );
160 public function shutdown(
161 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null, &$cpIndex = null
163 $chronProt = $this->getChronologyProtector();
164 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
165 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync', $cpIndex );
166 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
167 $this->shutdownChronologyProtector( $chronProt, null, 'async', $cpIndex );
170 $this->commitMasterChanges( __METHOD__
); // sanity
174 * @see ILBFactory::newMainLB()
175 * @param bool $domain
176 * @return ILoadBalancer
178 abstract public function newMainLB( $domain = false );
181 * @see ILBFactory::getMainLB()
182 * @param bool $domain
183 * @return ILoadBalancer
185 abstract public function getMainLB( $domain = false );
188 * @see ILBFactory::newExternalLB()
189 * @param string $cluster
190 * @return ILoadBalancer
192 abstract public function newExternalLB( $cluster );
195 * @see ILBFactory::getExternalLB()
196 * @param string $cluster
197 * @return ILoadBalancer
199 abstract public function getExternalLB( $cluster );
202 * Call a method of each tracked load balancer
204 * @param string $methodName
207 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
209 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
210 call_user_func_array( [ $loadBalancer, $methodName ], $args );
212 [ $methodName, $args ]
216 public function flushReplicaSnapshots( $fname = __METHOD__
) {
217 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
220 final public function commitAll( $fname = __METHOD__
, array $options = [] ) {
221 $this->commitMasterChanges( $fname, $options );
222 $this->forEachLBCallMethod( 'flushMasterSnapshots', [ $fname ] );
223 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
226 final public function beginMasterChanges( $fname = __METHOD__
) {
227 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
228 $this->trxRoundStage
= self
::ROUND_BEGINNING
;
229 if ( $this->trxRoundId
!== false ) {
230 throw new DBTransactionError(
232 "$fname: transaction round '{$this->trxRoundId}' already started."
235 $this->trxRoundId
= $fname;
236 // Set DBO_TRX flags on all appropriate DBs
237 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
238 $this->trxRoundStage
= self
::ROUND_CURSORY
;
241 final public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
242 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
243 $this->trxRoundStage
= self
::ROUND_COMMITTING
;
244 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
245 throw new DBTransactionError(
247 "$fname: transaction round '{$this->trxRoundId}' still running."
250 /** @noinspection PhpUnusedLocalVariableInspection */
251 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
252 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
254 $count = 0; // number of callbacks executed this iteration
255 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$count ) {
256 $count +
= $lb->finalizeMasterChanges();
258 } while ( $count > 0 );
259 $this->trxRoundId
= false;
260 // Perform pre-commit checks, aborting on failure
261 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
262 // Log the DBs and methods involved in multi-DB transactions
263 $this->logIfMultiDbTransaction();
264 // Actually perform the commit on all master DB connections and revert DBO_TRX
265 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
266 // Run all post-commit callbacks in a separate step
267 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
268 $e = $this->executePostTransactionCallbacks();
269 $this->trxRoundStage
= self
::ROUND_CURSORY
;
270 // Throw any last post-commit callback error
271 if ( $e instanceof Exception
) {
276 final public function rollbackMasterChanges( $fname = __METHOD__
) {
277 $this->trxRoundStage
= self
::ROUND_ROLLING_BACK
;
278 $this->trxRoundId
= false;
279 // Actually perform the rollback on all master DB connections and revert DBO_TRX
280 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
281 // Run all post-commit callbacks in a separate step
282 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
283 $this->executePostTransactionCallbacks();
284 $this->trxRoundStage
= self
::ROUND_CURSORY
;
288 * @return Exception|null
290 private function executePostTransactionCallbacks() {
291 // Run all post-commit callbacks until new ones stop getting added
292 $e = null; // first callback exception
294 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
295 $ex = $lb->runMasterTransactionIdleCallbacks();
298 } while ( $this->hasMasterChanges() );
299 // Run all listener callbacks once
300 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
301 $ex = $lb->runMasterTransactionListenerCallbacks();
308 public function hasTransactionRound() {
309 return ( $this->trxRoundId
!== false );
312 public function isReadyForRoundOperations() {
313 return ( $this->trxRoundStage
=== self
::ROUND_CURSORY
);
317 * Log query info if multi DB transactions are going to be committed now
319 private function logIfMultiDbTransaction() {
321 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
322 $masterName = $lb->getServerName( $lb->getWriterIndex() );
323 $callers = $lb->pendingMasterChangeCallers();
325 $callersByDB[$masterName] = $callers;
329 if ( count( $callersByDB ) >= 2 ) {
330 $dbs = implode( ', ', array_keys( $callersByDB ) );
331 $msg = "Multi-DB transaction [{$dbs}]:\n";
332 foreach ( $callersByDB as $db => $callers ) {
333 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
335 $this->queryLogger
->info( $msg );
339 public function hasMasterChanges() {
341 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
342 $ret = $ret ||
$lb->hasMasterChanges();
348 public function laggedReplicaUsed() {
350 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
351 $ret = $ret ||
$lb->laggedReplicaUsed();
357 public function hasOrMadeRecentMasterChanges( $age = null ) {
359 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
360 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
365 public function waitForReplication( array $opts = [] ) {
369 'timeout' => $this->cliMode ?
60 : 10,
370 'ifWritesSince' => null
373 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
374 $opts['domain'] = $opts['wiki']; // b/c
377 // Figure out which clusters need to be checked
378 /** @var ILoadBalancer[] $lbs */
380 if ( $opts['cluster'] !== false ) {
381 $lbs[] = $this->getExternalLB( $opts['cluster'] );
382 } elseif ( $opts['domain'] !== false ) {
383 $lbs[] = $this->getMainLB( $opts['domain'] );
385 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
389 return; // nothing actually used
393 // Get all the master positions of applicable DBs right now.
394 // This can be faster since waiting on one cluster reduces the
395 // time needed to wait on the next clusters.
396 $masterPositions = array_fill( 0, count( $lbs ), false );
397 foreach ( $lbs as $i => $lb ) {
398 if ( $lb->getServerCount() <= 1 ) {
399 // T29975 - Don't try to wait for replica DBs if there are none
400 // Prevents permission error when getting master position
402 } elseif ( $opts['ifWritesSince']
403 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
405 continue; // no writes since the last wait
407 $masterPositions[$i] = $lb->getMasterPos();
410 // Run any listener callbacks *after* getting the DB positions. The more
411 // time spent in the callbacks, the less time is spent in waitForAll().
412 foreach ( $this->replicationWaitCallbacks
as $callback ) {
417 foreach ( $lbs as $i => $lb ) {
418 if ( $masterPositions[$i] ) {
419 // The RDBMS may not support getMasterPos()
420 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
421 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
427 throw new DBReplicationWaitError(
429 "Could not wait for replica DBs to catch up to " .
430 implode( ', ', $failed )
435 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
437 $this->replicationWaitCallbacks
[$name] = $callback;
439 unset( $this->replicationWaitCallbacks
[$name] );
443 public function getEmptyTransactionTicket( $fname ) {
444 if ( $this->hasMasterChanges() ) {
445 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
446 ( new RuntimeException() )->getTraceAsString() );
451 return $this->ticket
;
454 final public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
455 if ( $ticket !== $this->ticket
) {
456 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
457 ( new RuntimeException() )->getTraceAsString() );
462 // The transaction owner and any caller with the empty transaction ticket can commit
463 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
464 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
465 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
466 $fnameEffective = $this->trxRoundId
;
468 $fnameEffective = $fname;
471 $this->commitMasterChanges( $fnameEffective );
472 $this->waitForReplication( $opts );
473 // If a nested caller committed on behalf of $fname, start another empty $fname
474 // transaction, leaving the caller with the same empty transaction state as before.
475 if ( $fnameEffective !== $fname ) {
476 $this->beginMasterChanges( $fnameEffective );
480 public function getChronologyProtectorTouched( $dbName ) {
481 return $this->getChronologyProtector()->getTouched( $dbName );
484 public function disableChronologyProtection() {
485 $this->getChronologyProtector()->setEnabled( false );
489 * @return ChronologyProtector
491 protected function getChronologyProtector() {
492 if ( $this->chronProt
) {
493 return $this->chronProt
;
496 $this->chronProt
= new ChronologyProtector(
499 'ip' => $this->requestInfo
['IPAddress'],
500 'agent' => $this->requestInfo
['UserAgent'],
502 $this->requestInfo
['ChronologyPositionIndex']
504 $this->chronProt
->setLogger( $this->replLogger
);
506 if ( $this->cliMode
) {
507 $this->chronProt
->setEnabled( false );
508 } elseif ( $this->requestInfo
['ChronologyProtection'] === 'false' ) {
509 // Request opted out of using position wait logic. This is useful for requests
510 // done by the job queue or background ETL that do not have a meaningful session.
511 $this->chronProt
->setWaitEnabled( false );
514 $this->replLogger
->debug( __METHOD__
. ': using request info ' .
515 json_encode( $this->requestInfo
, JSON_PRETTY_PRINT
) );
517 return $this->chronProt
;
521 * Get and record all of the staged DB positions into persistent memory storage
523 * @param ChronologyProtector $cp
524 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
525 * @param string $mode One of (sync, async); whether to wait on remote datacenters
526 * @param int|null &$cpIndex DB position key write counter; incremented on update
528 protected function shutdownChronologyProtector(
529 ChronologyProtector
$cp, $workCallback, $mode, &$cpIndex = null
531 // Record all the master positions needed
532 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
533 $cp->shutdownLB( $lb );
535 // Write them to the persistent stash. Try to do something useful by running $work
536 // while ChronologyProtector waits for the stash write to replicate to all DCs.
537 $unsavedPositions = $cp->shutdown( $workCallback, $mode, $cpIndex );
538 if ( $unsavedPositions && $workCallback ) {
539 // Invoke callback in case it did not cache the result yet
540 $workCallback(); // work now to block for less time in waitForAll()
542 // If the positions failed to write to the stash, at least wait on local datacenter
543 // replica DBs to catch up before responding. Even if there are several DCs, this increases
544 // the chance that the user will see their own changes immediately afterwards. As long
545 // as the sticky DC cookie applies (same domain), this is not even an issue.
546 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
547 $masterName = $lb->getServerName( $lb->getWriterIndex() );
548 if ( isset( $unsavedPositions[$masterName] ) ) {
549 $lb->waitForAll( $unsavedPositions[$masterName] );
555 * Base parameters to ILoadBalancer::__construct()
558 final protected function baseLoadBalancerParams() {
559 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
560 $initStage = ILoadBalancer
::STAGE_POSTCOMMIT_CALLBACKS
;
561 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
562 $initStage = ILoadBalancer
::STAGE_POSTROLLBACK_CALLBACKS
;
568 'localDomain' => $this->localDomain
,
569 'readOnlyReason' => $this->readOnlyReason
,
570 'srvCache' => $this->srvCache
,
571 'wanCache' => $this->wanCache
,
572 'profiler' => $this->profiler
,
573 'trxProfiler' => $this->trxProfiler
,
574 'queryLogger' => $this->queryLogger
,
575 'connLogger' => $this->connLogger
,
576 'replLogger' => $this->replLogger
,
577 'errorLogger' => $this->errorLogger
,
578 'deprecationLogger' => $this->deprecationLogger
,
579 'hostname' => $this->hostname
,
580 'cliMode' => $this->cliMode
,
581 'agent' => $this->agent
,
582 'chronologyCallback' => function ( ILoadBalancer
$lb ) {
583 // Defer ChronologyProtector construction in case setRequestInfo() ends up
584 // being called later (but before the first connection attempt) (T192611)
585 $this->getChronologyProtector()->initLB( $lb );
587 'roundStage' => $initStage
592 * @param ILoadBalancer $lb
594 protected function initLoadBalancer( ILoadBalancer
$lb ) {
595 if ( $this->trxRoundId
!== false ) {
596 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
599 $lb->setTableAliases( $this->tableAliases
);
600 $lb->setIndexAliases( $this->indexAliases
);
603 public function setTableAliases( array $aliases ) {
604 $this->tableAliases
= $aliases;
607 public function setIndexAliases( array $aliases ) {
608 $this->indexAliases
= $aliases;
611 public function setDomainPrefix( $prefix ) {
612 $this->localDomain
= new DatabaseDomain(
613 $this->localDomain
->getDatabase(),
618 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $prefix ) {
619 $lb->setDomainPrefix( $prefix );
623 public function closeAll() {
624 $this->forEachLBCallMethod( 'closeAll', [] );
627 public function setAgentName( $agent ) {
628 $this->agent
= $agent;
631 public function appendShutdownCPIndexAsQuery( $url, $index ) {
633 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$usedCluster ) {
634 $usedCluster |
= ( $lb->getServerCount() > 1 );
637 if ( !$usedCluster ) {
638 return $url; // no master/replica clusters touched
641 return strpos( $url, '?' ) === false ?
"$url?cpPosIndex=$index" : "$url&cpPosIndex=$index";
645 * @param int $index Write index
646 * @param int $time UNIX timestamp
647 * @return string Timestamp-qualified write index of the form "<index>.<timestamp>"
650 public static function makeCookieValueFromCPIndex( $index, $time ) {
651 return $index . '@' . $time;
655 * @param string $value String possibly of the form "<index>" or "<index>@<timestamp>"
656 * @param int $minTimestamp Lowest UNIX timestamp of non-expired values (if present)
657 * @return int|null Write index or null if $value is empty or expired
660 public static function getCPIndexFromCookieValue( $value, $minTimestamp ) {
661 if ( !preg_match( '/^(\d+)(?:@(\d+))?$/', $value, $m ) ) {
667 if ( isset( $m[2] ) && $m[2] !== '' && (int)$m[2] < $minTimestamp ) {
668 return null; // expired
671 return ( $index > 0 ) ?
$index : null;
674 public function setRequestInfo( array $info ) {
675 if ( $this->chronProt
) {
676 throw new LogicException( 'ChronologyProtector already initialized.' );
679 $this->requestInfo
= $info +
$this->requestInfo
;
683 * @param string $stage
685 private function assertTransactionRoundStage( $stage ) {
686 if ( $this->trxRoundStage
!== $stage ) {
687 throw new DBTransactionError(
689 "Transaction round stage must be '$stage' (not '{$this->trxRoundStage}')"
695 * Make PHP ignore user aborts/disconnects until the returned
696 * value leaves scope. This returns null and does nothing in CLI mode.
698 * @return ScopedCallback|null
700 final protected function getScopedPHPBehaviorForCommit() {
701 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
702 $old = ignore_user_abort( true ); // avoid half-finished operations
703 return new ScopedCallback( function () use ( $old ) {
704 ignore_user_abort( $old );
711 function __destruct() {
717 * @deprecated since 1.29
719 class_alias( LBFactory
::class, 'LBFactory' );