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 private static $loggerFields =
92 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
94 public function __construct( array $conf ) {
95 $this->localDomain
= isset( $conf['localDomain'] )
96 ? DatabaseDomain
::newFromId( $conf['localDomain'] )
97 : DatabaseDomain
::newUnspecified();
99 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
100 $this->readOnlyReason
= $conf['readOnlyReason'];
103 $this->srvCache
= isset( $conf['srvCache'] ) ?
$conf['srvCache'] : new EmptyBagOStuff();
104 $this->memStash
= isset( $conf['memStash'] ) ?
$conf['memStash'] : new EmptyBagOStuff();
105 $this->wanCache
= isset( $conf['wanCache'] )
107 : WANObjectCache
::newEmpty();
109 foreach ( self
::$loggerFields as $key ) {
110 $this->$key = isset( $conf[$key] ) ?
$conf[$key] : new \Psr\Log\
NullLogger();
112 $this->errorLogger
= isset( $conf['errorLogger'] )
113 ?
$conf['errorLogger']
114 : function ( Exception
$e ) {
115 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
117 $this->deprecationLogger
= isset( $conf['deprecationLogger'] )
118 ?
$conf['deprecationLogger']
119 : function ( $msg ) {
120 trigger_error( $msg, E_USER_DEPRECATED
);
123 $this->profiler
= isset( $conf['profiler'] ) ?
$conf['profiler'] : null;
124 $this->trxProfiler
= isset( $conf['trxProfiler'] )
125 ?
$conf['trxProfiler']
126 : new TransactionProfiler();
128 $this->requestInfo
= [
129 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ?
$_SERVER[ 'REMOTE_ADDR' ] : '',
130 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ?
$_SERVER['HTTP_USER_AGENT'] : '',
131 'ChronologyProtection' => 'true',
132 'ChronologyPositionIndex' => isset( $_GET['cpPosIndex'] ) ?
$_GET['cpPosIndex'] : null
135 $this->cliMode
= isset( $conf['cliMode'] )
137 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
138 $this->hostname
= isset( $conf['hostname'] ) ?
$conf['hostname'] : gethostname();
139 $this->agent
= isset( $conf['agent'] ) ?
$conf['agent'] : '';
141 $this->ticket
= mt_rand();
144 public function destroy() {
145 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
146 $this->forEachLBCallMethod( 'disable' );
149 public function shutdown(
150 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null, &$cpIndex = null
152 $chronProt = $this->getChronologyProtector();
153 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
154 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync', $cpIndex );
155 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
156 $this->shutdownChronologyProtector( $chronProt, null, 'async', $cpIndex );
159 $this->commitMasterChanges( __METHOD__
); // sanity
163 * @see ILBFactory::newMainLB()
164 * @param bool $domain
165 * @return LoadBalancer
167 abstract public function newMainLB( $domain = false );
170 * @see ILBFactory::getMainLB()
171 * @param bool $domain
172 * @return LoadBalancer
174 abstract public function getMainLB( $domain = false );
177 * @see ILBFactory::newExternalLB()
178 * @param string $cluster
179 * @return LoadBalancer
181 abstract public function newExternalLB( $cluster );
184 * @see ILBFactory::getExternalLB()
185 * @param string $cluster
186 * @return LoadBalancer
188 abstract public function getExternalLB( $cluster );
191 * Call a method of each tracked load balancer
193 * @param string $methodName
196 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
198 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
199 call_user_func_array( [ $loadBalancer, $methodName ], $args );
201 [ $methodName, $args ]
205 public function flushReplicaSnapshots( $fname = __METHOD__
) {
206 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
209 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
210 $this->commitMasterChanges( $fname, $options );
211 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
214 public function beginMasterChanges( $fname = __METHOD__
) {
215 if ( $this->trxRoundId
!== false ) {
216 throw new DBTransactionError(
218 "$fname: transaction round '{$this->trxRoundId}' already started."
221 $this->trxRoundId
= $fname;
222 // Set DBO_TRX flags on all appropriate DBs
223 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
226 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
227 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
228 throw new DBTransactionError(
230 "$fname: transaction round '{$this->trxRoundId}' still running."
233 /** @noinspection PhpUnusedLocalVariableInspection */
234 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
235 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
236 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
237 $this->trxRoundId
= false;
238 // Perform pre-commit checks, aborting on failure
239 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
240 // Log the DBs and methods involved in multi-DB transactions
241 $this->logIfMultiDbTransaction();
242 // Actually perform the commit on all master DB connections and revert DBO_TRX
243 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
244 // Run all post-commit callbacks
245 /** @var Exception $e */
246 $e = null; // first callback exception
247 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
248 $ex = $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_COMMIT
);
251 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
252 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
253 // Throw any last post-commit callback error
254 if ( $e instanceof Exception
) {
259 public function rollbackMasterChanges( $fname = __METHOD__
) {
260 $this->trxRoundId
= false;
261 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
262 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
263 // Run all post-rollback callbacks
264 $this->forEachLB( function ( ILoadBalancer
$lb ) {
265 $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_ROLLBACK
);
269 public function hasTransactionRound() {
270 return ( $this->trxRoundId
!== false );
274 * Log query info if multi DB transactions are going to be committed now
276 private function logIfMultiDbTransaction() {
278 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
279 $masterName = $lb->getServerName( $lb->getWriterIndex() );
280 $callers = $lb->pendingMasterChangeCallers();
282 $callersByDB[$masterName] = $callers;
286 if ( count( $callersByDB ) >= 2 ) {
287 $dbs = implode( ', ', array_keys( $callersByDB ) );
288 $msg = "Multi-DB transaction [{$dbs}]:\n";
289 foreach ( $callersByDB as $db => $callers ) {
290 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
292 $this->queryLogger
->info( $msg );
296 public function hasMasterChanges() {
298 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
299 $ret = $ret ||
$lb->hasMasterChanges();
305 public function laggedReplicaUsed() {
307 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
308 $ret = $ret ||
$lb->laggedReplicaUsed();
314 public function hasOrMadeRecentMasterChanges( $age = null ) {
316 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
317 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
322 public function waitForReplication( array $opts = [] ) {
326 'timeout' => $this->cliMode ?
60 : 10,
327 'ifWritesSince' => null
330 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
331 $opts['domain'] = $opts['wiki']; // b/c
334 // Figure out which clusters need to be checked
335 /** @var ILoadBalancer[] $lbs */
337 if ( $opts['cluster'] !== false ) {
338 $lbs[] = $this->getExternalLB( $opts['cluster'] );
339 } elseif ( $opts['domain'] !== false ) {
340 $lbs[] = $this->getMainLB( $opts['domain'] );
342 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
346 return; // nothing actually used
350 // Get all the master positions of applicable DBs right now.
351 // This can be faster since waiting on one cluster reduces the
352 // time needed to wait on the next clusters.
353 $masterPositions = array_fill( 0, count( $lbs ), false );
354 foreach ( $lbs as $i => $lb ) {
355 if ( $lb->getServerCount() <= 1 ) {
356 // T29975 - Don't try to wait for replica DBs if there are none
357 // Prevents permission error when getting master position
359 } elseif ( $opts['ifWritesSince']
360 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
362 continue; // no writes since the last wait
364 $masterPositions[$i] = $lb->getMasterPos();
367 // Run any listener callbacks *after* getting the DB positions. The more
368 // time spent in the callbacks, the less time is spent in waitForAll().
369 foreach ( $this->replicationWaitCallbacks
as $callback ) {
374 foreach ( $lbs as $i => $lb ) {
375 if ( $masterPositions[$i] ) {
376 // The RDBMS may not support getMasterPos()
377 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
378 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
384 throw new DBReplicationWaitError(
386 "Could not wait for replica DBs to catch up to " .
387 implode( ', ', $failed )
392 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
394 $this->replicationWaitCallbacks
[$name] = $callback;
396 unset( $this->replicationWaitCallbacks
[$name] );
400 public function getEmptyTransactionTicket( $fname ) {
401 if ( $this->hasMasterChanges() ) {
402 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
403 ( new RuntimeException() )->getTraceAsString() );
408 return $this->ticket
;
411 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
412 if ( $ticket !== $this->ticket
) {
413 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
414 ( new RuntimeException() )->getTraceAsString() );
419 // The transaction owner and any caller with the empty transaction ticket can commit
420 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
421 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
422 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
423 $fnameEffective = $this->trxRoundId
;
425 $fnameEffective = $fname;
428 $this->commitMasterChanges( $fnameEffective );
429 $this->waitForReplication( $opts );
430 // If a nested caller committed on behalf of $fname, start another empty $fname
431 // transaction, leaving the caller with the same empty transaction state as before.
432 if ( $fnameEffective !== $fname ) {
433 $this->beginMasterChanges( $fnameEffective );
437 public function getChronologyProtectorTouched( $dbName ) {
438 return $this->getChronologyProtector()->getTouched( $dbName );
441 public function disableChronologyProtection() {
442 $this->getChronologyProtector()->setEnabled( false );
446 * @return ChronologyProtector
448 protected function getChronologyProtector() {
449 if ( $this->chronProt
) {
450 return $this->chronProt
;
453 $this->chronProt
= new ChronologyProtector(
456 'ip' => $this->requestInfo
['IPAddress'],
457 'agent' => $this->requestInfo
['UserAgent'],
459 $this->requestInfo
['ChronologyPositionIndex']
461 $this->chronProt
->setLogger( $this->replLogger
);
463 if ( $this->cliMode
) {
464 $this->chronProt
->setEnabled( false );
465 } elseif ( $this->requestInfo
['ChronologyProtection'] === 'false' ) {
466 // Request opted out of using position wait logic. This is useful for requests
467 // done by the job queue or background ETL that do not have a meaningful session.
468 $this->chronProt
->setWaitEnabled( false );
471 $this->replLogger
->debug( __METHOD__
. ': using request info ' .
472 json_encode( $this->requestInfo
, JSON_PRETTY_PRINT
) );
474 return $this->chronProt
;
478 * Get and record all of the staged DB positions into persistent memory storage
480 * @param ChronologyProtector $cp
481 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
482 * @param string $mode One of (sync, async); whether to wait on remote datacenters
483 * @param int|null &$cpIndex DB position key write counter; incremented on update
485 protected function shutdownChronologyProtector(
486 ChronologyProtector
$cp, $workCallback, $mode, &$cpIndex = null
488 // Record all the master positions needed
489 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
490 $cp->shutdownLB( $lb );
492 // Write them to the persistent stash. Try to do something useful by running $work
493 // while ChronologyProtector waits for the stash write to replicate to all DCs.
494 $unsavedPositions = $cp->shutdown( $workCallback, $mode, $cpIndex );
495 if ( $unsavedPositions && $workCallback ) {
496 // Invoke callback in case it did not cache the result yet
497 $workCallback(); // work now to block for less time in waitForAll()
499 // If the positions failed to write to the stash, at least wait on local datacenter
500 // replica DBs to catch up before responding. Even if there are several DCs, this increases
501 // the chance that the user will see their own changes immediately afterwards. As long
502 // as the sticky DC cookie applies (same domain), this is not even an issue.
503 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
504 $masterName = $lb->getServerName( $lb->getWriterIndex() );
505 if ( isset( $unsavedPositions[$masterName] ) ) {
506 $lb->waitForAll( $unsavedPositions[$masterName] );
512 * Base parameters to LoadBalancer::__construct()
515 final protected function baseLoadBalancerParams() {
517 'localDomain' => $this->localDomain
,
518 'readOnlyReason' => $this->readOnlyReason
,
519 'srvCache' => $this->srvCache
,
520 'wanCache' => $this->wanCache
,
521 'profiler' => $this->profiler
,
522 'trxProfiler' => $this->trxProfiler
,
523 'queryLogger' => $this->queryLogger
,
524 'connLogger' => $this->connLogger
,
525 'replLogger' => $this->replLogger
,
526 'errorLogger' => $this->errorLogger
,
527 'deprecationLogger' => $this->deprecationLogger
,
528 'hostname' => $this->hostname
,
529 'cliMode' => $this->cliMode
,
530 'agent' => $this->agent
,
531 'chronologyCallback' => function ( ILoadBalancer
$lb ) {
532 // Defer ChronologyProtector construction in case setRequestInfo() ends up
533 // being called later (but before the first connection attempt) (T192611)
534 $this->getChronologyProtector()->initLB( $lb );
540 * @param ILoadBalancer $lb
542 protected function initLoadBalancer( ILoadBalancer
$lb ) {
543 if ( $this->trxRoundId
!== false ) {
544 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
547 $lb->setTableAliases( $this->tableAliases
);
548 $lb->setIndexAliases( $this->indexAliases
);
551 public function setTableAliases( array $aliases ) {
552 $this->tableAliases
= $aliases;
555 public function setIndexAliases( array $aliases ) {
556 $this->indexAliases
= $aliases;
559 public function setDomainPrefix( $prefix ) {
560 $this->localDomain
= new DatabaseDomain(
561 $this->localDomain
->getDatabase(),
566 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $prefix ) {
567 $lb->setDomainPrefix( $prefix );
571 public function closeAll() {
572 $this->forEachLBCallMethod( 'closeAll', [] );
575 public function setAgentName( $agent ) {
576 $this->agent
= $agent;
579 public function appendShutdownCPIndexAsQuery( $url, $index ) {
581 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$usedCluster ) {
582 $usedCluster |
= ( $lb->getServerCount() > 1 );
585 if ( !$usedCluster ) {
586 return $url; // no master/replica clusters touched
589 return strpos( $url, '?' ) === false ?
"$url?cpPosIndex=$index" : "$url&cpPosIndex=$index";
592 public function setRequestInfo( array $info ) {
593 if ( $this->chronProt
) {
594 throw new LogicException( 'ChronologyProtector already initialized.' );
597 $this->requestInfo
= $info +
$this->requestInfo
;
601 * Make PHP ignore user aborts/disconnects until the returned
602 * value leaves scope. This returns null and does nothing in CLI mode.
604 * @return ScopedCallback|null
606 final protected function getScopedPHPBehaviorForCommit() {
607 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
608 $old = ignore_user_abort( true ); // avoid half-finished operations
609 return new ScopedCallback( function () use ( $old ) {
610 ignore_user_abort( $old );
617 function __destruct() {
622 class_alias( LBFactory
::class, 'LBFactory' );