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 // Headers application can inject via LBFactory::setRequestInfo()
134 'ChronologyClientId' => null, // prior $cpClientId value from LBFactory::shutdown()
135 'ChronologyPositionIndex' => null // prior $cpIndex value from LBFactory::shutdown()
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
,
152 callable
$workCallback = null,
156 $chronProt = $this->getChronologyProtector();
157 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
158 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync', $cpIndex );
159 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
160 $this->shutdownChronologyProtector( $chronProt, null, 'async', $cpIndex );
163 $cpClientId = $chronProt->getClientId();
165 $this->commitMasterChanges( __METHOD__
); // sanity
169 * @see ILBFactory::newMainLB()
170 * @param bool $domain
171 * @return ILoadBalancer
173 abstract public function newMainLB( $domain = false );
176 * @see ILBFactory::getMainLB()
177 * @param bool $domain
178 * @return ILoadBalancer
180 abstract public function getMainLB( $domain = false );
183 * @see ILBFactory::newExternalLB()
184 * @param string $cluster
185 * @return ILoadBalancer
187 abstract public function newExternalLB( $cluster );
190 * @see ILBFactory::getExternalLB()
191 * @param string $cluster
192 * @return ILoadBalancer
194 abstract public function getExternalLB( $cluster );
197 * Call a method of each tracked load balancer
199 * @param string $methodName
202 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
204 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
205 call_user_func_array( [ $loadBalancer, $methodName ], $args );
207 [ $methodName, $args ]
211 public function flushReplicaSnapshots( $fname = __METHOD__
) {
212 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
215 final public function commitAll( $fname = __METHOD__
, array $options = [] ) {
216 $this->commitMasterChanges( $fname, $options );
217 $this->forEachLBCallMethod( 'flushMasterSnapshots', [ $fname ] );
218 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
221 final public function beginMasterChanges( $fname = __METHOD__
) {
222 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
223 $this->trxRoundStage
= self
::ROUND_BEGINNING
;
224 if ( $this->trxRoundId
!== false ) {
225 throw new DBTransactionError(
227 "$fname: transaction round '{$this->trxRoundId}' already started."
230 $this->trxRoundId
= $fname;
231 // Set DBO_TRX flags on all appropriate DBs
232 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
233 $this->trxRoundStage
= self
::ROUND_CURSORY
;
236 final public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
237 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
238 $this->trxRoundStage
= self
::ROUND_COMMITTING
;
239 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
240 throw new DBTransactionError(
242 "$fname: transaction round '{$this->trxRoundId}' still running."
245 /** @noinspection PhpUnusedLocalVariableInspection */
246 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
247 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
249 $count = 0; // number of callbacks executed this iteration
250 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$count ) {
251 $count +
= $lb->finalizeMasterChanges();
253 } while ( $count > 0 );
254 $this->trxRoundId
= false;
255 // Perform pre-commit checks, aborting on failure
256 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
257 // Log the DBs and methods involved in multi-DB transactions
258 $this->logIfMultiDbTransaction();
259 // Actually perform the commit on all master DB connections and revert DBO_TRX
260 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
261 // Run all post-commit callbacks in a separate step
262 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
263 $e = $this->executePostTransactionCallbacks();
264 $this->trxRoundStage
= self
::ROUND_CURSORY
;
265 // Throw any last post-commit callback error
266 if ( $e instanceof Exception
) {
271 final public function rollbackMasterChanges( $fname = __METHOD__
) {
272 $this->trxRoundStage
= self
::ROUND_ROLLING_BACK
;
273 $this->trxRoundId
= false;
274 // Actually perform the rollback on all master DB connections and revert DBO_TRX
275 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
276 // Run all post-commit callbacks in a separate step
277 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
278 $this->executePostTransactionCallbacks();
279 $this->trxRoundStage
= self
::ROUND_CURSORY
;
283 * @return Exception|null
285 private function executePostTransactionCallbacks() {
286 // Run all post-commit callbacks until new ones stop getting added
287 $e = null; // first callback exception
289 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
290 $ex = $lb->runMasterTransactionIdleCallbacks();
293 } while ( $this->hasMasterChanges() );
294 // Run all listener callbacks once
295 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
296 $ex = $lb->runMasterTransactionListenerCallbacks();
303 public function hasTransactionRound() {
304 return ( $this->trxRoundId
!== false );
307 public function isReadyForRoundOperations() {
308 return ( $this->trxRoundStage
=== self
::ROUND_CURSORY
);
312 * Log query info if multi DB transactions are going to be committed now
314 private function logIfMultiDbTransaction() {
316 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
317 $masterName = $lb->getServerName( $lb->getWriterIndex() );
318 $callers = $lb->pendingMasterChangeCallers();
320 $callersByDB[$masterName] = $callers;
324 if ( count( $callersByDB ) >= 2 ) {
325 $dbs = implode( ', ', array_keys( $callersByDB ) );
326 $msg = "Multi-DB transaction [{$dbs}]:\n";
327 foreach ( $callersByDB as $db => $callers ) {
328 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
330 $this->queryLogger
->info( $msg );
334 public function hasMasterChanges() {
336 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
337 $ret = $ret ||
$lb->hasMasterChanges();
343 public function laggedReplicaUsed() {
345 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
346 $ret = $ret ||
$lb->laggedReplicaUsed();
352 public function hasOrMadeRecentMasterChanges( $age = null ) {
354 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
355 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
360 public function waitForReplication( array $opts = [] ) {
364 'timeout' => $this->cliMode ?
60 : 10,
365 'ifWritesSince' => null
368 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
369 $opts['domain'] = $opts['wiki']; // b/c
372 // Figure out which clusters need to be checked
373 /** @var ILoadBalancer[] $lbs */
375 if ( $opts['cluster'] !== false ) {
376 $lbs[] = $this->getExternalLB( $opts['cluster'] );
377 } elseif ( $opts['domain'] !== false ) {
378 $lbs[] = $this->getMainLB( $opts['domain'] );
380 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
384 return; // nothing actually used
388 // Get all the master positions of applicable DBs right now.
389 // This can be faster since waiting on one cluster reduces the
390 // time needed to wait on the next clusters.
391 $masterPositions = array_fill( 0, count( $lbs ), false );
392 foreach ( $lbs as $i => $lb ) {
393 if ( $lb->getServerCount() <= 1 ) {
394 // T29975 - Don't try to wait for replica DBs if there are none
395 // Prevents permission error when getting master position
397 } elseif ( $opts['ifWritesSince']
398 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
400 continue; // no writes since the last wait
402 $masterPositions[$i] = $lb->getMasterPos();
405 // Run any listener callbacks *after* getting the DB positions. The more
406 // time spent in the callbacks, the less time is spent in waitForAll().
407 foreach ( $this->replicationWaitCallbacks
as $callback ) {
412 foreach ( $lbs as $i => $lb ) {
413 if ( $masterPositions[$i] ) {
414 // The RDBMS may not support getMasterPos()
415 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
416 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
422 throw new DBReplicationWaitError(
424 "Could not wait for replica DBs to catch up to " .
425 implode( ', ', $failed )
430 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
432 $this->replicationWaitCallbacks
[$name] = $callback;
434 unset( $this->replicationWaitCallbacks
[$name] );
438 public function getEmptyTransactionTicket( $fname ) {
439 if ( $this->hasMasterChanges() ) {
440 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
441 ( new RuntimeException() )->getTraceAsString() );
446 return $this->ticket
;
449 final public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
450 if ( $ticket !== $this->ticket
) {
451 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
452 ( new RuntimeException() )->getTraceAsString() );
457 // The transaction owner and any caller with the empty transaction ticket can commit
458 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
459 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
460 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
461 $fnameEffective = $this->trxRoundId
;
463 $fnameEffective = $fname;
466 $this->commitMasterChanges( $fnameEffective );
467 $this->waitForReplication( $opts );
468 // If a nested caller committed on behalf of $fname, start another empty $fname
469 // transaction, leaving the caller with the same empty transaction state as before.
470 if ( $fnameEffective !== $fname ) {
471 $this->beginMasterChanges( $fnameEffective );
475 public function getChronologyProtectorTouched( $dbName ) {
476 return $this->getChronologyProtector()->getTouched( $dbName );
479 public function disableChronologyProtection() {
480 $this->getChronologyProtector()->setEnabled( false );
484 * @return ChronologyProtector
486 protected function getChronologyProtector() {
487 if ( $this->chronProt
) {
488 return $this->chronProt
;
491 $this->chronProt
= new ChronologyProtector(
494 'ip' => $this->requestInfo
['IPAddress'],
495 'agent' => $this->requestInfo
['UserAgent'],
496 'clientId' => $this->requestInfo
['ChronologyClientId']
498 $this->requestInfo
['ChronologyPositionIndex']
500 $this->chronProt
->setLogger( $this->replLogger
);
502 if ( $this->cliMode
) {
503 $this->chronProt
->setEnabled( false );
504 } elseif ( $this->requestInfo
['ChronologyProtection'] === 'false' ) {
505 // Request opted out of using position wait logic. This is useful for requests
506 // done by the job queue or background ETL that do not have a meaningful session.
507 $this->chronProt
->setWaitEnabled( false );
510 $this->replLogger
->debug( __METHOD__
. ': using request info ' .
511 json_encode( $this->requestInfo
, JSON_PRETTY_PRINT
) );
513 return $this->chronProt
;
517 * Get and record all of the staged DB positions into persistent memory storage
519 * @param ChronologyProtector $cp
520 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
521 * @param string $mode One of (sync, async); whether to wait on remote datacenters
522 * @param int|null &$cpIndex DB position key write counter; incremented on update
524 protected function shutdownChronologyProtector(
525 ChronologyProtector
$cp, $workCallback, $mode, &$cpIndex = null
527 // Record all the master positions needed
528 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
529 $cp->shutdownLB( $lb );
531 // Write them to the persistent stash. Try to do something useful by running $work
532 // while ChronologyProtector waits for the stash write to replicate to all DCs.
533 $unsavedPositions = $cp->shutdown( $workCallback, $mode, $cpIndex );
534 if ( $unsavedPositions && $workCallback ) {
535 // Invoke callback in case it did not cache the result yet
536 $workCallback(); // work now to block for less time in waitForAll()
538 // If the positions failed to write to the stash, at least wait on local datacenter
539 // replica DBs to catch up before responding. Even if there are several DCs, this increases
540 // the chance that the user will see their own changes immediately afterwards. As long
541 // as the sticky DC cookie applies (same domain), this is not even an issue.
542 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
543 $masterName = $lb->getServerName( $lb->getWriterIndex() );
544 if ( isset( $unsavedPositions[$masterName] ) ) {
545 $lb->waitForAll( $unsavedPositions[$masterName] );
551 * Base parameters to ILoadBalancer::__construct()
554 final protected function baseLoadBalancerParams() {
555 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
556 $initStage = ILoadBalancer
::STAGE_POSTCOMMIT_CALLBACKS
;
557 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
558 $initStage = ILoadBalancer
::STAGE_POSTROLLBACK_CALLBACKS
;
564 'localDomain' => $this->localDomain
,
565 'readOnlyReason' => $this->readOnlyReason
,
566 'srvCache' => $this->srvCache
,
567 'wanCache' => $this->wanCache
,
568 'profiler' => $this->profiler
,
569 'trxProfiler' => $this->trxProfiler
,
570 'queryLogger' => $this->queryLogger
,
571 'connLogger' => $this->connLogger
,
572 'replLogger' => $this->replLogger
,
573 'errorLogger' => $this->errorLogger
,
574 'deprecationLogger' => $this->deprecationLogger
,
575 'hostname' => $this->hostname
,
576 'cliMode' => $this->cliMode
,
577 'agent' => $this->agent
,
578 'chronologyCallback' => function ( ILoadBalancer
$lb ) {
579 // Defer ChronologyProtector construction in case setRequestInfo() ends up
580 // being called later (but before the first connection attempt) (T192611)
581 $this->getChronologyProtector()->initLB( $lb );
583 'roundStage' => $initStage
588 * @param ILoadBalancer $lb
590 protected function initLoadBalancer( ILoadBalancer
$lb ) {
591 if ( $this->trxRoundId
!== false ) {
592 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
595 $lb->setTableAliases( $this->tableAliases
);
596 $lb->setIndexAliases( $this->indexAliases
);
599 public function setTableAliases( array $aliases ) {
600 $this->tableAliases
= $aliases;
603 public function setIndexAliases( array $aliases ) {
604 $this->indexAliases
= $aliases;
607 public function setDomainPrefix( $prefix ) {
608 $this->localDomain
= new DatabaseDomain(
609 $this->localDomain
->getDatabase(),
614 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $prefix ) {
615 $lb->setDomainPrefix( $prefix );
619 public function closeAll() {
620 $this->forEachLBCallMethod( 'closeAll', [] );
623 public function setAgentName( $agent ) {
624 $this->agent
= $agent;
627 public function appendShutdownCPIndexAsQuery( $url, $index ) {
629 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$usedCluster ) {
630 $usedCluster |
= ( $lb->getServerCount() > 1 );
633 if ( !$usedCluster ) {
634 return $url; // no master/replica clusters touched
637 return strpos( $url, '?' ) === false ?
"$url?cpPosIndex=$index" : "$url&cpPosIndex=$index";
641 * @param int $index Write index
642 * @param int $time UNIX timestamp; can be used to detect stale cookies (T190082)
643 * @param string $clientId Agent ID hash from ILBFactory::shutdown()
644 * @return string Timestamp-qualified write index of the form "<index>@<timestamp>#<hash>"
647 public static function makeCookieValueFromCPIndex( $index, $time, $clientId ) {
648 return "$index@$time#$clientId";
652 * @param string $value Possible result of LBFactory::makeCookieValueFromCPIndex()
653 * @param int $minTimestamp Lowest UNIX timestamp of non-expired values (if present)
654 * @return array (index: int or null, clientId: string or null)
657 public static function getCPInfoFromCookieValue( $value, $minTimestamp ) {
658 static $placeholder = [ 'index' => null, 'clientId' => null ];
660 if ( !preg_match( '/^(\d+)(?:@(\d+))?(?:#([0-9a-f]{32}))?$/', $value, $m ) ) {
661 return $placeholder; // invalid
666 return $placeholder; // invalid
667 } elseif ( isset( $m[2] ) && $m[2] !== '' && (int)$m[2] < $minTimestamp ) {
668 return $placeholder; // expired
671 $clientId = ( isset( $m[3] ) && $m[3] !== '' ) ?
$m[3] : null;
673 return [ 'index' => $index, 'clientId' => $clientId ];
676 public function setRequestInfo( array $info ) {
677 if ( $this->chronProt
) {
678 throw new LogicException( 'ChronologyProtector already initialized.' );
681 $this->requestInfo
= $info +
$this->requestInfo
;
685 * @param string $stage
687 private function assertTransactionRoundStage( $stage ) {
688 if ( $this->trxRoundStage
!== $stage ) {
689 throw new DBTransactionError(
691 "Transaction round stage must be '$stage' (not '{$this->trxRoundStage}')"
697 * Make PHP ignore user aborts/disconnects until the returned
698 * value leaves scope. This returns null and does nothing in CLI mode.
700 * @return ScopedCallback|null
702 final protected function getScopedPHPBehaviorForCommit() {
703 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
704 $old = ignore_user_abort( true ); // avoid half-finished operations
705 return new ScopedCallback( function () use ( $old ) {
706 ignore_user_abort( $old );
713 function __destruct() {
719 * @deprecated since 1.29
721 class_alias( LBFactory
::class, 'LBFactory' );