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
;
35 * An interface for generating database load balancers
38 abstract class LBFactory
implements ILBFactory
{
39 /** @var ChronologyProtector */
41 /** @var object|string Class name or object With profileIn/profileOut methods */
43 /** @var TransactionProfiler */
44 protected $trxProfiler;
45 /** @var LoggerInterface */
46 protected $replLogger;
47 /** @var LoggerInterface */
48 protected $connLogger;
49 /** @var LoggerInterface */
50 protected $queryLogger;
51 /** @var LoggerInterface */
52 protected $perfLogger;
53 /** @var callable Error logger */
54 protected $errorLogger;
55 /** @var callable Deprecation logger */
56 protected $deprecationLogger;
61 /** @var WANObjectCache */
64 /** @var DatabaseDomain Local domain */
65 protected $localDomain;
66 /** @var string Local hostname of the app server */
68 /** @var array Web request information about the client */
69 protected $requestInfo;
73 /** @var string|bool String if a requested DBO_TRX transaction round is active */
74 protected $trxRoundId = false;
75 /** @var string|bool Reason all LBs are read-only or false if not */
76 protected $readOnlyReason = false;
77 /** @var callable[] */
78 protected $replicationWaitCallbacks = [];
80 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
81 protected $tableAliases = [];
82 /** @var string[] Map of (index alias => index) */
83 protected $indexAliases = [];
85 /** @var bool Whether this PHP instance is for a CLI script */
87 /** @var string Agent name for query profiling */
90 private static $loggerFields =
91 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
93 public function __construct( array $conf ) {
94 $this->localDomain
= isset( $conf['localDomain'] )
95 ? DatabaseDomain
::newFromId( $conf['localDomain'] )
96 : DatabaseDomain
::newUnspecified();
98 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
99 $this->readOnlyReason
= $conf['readOnlyReason'];
102 $this->srvCache
= isset( $conf['srvCache'] ) ?
$conf['srvCache'] : new EmptyBagOStuff();
103 $this->memStash
= isset( $conf['memStash'] ) ?
$conf['memStash'] : new EmptyBagOStuff();
104 $this->wanCache
= isset( $conf['wanCache'] )
106 : WANObjectCache
::newEmpty();
108 foreach ( self
::$loggerFields as $key ) {
109 $this->$key = isset( $conf[$key] ) ?
$conf[$key] : new \Psr\Log\
NullLogger();
111 $this->errorLogger
= isset( $conf['errorLogger'] )
112 ?
$conf['errorLogger']
113 : function ( Exception
$e ) {
114 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
116 $this->deprecationLogger
= isset( $conf['deprecationLogger'] )
117 ?
$conf['deprecationLogger']
118 : function ( $msg ) {
119 trigger_error( $msg, E_USER_DEPRECATED
);
122 $this->profiler
= isset( $conf['profiler'] ) ?
$conf['profiler'] : null;
123 $this->trxProfiler
= isset( $conf['trxProfiler'] )
124 ?
$conf['trxProfiler']
125 : new TransactionProfiler();
127 $this->requestInfo
= [
128 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ?
$_SERVER[ 'REMOTE_ADDR' ] : '',
129 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ?
$_SERVER['HTTP_USER_AGENT'] : '',
130 'ChronologyProtection' => 'true',
131 'ChronologyPositionIndex' => isset( $_GET['cpPosIndex'] ) ?
$_GET['cpPosIndex'] : null
134 $this->cliMode
= isset( $conf['cliMode'] ) ?
$conf['cliMode'] : PHP_SAPI
=== 'cli';
135 $this->hostname
= isset( $conf['hostname'] ) ?
$conf['hostname'] : gethostname();
136 $this->agent
= isset( $conf['agent'] ) ?
$conf['agent'] : '';
138 $this->ticket
= mt_rand();
141 public function destroy() {
142 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
143 $this->forEachLBCallMethod( 'disable' );
146 public function shutdown(
147 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null, &$cpIndex = null
149 $chronProt = $this->getChronologyProtector();
150 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
151 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync', $cpIndex );
152 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
153 $this->shutdownChronologyProtector( $chronProt, null, 'async', $cpIndex );
156 $this->commitMasterChanges( __METHOD__
); // sanity
160 * @see ILBFactory::newMainLB()
161 * @param bool $domain
162 * @return LoadBalancer
164 abstract public function newMainLB( $domain = false );
167 * @see ILBFactory::getMainLB()
168 * @param bool $domain
169 * @return LoadBalancer
171 abstract public function getMainLB( $domain = false );
174 * @see ILBFactory::newExternalLB()
175 * @param string $cluster
176 * @return LoadBalancer
178 abstract public function newExternalLB( $cluster );
181 * @see ILBFactory::getExternalLB()
182 * @param string $cluster
183 * @return LoadBalancer
185 abstract public function getExternalLB( $cluster );
188 * Call a method of each tracked load balancer
190 * @param string $methodName
193 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
195 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
196 call_user_func_array( [ $loadBalancer, $methodName ], $args );
198 [ $methodName, $args ]
202 public function flushReplicaSnapshots( $fname = __METHOD__
) {
203 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
206 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
207 $this->commitMasterChanges( $fname, $options );
208 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
211 public function beginMasterChanges( $fname = __METHOD__
) {
212 if ( $this->trxRoundId
!== false ) {
213 throw new DBTransactionError(
215 "$fname: transaction round '{$this->trxRoundId}' already started."
218 $this->trxRoundId
= $fname;
219 // Set DBO_TRX flags on all appropriate DBs
220 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
223 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
224 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
225 throw new DBTransactionError(
227 "$fname: transaction round '{$this->trxRoundId}' still running."
230 /** @noinspection PhpUnusedLocalVariableInspection */
231 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
232 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
233 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
234 $this->trxRoundId
= false;
235 // Perform pre-commit checks, aborting on failure
236 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
237 // Log the DBs and methods involved in multi-DB transactions
238 $this->logIfMultiDbTransaction();
239 // Actually perform the commit on all master DB connections and revert DBO_TRX
240 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
241 // Run all post-commit callbacks
242 /** @var Exception $e */
243 $e = null; // first callback exception
244 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
245 $ex = $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_COMMIT
);
248 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
249 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
250 // Throw any last post-commit callback error
251 if ( $e instanceof Exception
) {
256 public function rollbackMasterChanges( $fname = __METHOD__
) {
257 $this->trxRoundId
= false;
258 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
259 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
260 // Run all post-rollback callbacks
261 $this->forEachLB( function ( ILoadBalancer
$lb ) {
262 $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_ROLLBACK
);
266 public function hasTransactionRound() {
267 return ( $this->trxRoundId
!== false );
271 * Log query info if multi DB transactions are going to be committed now
273 private function logIfMultiDbTransaction() {
275 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
276 $masterName = $lb->getServerName( $lb->getWriterIndex() );
277 $callers = $lb->pendingMasterChangeCallers();
279 $callersByDB[$masterName] = $callers;
283 if ( count( $callersByDB ) >= 2 ) {
284 $dbs = implode( ', ', array_keys( $callersByDB ) );
285 $msg = "Multi-DB transaction [{$dbs}]:\n";
286 foreach ( $callersByDB as $db => $callers ) {
287 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
289 $this->queryLogger
->info( $msg );
293 public function hasMasterChanges() {
295 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
296 $ret = $ret ||
$lb->hasMasterChanges();
302 public function laggedReplicaUsed() {
304 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
305 $ret = $ret ||
$lb->laggedReplicaUsed();
311 public function hasOrMadeRecentMasterChanges( $age = null ) {
313 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
314 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
319 public function waitForReplication( array $opts = [] ) {
323 'timeout' => $this->cliMode ?
60 : 10,
324 'ifWritesSince' => null
327 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
328 $opts['domain'] = $opts['wiki']; // b/c
331 // Figure out which clusters need to be checked
332 /** @var ILoadBalancer[] $lbs */
334 if ( $opts['cluster'] !== false ) {
335 $lbs[] = $this->getExternalLB( $opts['cluster'] );
336 } elseif ( $opts['domain'] !== false ) {
337 $lbs[] = $this->getMainLB( $opts['domain'] );
339 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
343 return; // nothing actually used
347 // Get all the master positions of applicable DBs right now.
348 // This can be faster since waiting on one cluster reduces the
349 // time needed to wait on the next clusters.
350 $masterPositions = array_fill( 0, count( $lbs ), false );
351 foreach ( $lbs as $i => $lb ) {
352 if ( $lb->getServerCount() <= 1 ) {
353 // T29975 - Don't try to wait for replica DBs if there are none
354 // Prevents permission error when getting master position
356 } elseif ( $opts['ifWritesSince']
357 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
359 continue; // no writes since the last wait
361 $masterPositions[$i] = $lb->getMasterPos();
364 // Run any listener callbacks *after* getting the DB positions. The more
365 // time spent in the callbacks, the less time is spent in waitForAll().
366 foreach ( $this->replicationWaitCallbacks
as $callback ) {
371 foreach ( $lbs as $i => $lb ) {
372 if ( $masterPositions[$i] ) {
373 // The RDBMS may not support getMasterPos()
374 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
375 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
381 throw new DBReplicationWaitError(
383 "Could not wait for replica DBs to catch up to " .
384 implode( ', ', $failed )
389 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
391 $this->replicationWaitCallbacks
[$name] = $callback;
393 unset( $this->replicationWaitCallbacks
[$name] );
397 public function getEmptyTransactionTicket( $fname ) {
398 if ( $this->hasMasterChanges() ) {
399 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
400 ( new RuntimeException() )->getTraceAsString() );
405 return $this->ticket
;
408 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
409 if ( $ticket !== $this->ticket
) {
410 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
411 ( new RuntimeException() )->getTraceAsString() );
416 // The transaction owner and any caller with the empty transaction ticket can commit
417 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
418 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
419 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
420 $fnameEffective = $this->trxRoundId
;
422 $fnameEffective = $fname;
425 $this->commitMasterChanges( $fnameEffective );
426 $this->waitForReplication( $opts );
427 // If a nested caller committed on behalf of $fname, start another empty $fname
428 // transaction, leaving the caller with the same empty transaction state as before.
429 if ( $fnameEffective !== $fname ) {
430 $this->beginMasterChanges( $fnameEffective );
434 public function getChronologyProtectorTouched( $dbName ) {
435 return $this->getChronologyProtector()->getTouched( $dbName );
438 public function disableChronologyProtection() {
439 $this->getChronologyProtector()->setEnabled( false );
443 * @return ChronologyProtector
445 protected function getChronologyProtector() {
446 if ( $this->chronProt
) {
447 return $this->chronProt
;
450 $this->chronProt
= new ChronologyProtector(
453 'ip' => $this->requestInfo
['IPAddress'],
454 'agent' => $this->requestInfo
['UserAgent'],
456 $this->requestInfo
['ChronologyPositionIndex']
458 $this->chronProt
->setLogger( $this->replLogger
);
460 if ( $this->cliMode
) {
461 $this->chronProt
->setEnabled( false );
462 } elseif ( $this->requestInfo
['ChronologyProtection'] === 'false' ) {
463 // Request opted out of using position wait logic. This is useful for requests
464 // done by the job queue or background ETL that do not have a meaningful session.
465 $this->chronProt
->setWaitEnabled( false );
468 $this->replLogger
->debug( __METHOD__
. ': using request info ' .
469 json_encode( $this->requestInfo
, JSON_PRETTY_PRINT
) );
471 return $this->chronProt
;
475 * Get and record all of the staged DB positions into persistent memory storage
477 * @param ChronologyProtector $cp
478 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
479 * @param string $mode One of (sync, async); whether to wait on remote datacenters
480 * @param int|null &$cpIndex DB position key write counter; incremented on update
482 protected function shutdownChronologyProtector(
483 ChronologyProtector
$cp, $workCallback, $mode, &$cpIndex = null
485 // Record all the master positions needed
486 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
487 $cp->shutdownLB( $lb );
489 // Write them to the persistent stash. Try to do something useful by running $work
490 // while ChronologyProtector waits for the stash write to replicate to all DCs.
491 $unsavedPositions = $cp->shutdown( $workCallback, $mode, $cpIndex );
492 if ( $unsavedPositions && $workCallback ) {
493 // Invoke callback in case it did not cache the result yet
494 $workCallback(); // work now to block for less time in waitForAll()
496 // If the positions failed to write to the stash, at least wait on local datacenter
497 // replica DBs to catch up before responding. Even if there are several DCs, this increases
498 // the chance that the user will see their own changes immediately afterwards. As long
499 // as the sticky DC cookie applies (same domain), this is not even an issue.
500 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
501 $masterName = $lb->getServerName( $lb->getWriterIndex() );
502 if ( isset( $unsavedPositions[$masterName] ) ) {
503 $lb->waitForAll( $unsavedPositions[$masterName] );
509 * Base parameters to LoadBalancer::__construct()
512 final protected function baseLoadBalancerParams() {
514 'localDomain' => $this->localDomain
,
515 'readOnlyReason' => $this->readOnlyReason
,
516 'srvCache' => $this->srvCache
,
517 'wanCache' => $this->wanCache
,
518 'profiler' => $this->profiler
,
519 'trxProfiler' => $this->trxProfiler
,
520 'queryLogger' => $this->queryLogger
,
521 'connLogger' => $this->connLogger
,
522 'replLogger' => $this->replLogger
,
523 'errorLogger' => $this->errorLogger
,
524 'deprecationLogger' => $this->deprecationLogger
,
525 'hostname' => $this->hostname
,
526 'cliMode' => $this->cliMode
,
527 'agent' => $this->agent
,
528 'chronologyProtector' => $this->getChronologyProtector()
533 * @param ILoadBalancer $lb
535 protected function initLoadBalancer( ILoadBalancer
$lb ) {
536 if ( $this->trxRoundId
!== false ) {
537 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
540 $lb->setTableAliases( $this->tableAliases
);
541 $lb->setIndexAliases( $this->indexAliases
);
544 public function setTableAliases( array $aliases ) {
545 $this->tableAliases
= $aliases;
548 public function setIndexAliases( array $aliases ) {
549 $this->indexAliases
= $aliases;
552 public function setDomainPrefix( $prefix ) {
553 $this->localDomain
= new DatabaseDomain(
554 $this->localDomain
->getDatabase(),
559 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $prefix ) {
560 $lb->setDomainPrefix( $prefix );
564 public function closeAll() {
565 $this->forEachLBCallMethod( 'closeAll', [] );
568 public function setAgentName( $agent ) {
569 $this->agent
= $agent;
572 public function appendShutdownCPIndexAsQuery( $url, $index ) {
574 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$usedCluster ) {
575 $usedCluster |
= ( $lb->getServerCount() > 1 );
578 if ( !$usedCluster ) {
579 return $url; // no master/replica clusters touched
582 return strpos( $url, '?' ) === false ?
"$url?cpPosIndex=$index" : "$url&cpPosIndex=$index";
585 public function setRequestInfo( array $info ) {
586 $this->requestInfo
= $info +
$this->requestInfo
;
590 * Make PHP ignore user aborts/disconnects until the returned
591 * value leaves scope. This returns null and does nothing in CLI mode.
593 * @return ScopedCallback|null
595 final protected function getScopedPHPBehaviorForCommit() {
596 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
597 $old = ignore_user_abort( true ); // avoid half-finished operations
598 return new ScopedCallback( function () use ( $old ) {
599 ignore_user_abort( $old );
606 function __destruct() {
611 class_alias( LBFactory
::class, 'LBFactory' );