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';
99 private static $loggerFields =
100 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
102 public function __construct( array $conf ) {
103 $this->localDomain
= isset( $conf['localDomain'] )
104 ? DatabaseDomain
::newFromId( $conf['localDomain'] )
105 : DatabaseDomain
::newUnspecified();
107 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
108 $this->readOnlyReason
= $conf['readOnlyReason'];
111 $this->srvCache
= isset( $conf['srvCache'] ) ?
$conf['srvCache'] : new EmptyBagOStuff();
112 $this->memStash
= isset( $conf['memStash'] ) ?
$conf['memStash'] : new EmptyBagOStuff();
113 $this->wanCache
= isset( $conf['wanCache'] )
115 : WANObjectCache
::newEmpty();
117 foreach ( self
::$loggerFields as $key ) {
118 $this->$key = isset( $conf[$key] ) ?
$conf[$key] : new \Psr\Log\
NullLogger();
120 $this->errorLogger
= isset( $conf['errorLogger'] )
121 ?
$conf['errorLogger']
122 : function ( Exception
$e ) {
123 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
125 $this->deprecationLogger
= isset( $conf['deprecationLogger'] )
126 ?
$conf['deprecationLogger']
127 : function ( $msg ) {
128 trigger_error( $msg, E_USER_DEPRECATED
);
131 $this->profiler
= isset( $conf['profiler'] ) ?
$conf['profiler'] : null;
132 $this->trxProfiler
= isset( $conf['trxProfiler'] )
133 ?
$conf['trxProfiler']
134 : new TransactionProfiler();
136 $this->requestInfo
= [
137 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ?
$_SERVER[ 'REMOTE_ADDR' ] : '',
138 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ?
$_SERVER['HTTP_USER_AGENT'] : '',
139 'ChronologyProtection' => 'true',
140 'ChronologyPositionIndex' => isset( $_GET['cpPosIndex'] ) ?
$_GET['cpPosIndex'] : null
143 $this->cliMode
= isset( $conf['cliMode'] )
145 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
146 $this->hostname
= isset( $conf['hostname'] ) ?
$conf['hostname'] : gethostname();
147 $this->agent
= isset( $conf['agent'] ) ?
$conf['agent'] : '';
149 $this->ticket
= mt_rand();
152 public function destroy() {
153 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
154 $this->forEachLBCallMethod( 'disable' );
157 public function shutdown(
158 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null, &$cpIndex = null
160 $chronProt = $this->getChronologyProtector();
161 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
162 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync', $cpIndex );
163 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
164 $this->shutdownChronologyProtector( $chronProt, null, 'async', $cpIndex );
167 $this->commitMasterChanges( __METHOD__
); // sanity
171 * @see ILBFactory::newMainLB()
172 * @param bool $domain
173 * @return LoadBalancer
175 abstract public function newMainLB( $domain = false );
178 * @see ILBFactory::getMainLB()
179 * @param bool $domain
180 * @return LoadBalancer
182 abstract public function getMainLB( $domain = false );
185 * @see ILBFactory::newExternalLB()
186 * @param string $cluster
187 * @return LoadBalancer
189 abstract public function newExternalLB( $cluster );
192 * @see ILBFactory::getExternalLB()
193 * @param string $cluster
194 * @return LoadBalancer
196 abstract public function getExternalLB( $cluster );
199 * Call a method of each tracked load balancer
201 * @param string $methodName
204 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
206 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
207 call_user_func_array( [ $loadBalancer, $methodName ], $args );
209 [ $methodName, $args ]
213 public function flushReplicaSnapshots( $fname = __METHOD__
) {
214 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
217 final public function commitAll( $fname = __METHOD__
, array $options = [] ) {
218 $this->commitMasterChanges( $fname, $options );
219 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
222 final public function beginMasterChanges( $fname = __METHOD__
) {
223 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
224 $this->trxRoundStage
= self
::ROUND_BEGINNING
;
225 if ( $this->trxRoundId
!== false ) {
226 throw new DBTransactionError(
228 "$fname: transaction round '{$this->trxRoundId}' already started."
231 $this->trxRoundId
= $fname;
232 // Set DBO_TRX flags on all appropriate DBs
233 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
234 $this->trxRoundStage
= self
::ROUND_CURSORY
;
237 final public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
238 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
239 $this->trxRoundStage
= self
::ROUND_COMMITTING
;
240 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
241 throw new DBTransactionError(
243 "$fname: transaction round '{$this->trxRoundId}' still running."
246 /** @noinspection PhpUnusedLocalVariableInspection */
247 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
248 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
249 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
250 $this->trxRoundId
= false;
251 // Perform pre-commit checks, aborting on failure
252 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
253 // Log the DBs and methods involved in multi-DB transactions
254 $this->logIfMultiDbTransaction();
255 // Actually perform the commit on all master DB connections and revert DBO_TRX
256 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
257 // Run all post-commit callbacks until new ones stop getting added
258 $e = null; // first callback exception
260 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
261 $ex = $lb->runMasterTransactionIdleCallbacks();
264 } while ( $this->hasMasterChanges() );
265 // Run all listener callbacks once
266 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
267 $ex = $lb->runMasterTransactionListenerCallbacks();
270 $this->trxRoundStage
= self
::ROUND_CURSORY
;
271 // Throw any last post-commit callback error
272 if ( $e instanceof Exception
) {
277 final public function rollbackMasterChanges( $fname = __METHOD__
) {
278 $this->trxRoundStage
= self
::ROUND_ROLLING_BACK
;
279 $this->trxRoundId
= false;
280 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
281 $this->forEachLBCallMethod( 'runMasterTransactionIdleCallbacks' );
282 $this->forEachLBCallMethod( 'runMasterTransactionListenerCallbacks' );
283 $this->trxRoundStage
= self
::ROUND_CURSORY
;
286 public function hasTransactionRound() {
287 return ( $this->trxRoundId
!== false );
291 * Log query info if multi DB transactions are going to be committed now
293 private function logIfMultiDbTransaction() {
295 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
296 $masterName = $lb->getServerName( $lb->getWriterIndex() );
297 $callers = $lb->pendingMasterChangeCallers();
299 $callersByDB[$masterName] = $callers;
303 if ( count( $callersByDB ) >= 2 ) {
304 $dbs = implode( ', ', array_keys( $callersByDB ) );
305 $msg = "Multi-DB transaction [{$dbs}]:\n";
306 foreach ( $callersByDB as $db => $callers ) {
307 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
309 $this->queryLogger
->info( $msg );
313 public function hasMasterChanges() {
315 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
316 $ret = $ret ||
$lb->hasMasterChanges();
322 public function laggedReplicaUsed() {
324 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
325 $ret = $ret ||
$lb->laggedReplicaUsed();
331 public function hasOrMadeRecentMasterChanges( $age = null ) {
333 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
334 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
339 public function waitForReplication( array $opts = [] ) {
343 'timeout' => $this->cliMode ?
60 : 10,
344 'ifWritesSince' => null
347 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
348 $opts['domain'] = $opts['wiki']; // b/c
351 // Figure out which clusters need to be checked
352 /** @var ILoadBalancer[] $lbs */
354 if ( $opts['cluster'] !== false ) {
355 $lbs[] = $this->getExternalLB( $opts['cluster'] );
356 } elseif ( $opts['domain'] !== false ) {
357 $lbs[] = $this->getMainLB( $opts['domain'] );
359 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
363 return; // nothing actually used
367 // Get all the master positions of applicable DBs right now.
368 // This can be faster since waiting on one cluster reduces the
369 // time needed to wait on the next clusters.
370 $masterPositions = array_fill( 0, count( $lbs ), false );
371 foreach ( $lbs as $i => $lb ) {
372 if ( $lb->getServerCount() <= 1 ) {
373 // T29975 - Don't try to wait for replica DBs if there are none
374 // Prevents permission error when getting master position
376 } elseif ( $opts['ifWritesSince']
377 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
379 continue; // no writes since the last wait
381 $masterPositions[$i] = $lb->getMasterPos();
384 // Run any listener callbacks *after* getting the DB positions. The more
385 // time spent in the callbacks, the less time is spent in waitForAll().
386 foreach ( $this->replicationWaitCallbacks
as $callback ) {
391 foreach ( $lbs as $i => $lb ) {
392 if ( $masterPositions[$i] ) {
393 // The RDBMS may not support getMasterPos()
394 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
395 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
401 throw new DBReplicationWaitError(
403 "Could not wait for replica DBs to catch up to " .
404 implode( ', ', $failed )
409 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
411 $this->replicationWaitCallbacks
[$name] = $callback;
413 unset( $this->replicationWaitCallbacks
[$name] );
417 public function getEmptyTransactionTicket( $fname ) {
418 if ( $this->hasMasterChanges() ) {
419 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
420 ( new RuntimeException() )->getTraceAsString() );
425 return $this->ticket
;
428 final public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
429 if ( $ticket !== $this->ticket
) {
430 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
431 ( new RuntimeException() )->getTraceAsString() );
436 // The transaction owner and any caller with the empty transaction ticket can commit
437 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
438 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
439 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
440 $fnameEffective = $this->trxRoundId
;
442 $fnameEffective = $fname;
445 $this->commitMasterChanges( $fnameEffective );
446 $this->waitForReplication( $opts );
447 // If a nested caller committed on behalf of $fname, start another empty $fname
448 // transaction, leaving the caller with the same empty transaction state as before.
449 if ( $fnameEffective !== $fname ) {
450 $this->beginMasterChanges( $fnameEffective );
454 public function getChronologyProtectorTouched( $dbName ) {
455 return $this->getChronologyProtector()->getTouched( $dbName );
458 public function disableChronologyProtection() {
459 $this->getChronologyProtector()->setEnabled( false );
463 * @return ChronologyProtector
465 protected function getChronologyProtector() {
466 if ( $this->chronProt
) {
467 return $this->chronProt
;
470 $this->chronProt
= new ChronologyProtector(
473 'ip' => $this->requestInfo
['IPAddress'],
474 'agent' => $this->requestInfo
['UserAgent'],
476 $this->requestInfo
['ChronologyPositionIndex']
478 $this->chronProt
->setLogger( $this->replLogger
);
480 if ( $this->cliMode
) {
481 $this->chronProt
->setEnabled( false );
482 } elseif ( $this->requestInfo
['ChronologyProtection'] === 'false' ) {
483 // Request opted out of using position wait logic. This is useful for requests
484 // done by the job queue or background ETL that do not have a meaningful session.
485 $this->chronProt
->setWaitEnabled( false );
488 $this->replLogger
->debug( __METHOD__
. ': using request info ' .
489 json_encode( $this->requestInfo
, JSON_PRETTY_PRINT
) );
491 return $this->chronProt
;
495 * Get and record all of the staged DB positions into persistent memory storage
497 * @param ChronologyProtector $cp
498 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
499 * @param string $mode One of (sync, async); whether to wait on remote datacenters
500 * @param int|null &$cpIndex DB position key write counter; incremented on update
502 protected function shutdownChronologyProtector(
503 ChronologyProtector
$cp, $workCallback, $mode, &$cpIndex = null
505 // Record all the master positions needed
506 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
507 $cp->shutdownLB( $lb );
509 // Write them to the persistent stash. Try to do something useful by running $work
510 // while ChronologyProtector waits for the stash write to replicate to all DCs.
511 $unsavedPositions = $cp->shutdown( $workCallback, $mode, $cpIndex );
512 if ( $unsavedPositions && $workCallback ) {
513 // Invoke callback in case it did not cache the result yet
514 $workCallback(); // work now to block for less time in waitForAll()
516 // If the positions failed to write to the stash, at least wait on local datacenter
517 // replica DBs to catch up before responding. Even if there are several DCs, this increases
518 // the chance that the user will see their own changes immediately afterwards. As long
519 // as the sticky DC cookie applies (same domain), this is not even an issue.
520 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
521 $masterName = $lb->getServerName( $lb->getWriterIndex() );
522 if ( isset( $unsavedPositions[$masterName] ) ) {
523 $lb->waitForAll( $unsavedPositions[$masterName] );
529 * Base parameters to LoadBalancer::__construct()
532 final protected function baseLoadBalancerParams() {
534 'localDomain' => $this->localDomain
,
535 'readOnlyReason' => $this->readOnlyReason
,
536 'srvCache' => $this->srvCache
,
537 'wanCache' => $this->wanCache
,
538 'profiler' => $this->profiler
,
539 'trxProfiler' => $this->trxProfiler
,
540 'queryLogger' => $this->queryLogger
,
541 'connLogger' => $this->connLogger
,
542 'replLogger' => $this->replLogger
,
543 'errorLogger' => $this->errorLogger
,
544 'deprecationLogger' => $this->deprecationLogger
,
545 'hostname' => $this->hostname
,
546 'cliMode' => $this->cliMode
,
547 'agent' => $this->agent
,
548 'chronologyCallback' => function ( ILoadBalancer
$lb ) {
549 // Defer ChronologyProtector construction in case setRequestInfo() ends up
550 // being called later (but before the first connection attempt) (T192611)
551 $this->getChronologyProtector()->initLB( $lb );
557 * @param ILoadBalancer $lb
559 protected function initLoadBalancer( ILoadBalancer
$lb ) {
560 if ( $this->trxRoundId
!== false ) {
561 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
564 $lb->setTableAliases( $this->tableAliases
);
565 $lb->setIndexAliases( $this->indexAliases
);
568 public function setTableAliases( array $aliases ) {
569 $this->tableAliases
= $aliases;
572 public function setIndexAliases( array $aliases ) {
573 $this->indexAliases
= $aliases;
576 public function setDomainPrefix( $prefix ) {
577 $this->localDomain
= new DatabaseDomain(
578 $this->localDomain
->getDatabase(),
583 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $prefix ) {
584 $lb->setDomainPrefix( $prefix );
588 public function closeAll() {
589 $this->forEachLBCallMethod( 'closeAll', [] );
592 public function setAgentName( $agent ) {
593 $this->agent
= $agent;
596 public function appendShutdownCPIndexAsQuery( $url, $index ) {
598 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$usedCluster ) {
599 $usedCluster |
= ( $lb->getServerCount() > 1 );
602 if ( !$usedCluster ) {
603 return $url; // no master/replica clusters touched
606 return strpos( $url, '?' ) === false ?
"$url?cpPosIndex=$index" : "$url&cpPosIndex=$index";
609 public function setRequestInfo( array $info ) {
610 if ( $this->chronProt
) {
611 throw new LogicException( 'ChronologyProtector already initialized.' );
614 $this->requestInfo
= $info +
$this->requestInfo
;
618 * @param string $stage
620 private function assertTransactionRoundStage( $stage ) {
621 if ( $this->trxRoundStage
!== $stage ) {
622 throw new DBTransactionError(
624 "Transaction round stage must be '$stage' (not '{$this->trxRoundStage}')"
630 * Make PHP ignore user aborts/disconnects until the returned
631 * value leaves scope. This returns null and does nothing in CLI mode.
633 * @return ScopedCallback|null
635 final protected function getScopedPHPBehaviorForCommit() {
636 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
637 $old = ignore_user_abort( true ); // avoid half-finished operations
638 return new ScopedCallback( function () use ( $old ) {
639 ignore_user_abort( $old );
646 function __destruct() {
651 class_alias( LBFactory
::class, 'LBFactory' );