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;
59 /** @var WANObjectCache */
62 /** @var DatabaseDomain Local domain */
63 protected $localDomain;
64 /** @var string Local hostname of the app server */
66 /** @var array Web request information about the client */
67 protected $requestInfo;
71 /** @var string|bool String if a requested DBO_TRX transaction round is active */
72 protected $trxRoundId = false;
73 /** @var string|bool Reason all LBs are read-only or false if not */
74 protected $readOnlyReason = false;
75 /** @var callable[] */
76 protected $replicationWaitCallbacks = [];
78 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
79 protected $tableAliases = [];
80 /** @var string[] Map of (index alias => index) */
81 protected $indexAliases = [];
83 /** @var bool Whether this PHP instance is for a CLI script */
85 /** @var string Agent name for query profiling */
88 private static $loggerFields =
89 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
91 public function __construct( array $conf ) {
92 $this->localDomain
= isset( $conf['localDomain'] )
93 ? DatabaseDomain
::newFromId( $conf['localDomain'] )
94 : DatabaseDomain
::newUnspecified();
96 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
97 $this->readOnlyReason
= $conf['readOnlyReason'];
100 $this->srvCache
= isset( $conf['srvCache'] ) ?
$conf['srvCache'] : new EmptyBagOStuff();
101 $this->memStash
= isset( $conf['memStash'] ) ?
$conf['memStash'] : new EmptyBagOStuff();
102 $this->wanCache
= isset( $conf['wanCache'] )
104 : WANObjectCache
::newEmpty();
106 foreach ( self
::$loggerFields as $key ) {
107 $this->$key = isset( $conf[$key] ) ?
$conf[$key] : new \Psr\Log\
NullLogger();
109 $this->errorLogger
= isset( $conf['errorLogger'] )
110 ?
$conf['errorLogger']
111 : function ( Exception
$e ) {
112 trigger_error( E_USER_WARNING
, get_class( $e ) . ': ' . $e->getMessage() );
115 $this->profiler
= isset( $conf['profiler'] ) ?
$conf['profiler'] : null;
116 $this->trxProfiler
= isset( $conf['trxProfiler'] )
117 ?
$conf['trxProfiler']
118 : new TransactionProfiler();
120 $this->requestInfo
= [
121 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ?
$_SERVER[ 'REMOTE_ADDR' ] : '',
122 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ?
$_SERVER['HTTP_USER_AGENT'] : '',
123 'ChronologyProtection' => 'true',
124 'ChronologyPositionIndex' => isset( $_GET['cpPosIndex'] ) ?
$_GET['cpPosIndex'] : null
127 $this->cliMode
= isset( $conf['cliMode'] ) ?
$conf['cliMode'] : PHP_SAPI
=== 'cli';
128 $this->hostname
= isset( $conf['hostname'] ) ?
$conf['hostname'] : gethostname();
129 $this->agent
= isset( $conf['agent'] ) ?
$conf['agent'] : '';
131 $this->ticket
= mt_rand();
134 public function destroy() {
135 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
136 $this->forEachLBCallMethod( 'disable' );
139 public function shutdown(
140 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null, &$cpIndex = null
142 $chronProt = $this->getChronologyProtector();
143 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
144 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync', $cpIndex );
145 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
146 $this->shutdownChronologyProtector( $chronProt, null, 'async', $cpIndex );
149 $this->commitMasterChanges( __METHOD__
); // sanity
153 * @see ILBFactory::newMainLB()
154 * @param bool $domain
155 * @return LoadBalancer
157 abstract public function newMainLB( $domain = false );
160 * @see ILBFactory::getMainLB()
161 * @param bool $domain
162 * @return LoadBalancer
164 abstract public function getMainLB( $domain = false );
167 * @see ILBFactory::newExternalLB()
168 * @param string $cluster
169 * @return LoadBalancer
171 abstract public function newExternalLB( $cluster );
174 * @see ILBFactory::getExternalLB()
175 * @param string $cluster
176 * @return LoadBalancer
178 abstract public function getExternalLB( $cluster );
181 * Call a method of each tracked load balancer
183 * @param string $methodName
186 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
188 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
189 call_user_func_array( [ $loadBalancer, $methodName ], $args );
191 [ $methodName, $args ]
195 public function flushReplicaSnapshots( $fname = __METHOD__
) {
196 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
199 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
200 $this->commitMasterChanges( $fname, $options );
201 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
204 public function beginMasterChanges( $fname = __METHOD__
) {
205 if ( $this->trxRoundId
!== false ) {
206 throw new DBTransactionError(
208 "$fname: transaction round '{$this->trxRoundId}' already started."
211 $this->trxRoundId
= $fname;
212 // Set DBO_TRX flags on all appropriate DBs
213 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
216 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
217 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
218 throw new DBTransactionError(
220 "$fname: transaction round '{$this->trxRoundId}' still running."
223 /** @noinspection PhpUnusedLocalVariableInspection */
224 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
225 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
226 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
227 $this->trxRoundId
= false;
228 // Perform pre-commit checks, aborting on failure
229 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
230 // Log the DBs and methods involved in multi-DB transactions
231 $this->logIfMultiDbTransaction();
232 // Actually perform the commit on all master DB connections and revert DBO_TRX
233 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
234 // Run all post-commit callbacks
235 /** @var Exception $e */
236 $e = null; // first callback exception
237 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
238 $ex = $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_COMMIT
);
241 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
242 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
243 // Throw any last post-commit callback error
244 if ( $e instanceof Exception
) {
249 public function rollbackMasterChanges( $fname = __METHOD__
) {
250 $this->trxRoundId
= false;
251 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
252 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
253 // Run all post-rollback callbacks
254 $this->forEachLB( function ( ILoadBalancer
$lb ) {
255 $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_ROLLBACK
);
259 public function hasTransactionRound() {
260 return ( $this->trxRoundId
!== false );
264 * Log query info if multi DB transactions are going to be committed now
266 private function logIfMultiDbTransaction() {
268 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
269 $masterName = $lb->getServerName( $lb->getWriterIndex() );
270 $callers = $lb->pendingMasterChangeCallers();
272 $callersByDB[$masterName] = $callers;
276 if ( count( $callersByDB ) >= 2 ) {
277 $dbs = implode( ', ', array_keys( $callersByDB ) );
278 $msg = "Multi-DB transaction [{$dbs}]:\n";
279 foreach ( $callersByDB as $db => $callers ) {
280 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
282 $this->queryLogger
->info( $msg );
286 public function hasMasterChanges() {
288 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
289 $ret = $ret ||
$lb->hasMasterChanges();
295 public function laggedReplicaUsed() {
297 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
298 $ret = $ret ||
$lb->laggedReplicaUsed();
304 public function hasOrMadeRecentMasterChanges( $age = null ) {
306 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
307 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
312 public function waitForReplication( array $opts = [] ) {
317 'ifWritesSince' => null
320 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
321 $opts['domain'] = $opts['wiki']; // b/c
324 // Figure out which clusters need to be checked
325 /** @var ILoadBalancer[] $lbs */
327 if ( $opts['cluster'] !== false ) {
328 $lbs[] = $this->getExternalLB( $opts['cluster'] );
329 } elseif ( $opts['domain'] !== false ) {
330 $lbs[] = $this->getMainLB( $opts['domain'] );
332 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
336 return; // nothing actually used
340 // Get all the master positions of applicable DBs right now.
341 // This can be faster since waiting on one cluster reduces the
342 // time needed to wait on the next clusters.
343 $masterPositions = array_fill( 0, count( $lbs ), false );
344 foreach ( $lbs as $i => $lb ) {
345 if ( $lb->getServerCount() <= 1 ) {
346 // T29975 - Don't try to wait for replica DBs if there are none
347 // Prevents permission error when getting master position
349 } elseif ( $opts['ifWritesSince']
350 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
352 continue; // no writes since the last wait
354 $masterPositions[$i] = $lb->getMasterPos();
357 // Run any listener callbacks *after* getting the DB positions. The more
358 // time spent in the callbacks, the less time is spent in waitForAll().
359 foreach ( $this->replicationWaitCallbacks
as $callback ) {
364 foreach ( $lbs as $i => $lb ) {
365 if ( $masterPositions[$i] ) {
366 // The RDBMS may not support getMasterPos()
367 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
368 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
374 throw new DBReplicationWaitError(
376 "Could not wait for replica DBs to catch up to " .
377 implode( ', ', $failed )
382 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
384 $this->replicationWaitCallbacks
[$name] = $callback;
386 unset( $this->replicationWaitCallbacks
[$name] );
390 public function getEmptyTransactionTicket( $fname ) {
391 if ( $this->hasMasterChanges() ) {
392 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
393 ( new RuntimeException() )->getTraceAsString() );
398 return $this->ticket
;
401 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
402 if ( $ticket !== $this->ticket
) {
403 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
404 ( new RuntimeException() )->getTraceAsString() );
409 // The transaction owner and any caller with the empty transaction ticket can commit
410 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
411 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
412 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
413 $fnameEffective = $this->trxRoundId
;
415 $fnameEffective = $fname;
418 $this->commitMasterChanges( $fnameEffective );
419 $this->waitForReplication( $opts );
420 // If a nested caller committed on behalf of $fname, start another empty $fname
421 // transaction, leaving the caller with the same empty transaction state as before.
422 if ( $fnameEffective !== $fname ) {
423 $this->beginMasterChanges( $fnameEffective );
427 public function getChronologyProtectorTouched( $dbName ) {
428 return $this->getChronologyProtector()->getTouched( $dbName );
431 public function disableChronologyProtection() {
432 $this->getChronologyProtector()->setEnabled( false );
436 * @return ChronologyProtector
438 protected function getChronologyProtector() {
439 if ( $this->chronProt
) {
440 return $this->chronProt
;
443 $this->chronProt
= new ChronologyProtector(
446 'ip' => $this->requestInfo
['IPAddress'],
447 'agent' => $this->requestInfo
['UserAgent'],
449 $this->requestInfo
['ChronologyPositionIndex']
451 $this->chronProt
->setLogger( $this->replLogger
);
453 if ( $this->cliMode
) {
454 $this->chronProt
->setEnabled( false );
455 } elseif ( $this->requestInfo
['ChronologyProtection'] === 'false' ) {
456 // Request opted out of using position wait logic. This is useful for requests
457 // done by the job queue or background ETL that do not have a meaningful session.
458 $this->chronProt
->setWaitEnabled( false );
461 $this->replLogger
->debug( __METHOD__
. ': using request info ' .
462 json_encode( $this->requestInfo
, JSON_PRETTY_PRINT
) );
464 return $this->chronProt
;
468 * Get and record all of the staged DB positions into persistent memory storage
470 * @param ChronologyProtector $cp
471 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
472 * @param string $mode One of (sync, async); whether to wait on remote datacenters
473 * @param int|null &$cpIndex DB position key write counter; incremented on update
475 protected function shutdownChronologyProtector(
476 ChronologyProtector
$cp, $workCallback, $mode, &$cpIndex = null
478 // Record all the master positions needed
479 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
480 $cp->shutdownLB( $lb );
482 // Write them to the persistent stash. Try to do something useful by running $work
483 // while ChronologyProtector waits for the stash write to replicate to all DCs.
484 $unsavedPositions = $cp->shutdown( $workCallback, $mode, $cpIndex );
485 if ( $unsavedPositions && $workCallback ) {
486 // Invoke callback in case it did not cache the result yet
487 $workCallback(); // work now to block for less time in waitForAll()
489 // If the positions failed to write to the stash, at least wait on local datacenter
490 // replica DBs to catch up before responding. Even if there are several DCs, this increases
491 // the chance that the user will see their own changes immediately afterwards. As long
492 // as the sticky DC cookie applies (same domain), this is not even an issue.
493 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
494 $masterName = $lb->getServerName( $lb->getWriterIndex() );
495 if ( isset( $unsavedPositions[$masterName] ) ) {
496 $lb->waitForAll( $unsavedPositions[$masterName] );
502 * Base parameters to LoadBalancer::__construct()
505 final protected function baseLoadBalancerParams() {
507 'localDomain' => $this->localDomain
,
508 'readOnlyReason' => $this->readOnlyReason
,
509 'srvCache' => $this->srvCache
,
510 'wanCache' => $this->wanCache
,
511 'profiler' => $this->profiler
,
512 'trxProfiler' => $this->trxProfiler
,
513 'queryLogger' => $this->queryLogger
,
514 'connLogger' => $this->connLogger
,
515 'replLogger' => $this->replLogger
,
516 'errorLogger' => $this->errorLogger
,
517 'hostname' => $this->hostname
,
518 'cliMode' => $this->cliMode
,
519 'agent' => $this->agent
,
520 'chronologyProtector' => $this->getChronologyProtector()
525 * @param ILoadBalancer $lb
527 protected function initLoadBalancer( ILoadBalancer
$lb ) {
528 if ( $this->trxRoundId
!== false ) {
529 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
532 $lb->setTableAliases( $this->tableAliases
);
533 $lb->setIndexAliases( $this->indexAliases
);
536 public function setTableAliases( array $aliases ) {
537 $this->tableAliases
= $aliases;
540 public function setIndexAliases( array $aliases ) {
541 $this->indexAliases
= $aliases;
544 public function setDomainPrefix( $prefix ) {
545 $this->localDomain
= new DatabaseDomain(
546 $this->localDomain
->getDatabase(),
551 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $prefix ) {
552 $lb->setDomainPrefix( $prefix );
556 public function closeAll() {
557 $this->forEachLBCallMethod( 'closeAll', [] );
560 public function setAgentName( $agent ) {
561 $this->agent
= $agent;
564 public function appendShutdownCPIndexAsQuery( $url, $index ) {
566 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$usedCluster ) {
567 $usedCluster |
= ( $lb->getServerCount() > 1 );
570 if ( !$usedCluster ) {
571 return $url; // no master/replica clusters touched
574 return strpos( $url, '?' ) === false ?
"$url?cpPosIndex=$index" : "$url&cpPosIndex=$index";
577 public function setRequestInfo( array $info ) {
578 $this->requestInfo
= $info +
$this->requestInfo
;
582 * Make PHP ignore user aborts/disconnects until the returned
583 * value leaves scope. This returns null and does nothing in CLI mode.
585 * @return ScopedCallback|null
587 final protected function getScopedPHPBehaviorForCommit() {
588 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
589 $old = ignore_user_abort( true ); // avoid half-finished operations
590 return new ScopedCallback( function () use ( $old ) {
591 ignore_user_abort( $old );
598 function __destruct() {
603 class_alias( LBFactory
::class, 'LBFactory' );