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 */
46 /** @var LoggerInterface */
48 /** @var LoggerInterface */
50 /** @var LoggerInterface */
52 /** @var LoggerInterface */
54 /** @var callable Error logger */
56 /** @var callable Deprecation logger */
57 private $deprecationLogger;
63 /** @var WANObjectCache */
66 /** @var DatabaseDomain Local domain */
67 protected $localDomain;
69 /** @var string Local hostname of the app server */
71 /** @var array Web request information about the client */
73 /** @var bool Whether this PHP instance is for a CLI script */
75 /** @var string Agent name for query profiling */
78 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
79 private $tableAliases = [];
80 /** @var string[] Map of (index alias => index) */
81 private $indexAliases = [];
82 /** @var callable[] */
83 private $replicationWaitCallbacks = [];
87 /** @var string|bool String if a requested DBO_TRX transaction round is active */
88 private $trxRoundId = false;
89 /** @var string One of the ROUND_* class constants */
90 private $trxRoundStage = self
::ROUND_CURSORY
;
92 /** @var string|bool Reason all LBs are read-only or false if not */
93 protected $readOnlyReason = false;
95 /** @var string|null */
96 private $defaultGroup = null;
98 const ROUND_CURSORY
= 'cursory';
99 const ROUND_BEGINNING
= 'within-begin';
100 const ROUND_COMMITTING
= 'within-commit';
101 const ROUND_ROLLING_BACK
= 'within-rollback';
102 const ROUND_COMMIT_CALLBACKS
= 'within-commit-callbacks';
103 const ROUND_ROLLBACK_CALLBACKS
= 'within-rollback-callbacks';
105 private static $loggerFields =
106 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
108 public function __construct( array $conf ) {
109 $this->localDomain
= isset( $conf['localDomain'] )
110 ? DatabaseDomain
::newFromId( $conf['localDomain'] )
111 : DatabaseDomain
::newUnspecified();
113 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
114 $this->readOnlyReason
= $conf['readOnlyReason'];
117 $this->srvCache
= $conf['srvCache'] ??
new EmptyBagOStuff();
118 $this->memStash
= $conf['memStash'] ??
new EmptyBagOStuff();
119 $this->wanCache
= $conf['wanCache'] ?? WANObjectCache
::newEmpty();
121 foreach ( self
::$loggerFields as $key ) {
122 $this->$key = $conf[$key] ??
new \Psr\Log\
NullLogger();
124 $this->errorLogger
= $conf['errorLogger'] ??
function ( Exception
$e ) {
125 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
127 $this->deprecationLogger
= $conf['deprecationLogger'] ??
function ( $msg ) {
128 trigger_error( $msg, E_USER_DEPRECATED
);
131 $this->profiler
= $conf['profiler'] ??
null;
132 $this->trxProfiler
= $conf['trxProfiler'] ??
new TransactionProfiler();
134 $this->requestInfo
= [
135 'IPAddress' => $_SERVER[ 'REMOTE_ADDR' ] ??
'',
136 'UserAgent' => $_SERVER['HTTP_USER_AGENT'] ??
'',
137 // Headers application can inject via LBFactory::setRequestInfo()
138 'ChronologyProtection' => null,
139 'ChronologyClientId' => null, // prior $cpClientId value from LBFactory::shutdown()
140 'ChronologyPositionIndex' => null // prior $cpIndex value from LBFactory::shutdown()
143 $this->cliMode
= $conf['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
144 $this->hostname
= $conf['hostname'] ??
gethostname();
145 $this->agent
= $conf['agent'] ??
'';
146 $this->defaultGroup
= $conf['defaultGroup'] ??
null;
148 $this->ticket
= mt_rand();
151 public function destroy() {
152 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
153 $this->forEachLBCallMethod( 'disable' );
156 public function getLocalDomainID() {
157 return $this->localDomain
->getId();
160 public function resolveDomainID( $domain ) {
161 return ( $domain !== false ) ?
(string)$domain : $this->getLocalDomainID();
164 public function shutdown(
165 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
,
166 callable
$workCallback = null,
170 $chronProt = $this->getChronologyProtector();
171 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
172 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync', $cpIndex );
173 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
174 $this->shutdownChronologyProtector( $chronProt, null, 'async', $cpIndex );
177 $cpClientId = $chronProt->getClientId();
179 $this->commitMasterChanges( __METHOD__
); // sanity
183 * @see ILBFactory::newMainLB()
184 * @param bool $domain
185 * @return ILoadBalancer
187 abstract public function newMainLB( $domain = false );
190 * @see ILBFactory::getMainLB()
191 * @param bool $domain
192 * @return ILoadBalancer
194 abstract public function getMainLB( $domain = false );
197 * @see ILBFactory::newExternalLB()
198 * @param string $cluster
199 * @return ILoadBalancer
201 abstract public function newExternalLB( $cluster );
204 * @see ILBFactory::getExternalLB()
205 * @param string $cluster
206 * @return ILoadBalancer
208 abstract public function getExternalLB( $cluster );
211 * Call a method of each tracked load balancer
213 * @param string $methodName
216 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
218 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
219 $loadBalancer->$methodName( ...$args );
221 [ $methodName, $args ]
225 public function flushReplicaSnapshots( $fname = __METHOD__
) {
226 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
229 final public function commitAll( $fname = __METHOD__
, array $options = [] ) {
230 $this->commitMasterChanges( $fname, $options );
231 $this->forEachLBCallMethod( 'flushMasterSnapshots', [ $fname ] );
232 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
235 final public function beginMasterChanges( $fname = __METHOD__
) {
236 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
237 $this->trxRoundStage
= self
::ROUND_BEGINNING
;
238 if ( $this->trxRoundId
!== false ) {
239 throw new DBTransactionError(
241 "$fname: transaction round '{$this->trxRoundId}' already started."
244 $this->trxRoundId
= $fname;
245 // Set DBO_TRX flags on all appropriate DBs
246 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
247 $this->trxRoundStage
= self
::ROUND_CURSORY
;
250 final public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
251 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
252 $this->trxRoundStage
= self
::ROUND_COMMITTING
;
253 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
254 throw new DBTransactionError(
256 "$fname: transaction round '{$this->trxRoundId}' still running."
259 /** @noinspection PhpUnusedLocalVariableInspection */
260 $scope = ScopedCallback
::newScopedIgnoreUserAbort(); // try to ignore client aborts
261 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
263 $count = 0; // number of callbacks executed this iteration
264 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$count ) {
265 $count +
= $lb->finalizeMasterChanges();
267 } while ( $count > 0 );
268 $this->trxRoundId
= false;
269 // Perform pre-commit checks, aborting on failure
270 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
271 // Log the DBs and methods involved in multi-DB transactions
272 $this->logIfMultiDbTransaction();
273 // Actually perform the commit on all master DB connections and revert DBO_TRX
274 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
275 // Run all post-commit callbacks in a separate step
276 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
277 $e = $this->executePostTransactionCallbacks();
278 $this->trxRoundStage
= self
::ROUND_CURSORY
;
279 // Throw any last post-commit callback error
280 if ( $e instanceof Exception
) {
285 final public function rollbackMasterChanges( $fname = __METHOD__
) {
286 $this->trxRoundStage
= self
::ROUND_ROLLING_BACK
;
287 $this->trxRoundId
= false;
288 // Actually perform the rollback on all master DB connections and revert DBO_TRX
289 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
290 // Run all post-commit callbacks in a separate step
291 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
292 $this->executePostTransactionCallbacks();
293 $this->trxRoundStage
= self
::ROUND_CURSORY
;
297 * @return Exception|null
299 private function executePostTransactionCallbacks() {
300 // Run all post-commit callbacks until new ones stop getting added
301 $e = null; // first callback exception
303 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
304 $ex = $lb->runMasterTransactionIdleCallbacks();
307 } while ( $this->hasMasterChanges() );
308 // Run all listener callbacks once
309 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
310 $ex = $lb->runMasterTransactionListenerCallbacks();
317 public function hasTransactionRound() {
318 return ( $this->trxRoundId
!== false );
321 public function isReadyForRoundOperations() {
322 return ( $this->trxRoundStage
=== self
::ROUND_CURSORY
);
326 * Log query info if multi DB transactions are going to be committed now
328 private function logIfMultiDbTransaction() {
330 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
331 $masterName = $lb->getServerName( $lb->getWriterIndex() );
332 $callers = $lb->pendingMasterChangeCallers();
334 $callersByDB[$masterName] = $callers;
338 if ( count( $callersByDB ) >= 2 ) {
339 $dbs = implode( ', ', array_keys( $callersByDB ) );
340 $msg = "Multi-DB transaction [{$dbs}]:\n";
341 foreach ( $callersByDB as $db => $callers ) {
342 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
344 $this->queryLogger
->info( $msg );
348 public function hasMasterChanges() {
350 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
351 $ret = $ret ||
$lb->hasMasterChanges();
357 public function laggedReplicaUsed() {
359 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
360 $ret = $ret ||
$lb->laggedReplicaUsed();
366 public function hasOrMadeRecentMasterChanges( $age = null ) {
368 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
369 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
374 public function waitForReplication( array $opts = [] ) {
378 'timeout' => $this->cliMode ?
60 : 1,
379 'ifWritesSince' => null
382 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
383 $opts['domain'] = $opts['wiki']; // b/c
386 // Figure out which clusters need to be checked
387 /** @var ILoadBalancer[] $lbs */
389 if ( $opts['cluster'] !== false ) {
390 $lbs[] = $this->getExternalLB( $opts['cluster'] );
391 } elseif ( $opts['domain'] !== false ) {
392 $lbs[] = $this->getMainLB( $opts['domain'] );
394 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
398 return; // nothing actually used
402 // Get all the master positions of applicable DBs right now.
403 // This can be faster since waiting on one cluster reduces the
404 // time needed to wait on the next clusters.
405 $masterPositions = array_fill( 0, count( $lbs ), false );
406 foreach ( $lbs as $i => $lb ) {
407 if ( $lb->getServerCount() <= 1 ) {
408 // T29975 - Don't try to wait for replica DBs if there are none
409 // Prevents permission error when getting master position
411 } elseif ( $opts['ifWritesSince']
412 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
414 continue; // no writes since the last wait
416 $masterPositions[$i] = $lb->getMasterPos();
419 // Run any listener callbacks *after* getting the DB positions. The more
420 // time spent in the callbacks, the less time is spent in waitForAll().
421 foreach ( $this->replicationWaitCallbacks
as $callback ) {
426 foreach ( $lbs as $i => $lb ) {
427 if ( $masterPositions[$i] ) {
428 // The RDBMS may not support getMasterPos()
429 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
430 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
438 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
440 $this->replicationWaitCallbacks
[$name] = $callback;
442 unset( $this->replicationWaitCallbacks
[$name] );
446 public function getEmptyTransactionTicket( $fname ) {
447 if ( $this->hasMasterChanges() ) {
448 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
449 ( new RuntimeException() )->getTraceAsString() );
454 return $this->ticket
;
457 final public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
458 if ( $ticket !== $this->ticket
) {
459 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
460 ( new RuntimeException() )->getTraceAsString() );
465 // The transaction owner and any caller with the empty transaction ticket can commit
466 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
467 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
468 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
469 $fnameEffective = $this->trxRoundId
;
471 $fnameEffective = $fname;
474 $this->commitMasterChanges( $fnameEffective );
475 $waitSucceeded = $this->waitForReplication( $opts );
476 // If a nested caller committed on behalf of $fname, start another empty $fname
477 // transaction, leaving the caller with the same empty transaction state as before.
478 if ( $fnameEffective !== $fname ) {
479 $this->beginMasterChanges( $fnameEffective );
481 return $waitSucceeded;
484 public function getChronologyProtectorTouched( $dbName ) {
485 return $this->getChronologyProtector()->getTouched( $dbName );
488 public function disableChronologyProtection() {
489 $this->getChronologyProtector()->setEnabled( false );
493 * @return ChronologyProtector
495 protected function getChronologyProtector() {
496 if ( $this->chronProt
) {
497 return $this->chronProt
;
500 $this->chronProt
= new ChronologyProtector(
503 'ip' => $this->requestInfo
['IPAddress'],
504 'agent' => $this->requestInfo
['UserAgent'],
505 'clientId' => $this->requestInfo
['ChronologyClientId']
507 $this->requestInfo
['ChronologyPositionIndex']
509 $this->chronProt
->setLogger( $this->replLogger
);
511 if ( $this->cliMode
) {
512 $this->chronProt
->setEnabled( false );
513 } elseif ( $this->requestInfo
['ChronologyProtection'] === 'false' ) {
514 // Request opted out of using position wait logic. This is useful for requests
515 // done by the job queue or background ETL that do not have a meaningful session.
516 $this->chronProt
->setWaitEnabled( false );
517 } elseif ( $this->memStash
instanceof EmptyBagOStuff
) {
518 // No where to store any DB positions and wait for them to appear
519 $this->chronProt
->setEnabled( false );
520 $this->replLogger
->info( 'Cannot use ChronologyProtector with EmptyBagOStuff.' );
523 $this->replLogger
->debug( __METHOD__
. ': using request info ' .
524 json_encode( $this->requestInfo
, JSON_PRETTY_PRINT
) );
526 return $this->chronProt
;
530 * Get and record all of the staged DB positions into persistent memory storage
532 * @param ChronologyProtector $cp
533 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
534 * @param string $mode One of (sync, async); whether to wait on remote datacenters
535 * @param int|null &$cpIndex DB position key write counter; incremented on update
537 protected function shutdownChronologyProtector(
538 ChronologyProtector
$cp, $workCallback, $mode, &$cpIndex = null
540 // Record all the master positions needed
541 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
542 $cp->shutdownLB( $lb );
544 // Write them to the persistent stash. Try to do something useful by running $work
545 // while ChronologyProtector waits for the stash write to replicate to all DCs.
546 $unsavedPositions = $cp->shutdown( $workCallback, $mode, $cpIndex );
547 if ( $unsavedPositions && $workCallback ) {
548 // Invoke callback in case it did not cache the result yet
549 $workCallback(); // work now to block for less time in waitForAll()
551 // If the positions failed to write to the stash, at least wait on local datacenter
552 // replica DBs to catch up before responding. Even if there are several DCs, this increases
553 // the chance that the user will see their own changes immediately afterwards. As long
554 // as the sticky DC cookie applies (same domain), this is not even an issue.
555 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
556 $masterName = $lb->getServerName( $lb->getWriterIndex() );
557 if ( isset( $unsavedPositions[$masterName] ) ) {
558 $lb->waitForAll( $unsavedPositions[$masterName] );
564 * Base parameters to ILoadBalancer::__construct()
567 final protected function baseLoadBalancerParams() {
568 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
569 $initStage = ILoadBalancer
::STAGE_POSTCOMMIT_CALLBACKS
;
570 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
571 $initStage = ILoadBalancer
::STAGE_POSTROLLBACK_CALLBACKS
;
577 'localDomain' => $this->localDomain
,
578 'readOnlyReason' => $this->readOnlyReason
,
579 'srvCache' => $this->srvCache
,
580 'wanCache' => $this->wanCache
,
581 'profiler' => $this->profiler
,
582 'trxProfiler' => $this->trxProfiler
,
583 'queryLogger' => $this->queryLogger
,
584 'connLogger' => $this->connLogger
,
585 'replLogger' => $this->replLogger
,
586 'errorLogger' => $this->errorLogger
,
587 'deprecationLogger' => $this->deprecationLogger
,
588 'hostname' => $this->hostname
,
589 'cliMode' => $this->cliMode
,
590 'agent' => $this->agent
,
591 'defaultGroup' => $this->defaultGroup
,
592 'chronologyCallback' => function ( ILoadBalancer
$lb ) {
593 // Defer ChronologyProtector construction in case setRequestInfo() ends up
594 // being called later (but before the first connection attempt) (T192611)
595 $this->getChronologyProtector()->initLB( $lb );
597 'roundStage' => $initStage
602 * @param ILoadBalancer $lb
604 protected function initLoadBalancer( ILoadBalancer
$lb ) {
605 if ( $this->trxRoundId
!== false ) {
606 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
609 $lb->setTableAliases( $this->tableAliases
);
610 $lb->setIndexAliases( $this->indexAliases
);
613 public function setTableAliases( array $aliases ) {
614 $this->tableAliases
= $aliases;
617 public function setIndexAliases( array $aliases ) {
618 $this->indexAliases
= $aliases;
622 * @param string $prefix
623 * @deprecated Since 1.33
625 public function setDomainPrefix( $prefix ) {
626 $this->setLocalDomainPrefix( $prefix );
629 public function setLocalDomainPrefix( $prefix ) {
630 $this->localDomain
= new DatabaseDomain(
631 $this->localDomain
->getDatabase(),
636 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $prefix ) {
637 $lb->setLocalDomainPrefix( $prefix );
641 public function redefineLocalDomain( $domain ) {
644 $this->localDomain
= DatabaseDomain
::newFromId( $domain );
646 $this->forEachLB( function ( ILoadBalancer
$lb ) {
647 $lb->redefineLocalDomain( $this->localDomain
);
651 public function closeAll() {
652 $this->forEachLBCallMethod( 'closeAll', [] );
655 public function setAgentName( $agent ) {
656 $this->agent
= $agent;
659 public function appendShutdownCPIndexAsQuery( $url, $index ) {
661 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$usedCluster ) {
662 $usedCluster |
= ( $lb->getServerCount() > 1 );
665 if ( !$usedCluster ) {
666 return $url; // no master/replica clusters touched
669 return strpos( $url, '?' ) === false ?
"$url?cpPosIndex=$index" : "$url&cpPosIndex=$index";
673 * @param int $index Write index
674 * @param int $time UNIX timestamp; can be used to detect stale cookies (T190082)
675 * @param string $clientId Agent ID hash from ILBFactory::shutdown()
676 * @return string Timestamp-qualified write index of the form "<index>@<timestamp>#<hash>"
679 public static function makeCookieValueFromCPIndex( $index, $time, $clientId ) {
680 return "$index@$time#$clientId";
684 * @param string $value Possible result of LBFactory::makeCookieValueFromCPIndex()
685 * @param int $minTimestamp Lowest UNIX timestamp that a non-expired value can have
686 * @return array (index: int or null, clientId: string or null)
689 public static function getCPInfoFromCookieValue( $value, $minTimestamp ) {
690 static $placeholder = [ 'index' => null, 'clientId' => null ];
692 if ( !preg_match( '/^(\d+)@(\d+)#([0-9a-f]{32})$/', $value, $m ) ) {
693 return $placeholder; // invalid
698 return $placeholder; // invalid
699 } elseif ( isset( $m[2] ) && $m[2] !== '' && (int)$m[2] < $minTimestamp ) {
700 return $placeholder; // expired
703 $clientId = ( isset( $m[3] ) && $m[3] !== '' ) ?
$m[3] : null;
705 return [ 'index' => $index, 'clientId' => $clientId ];
708 public function setRequestInfo( array $info ) {
709 if ( $this->chronProt
) {
710 throw new LogicException( 'ChronologyProtector already initialized.' );
713 $this->requestInfo
= $info +
$this->requestInfo
;
717 * @param string $stage
719 private function assertTransactionRoundStage( $stage ) {
720 if ( $this->trxRoundStage
!== $stage ) {
721 throw new DBTransactionError(
723 "Transaction round stage must be '$stage' (not '{$this->trxRoundStage}')"
728 function __destruct() {