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 use Psr\Log\LoggerInterface
;
25 use Wikimedia\ScopedCallback
;
28 * An interface for generating database load balancers
31 abstract class LBFactory
implements ILBFactory
{
32 /** @var ChronologyProtector */
34 /** @var object|string Class name or object With profileIn/profileOut methods */
36 /** @var TransactionProfiler */
37 protected $trxProfiler;
38 /** @var LoggerInterface */
39 protected $replLogger;
40 /** @var LoggerInterface */
41 protected $connLogger;
42 /** @var LoggerInterface */
43 protected $queryLogger;
44 /** @var LoggerInterface */
45 protected $perfLogger;
46 /** @var callable Error logger */
47 protected $errorLogger;
52 /** @var WANObjectCache */
55 /** @var DatabaseDomain Local domain */
56 protected $localDomain;
57 /** @var string Local hostname of the app server */
59 /** @var array Web request information about the client */
60 protected $requestInfo;
62 /** @var bool[] Map of (section ID => true) for usage section IDs */
63 protected $usageSections = [];
67 /** @var string|bool String if a requested DBO_TRX transaction round is active */
68 protected $trxRoundId = false;
69 /** @var string|bool Reason all LBs are read-only or false if not */
70 protected $readOnlyReason = false;
71 /** @var callable[] */
72 protected $replicationWaitCallbacks = [];
74 /** @var bool Whether this PHP instance is for a CLI script */
76 /** @var string Agent name for query profiling */
79 private static $loggerFields =
80 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
82 public function __construct( array $conf ) {
83 $this->localDomain
= isset( $conf['localDomain'] )
84 ? DatabaseDomain
::newFromId( $conf['localDomain'] )
85 : DatabaseDomain
::newUnspecified();
87 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
88 $this->readOnlyReason
= $conf['readOnlyReason'];
91 $this->srvCache
= isset( $conf['srvCache'] ) ?
$conf['srvCache'] : new EmptyBagOStuff();
92 $this->memCache
= isset( $conf['memCache'] ) ?
$conf['memCache'] : new EmptyBagOStuff();
93 $this->wanCache
= isset( $conf['wanCache'] )
95 : WANObjectCache
::newEmpty();
97 foreach ( self
::$loggerFields as $key ) {
98 $this->$key = isset( $conf[$key] ) ?
$conf[$key] : new \Psr\Log\
NullLogger();
100 $this->errorLogger
= isset( $conf['errorLogger'] )
101 ?
$conf['errorLogger']
102 : function ( Exception
$e ) {
103 trigger_error( E_USER_WARNING
, get_class( $e ) . ': ' . $e->getMessage() );
106 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
107 $this->trxProfiler
= isset( $conf['trxProfiler'] )
108 ?
$conf['trxProfiler']
109 : new TransactionProfiler();
111 $this->requestInfo
= [
112 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ?
$_SERVER[ 'REMOTE_ADDR' ] : '',
113 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ?
$_SERVER['HTTP_USER_AGENT'] : '',
114 'ChronologyProtection' => 'true'
117 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
118 $this->hostname
= isset( $conf['hostname'] ) ?
$conf['hostname'] : gethostname();
119 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
121 $this->ticket
= mt_rand();
124 public function destroy() {
125 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
126 $this->forEachLBCallMethod( 'disable' );
129 public function shutdown(
130 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null
132 $chronProt = $this->getChronologyProtector();
133 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
134 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync' );
135 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
136 $this->shutdownChronologyProtector( $chronProt, null, 'async' );
139 $this->commitMasterChanges( __METHOD__
); // sanity
143 * @see ILBFactory::newMainLB()
144 * @param bool $domain
145 * @return LoadBalancer
147 abstract public function newMainLB( $domain = false );
150 * @see ILBFactory::getMainLB()
151 * @param bool $domain
152 * @return LoadBalancer
154 abstract public function getMainLB( $domain = false );
157 * @see ILBFactory::newExternalLB()
158 * @param string $cluster
159 * @return LoadBalancer
161 abstract public function newExternalLB( $cluster );
164 * @see ILBFactory::getExternalLB()
165 * @param string $cluster
166 * @return LoadBalancer
168 abstract public function getExternalLB( $cluster );
171 * Call a method of each tracked load balancer
173 * @param string $methodName
176 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
178 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
179 call_user_func_array( [ $loadBalancer, $methodName ], $args );
181 [ $methodName, $args ]
185 public function flushReplicaSnapshots( $fname = __METHOD__
) {
186 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
189 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
190 $this->commitMasterChanges( $fname, $options );
191 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
194 public function beginMasterChanges( $fname = __METHOD__
) {
195 if ( $this->trxRoundId
!== false ) {
196 throw new DBTransactionError(
198 "$fname: transaction round '{$this->trxRoundId}' already started."
201 $this->trxRoundId
= $fname;
202 // Set DBO_TRX flags on all appropriate DBs
203 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
206 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
207 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
208 throw new DBTransactionError(
210 "$fname: transaction round '{$this->trxRoundId}' still running."
213 /** @noinspection PhpUnusedLocalVariableInspection */
214 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
215 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
216 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
217 $this->trxRoundId
= false;
218 // Perform pre-commit checks, aborting on failure
219 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
220 // Log the DBs and methods involved in multi-DB transactions
221 $this->logIfMultiDbTransaction();
222 // Actually perform the commit on all master DB connections and revert DBO_TRX
223 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
224 // Run all post-commit callbacks
225 /** @var Exception $e */
226 $e = null; // first callback exception
227 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
228 $ex = $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_COMMIT
);
231 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
232 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
233 // Throw any last post-commit callback error
234 if ( $e instanceof Exception
) {
239 public function rollbackMasterChanges( $fname = __METHOD__
) {
240 $this->trxRoundId
= false;
241 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
242 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
243 // Run all post-rollback callbacks
244 $this->forEachLB( function ( ILoadBalancer
$lb ) {
245 $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_ROLLBACK
);
250 * Log query info if multi DB transactions are going to be committed now
252 private function logIfMultiDbTransaction() {
254 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
255 $masterName = $lb->getServerName( $lb->getWriterIndex() );
256 $callers = $lb->pendingMasterChangeCallers();
258 $callersByDB[$masterName] = $callers;
262 if ( count( $callersByDB ) >= 2 ) {
263 $dbs = implode( ', ', array_keys( $callersByDB ) );
264 $msg = "Multi-DB transaction [{$dbs}]:\n";
265 foreach ( $callersByDB as $db => $callers ) {
266 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
268 $this->queryLogger
->info( $msg );
272 public function hasMasterChanges() {
274 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
275 $ret = $ret ||
$lb->hasMasterChanges();
281 public function laggedReplicaUsed() {
283 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
284 $ret = $ret ||
$lb->laggedReplicaUsed();
290 public function hasOrMadeRecentMasterChanges( $age = null ) {
292 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
293 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
298 public function waitForReplication( array $opts = [] ) {
303 'ifWritesSince' => null
306 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
307 $opts['domain'] = $opts['wiki']; // b/c
310 // Figure out which clusters need to be checked
311 /** @var ILoadBalancer[] $lbs */
313 if ( $opts['cluster'] !== false ) {
314 $lbs[] = $this->getExternalLB( $opts['cluster'] );
315 } elseif ( $opts['domain'] !== false ) {
316 $lbs[] = $this->getMainLB( $opts['domain'] );
318 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
322 return; // nothing actually used
326 // Get all the master positions of applicable DBs right now.
327 // This can be faster since waiting on one cluster reduces the
328 // time needed to wait on the next clusters.
329 $masterPositions = array_fill( 0, count( $lbs ), false );
330 foreach ( $lbs as $i => $lb ) {
331 if ( $lb->getServerCount() <= 1 ) {
332 // Bug 27975 - Don't try to wait for replica DBs if there are none
333 // Prevents permission error when getting master position
335 } elseif ( $opts['ifWritesSince']
336 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
338 continue; // no writes since the last wait
340 $masterPositions[$i] = $lb->getMasterPos();
343 // Run any listener callbacks *after* getting the DB positions. The more
344 // time spent in the callbacks, the less time is spent in waitForAll().
345 foreach ( $this->replicationWaitCallbacks
as $callback ) {
350 foreach ( $lbs as $i => $lb ) {
351 if ( $masterPositions[$i] ) {
352 // The DBMS may not support getMasterPos()
353 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
354 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
360 throw new DBReplicationWaitError(
362 "Could not wait for replica DBs to catch up to " .
363 implode( ', ', $failed )
368 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
370 $this->replicationWaitCallbacks
[$name] = $callback;
372 unset( $this->replicationWaitCallbacks
[$name] );
376 public function getEmptyTransactionTicket( $fname ) {
377 if ( $this->hasMasterChanges() ) {
378 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
379 ( new RuntimeException() )->getTraceAsString() );
384 return $this->ticket
;
387 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
388 if ( $ticket !== $this->ticket
) {
389 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
390 ( new RuntimeException() )->getTraceAsString() );
395 // The transaction owner and any caller with the empty transaction ticket can commit
396 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
397 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
398 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
399 $fnameEffective = $this->trxRoundId
;
401 $fnameEffective = $fname;
404 $this->commitMasterChanges( $fnameEffective );
405 $this->waitForReplication( $opts );
406 // If a nested caller committed on behalf of $fname, start another empty $fname
407 // transaction, leaving the caller with the same empty transaction state as before.
408 if ( $fnameEffective !== $fname ) {
409 $this->beginMasterChanges( $fnameEffective );
413 public function getChronologyProtectorTouched( $dbName ) {
414 return $this->getChronologyProtector()->getTouched( $dbName );
417 public function disableChronologyProtection() {
418 $this->getChronologyProtector()->setEnabled( false );
422 * @return ChronologyProtector
424 protected function getChronologyProtector() {
425 if ( $this->chronProt
) {
426 return $this->chronProt
;
429 $this->chronProt
= new ChronologyProtector(
432 'ip' => $this->requestInfo
['IPAddress'],
433 'agent' => $this->requestInfo
['UserAgent'],
435 isset( $_GET['cpPosTime'] ) ?
$_GET['cpPosTime'] : null
437 $this->chronProt
->setLogger( $this->replLogger
);
439 if ( $this->cliMode
) {
440 $this->chronProt
->setEnabled( false );
441 } elseif ( $this->requestInfo
['ChronologyProtection'] === 'false' ) {
442 // Request opted out of using position wait logic. This is useful for requests
443 // done by the job queue or background ETL that do not have a meaningful session.
444 $this->chronProt
->setWaitEnabled( false );
447 $this->replLogger
->debug( __METHOD__
. ': using request info ' .
448 json_encode( $this->requestInfo
, JSON_PRETTY_PRINT
) );
450 return $this->chronProt
;
454 * Get and record all of the staged DB positions into persistent memory storage
456 * @param ChronologyProtector $cp
457 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
458 * @param string $mode One of (sync, async); whether to wait on remote datacenters
460 protected function shutdownChronologyProtector(
461 ChronologyProtector
$cp, $workCallback, $mode
463 // Record all the master positions needed
464 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
465 $cp->shutdownLB( $lb );
467 // Write them to the persistent stash. Try to do something useful by running $work
468 // while ChronologyProtector waits for the stash write to replicate to all DCs.
469 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
470 if ( $unsavedPositions && $workCallback ) {
471 // Invoke callback in case it did not cache the result yet
472 $workCallback(); // work now to block for less time in waitForAll()
474 // If the positions failed to write to the stash, at least wait on local datacenter
475 // replica DBs to catch up before responding. Even if there are several DCs, this increases
476 // the chance that the user will see their own changes immediately afterwards. As long
477 // as the sticky DC cookie applies (same domain), this is not even an issue.
478 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
479 $masterName = $lb->getServerName( $lb->getWriterIndex() );
480 if ( isset( $unsavedPositions[$masterName] ) ) {
481 $lb->waitForAll( $unsavedPositions[$masterName] );
487 * Base parameters to LoadBalancer::__construct()
490 final protected function baseLoadBalancerParams() {
492 'localDomain' => $this->localDomain
,
493 'readOnlyReason' => $this->readOnlyReason
,
494 'srvCache' => $this->srvCache
,
495 'wanCache' => $this->wanCache
,
496 'profiler' => $this->profiler
,
497 'trxProfiler' => $this->trxProfiler
,
498 'queryLogger' => $this->queryLogger
,
499 'connLogger' => $this->connLogger
,
500 'replLogger' => $this->replLogger
,
501 'errorLogger' => $this->errorLogger
,
502 'hostname' => $this->hostname
,
503 'cliMode' => $this->cliMode
,
504 'agent' => $this->agent
509 * Method called whenever a new LoadBalancer is created
511 * @param ILoadBalancer $lb
513 protected function initLoadBalancer( ILoadBalancer
$lb ) {
514 if ( $this->trxRoundId
!== false ) {
515 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
517 foreach ( $this->usageSections
as $id => $unused ) {
518 $lb->declareUsageSectionStart( $id );
522 public function setDomainPrefix( $prefix ) {
523 $this->localDomain
= new DatabaseDomain(
524 $this->localDomain
->getDatabase(),
529 $this->forEachLB( function( ILoadBalancer
$lb ) use ( $prefix ) {
530 $lb->setDomainPrefix( $prefix );
534 public function closeAll() {
535 $this->forEachLBCallMethod( 'closeAll', [] );
538 public function setAgentName( $agent ) {
539 $this->agent
= $agent;
542 public function appendPreShutdownTimeAsQuery( $url, $time ) {
544 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$usedCluster ) {
545 $usedCluster |
= ( $lb->getServerCount() > 1 );
548 if ( !$usedCluster ) {
549 return $url; // no master/replica clusters touched
552 return strpos( $url, '?' ) === false ?
"$url?cpPosTime=$time" : "$url&cpPosTime=$time";
555 public function setRequestInfo( array $info ) {
556 $this->requestInfo
= $info +
$this->requestInfo
;
559 public function declareUsageSectionStart( $id = null ) {
561 if ( $id === null ) {
565 // Handle existing load balancers
566 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $id ) {
567 $lb->declareUsageSectionStart( $id );
569 // Remember to set this for new load balancers
570 $this->usageSections
[$id] = true;
575 public function declareUsageSectionEnd( $id ) {
576 $info = [ 'readQueries' => 0, 'writeQueries' => 0, 'cacheSetOptions' => null ];
577 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $id, &$info ) {
578 $lbInfo = $lb->declareUsageSectionEnd( $id );
579 $info['readQueries'] +
= $lbInfo['readQueries'];
580 $info['writeQueries'] +
= $lbInfo['writeQueries'];
581 $dbCacheOpts = $lbInfo['cacheSetOptions'];
582 if ( $dbCacheOpts ) {
583 $info['cacheSetOptions'] = $info['cacheSetOptions']
584 ? Database
::mergeCacheSetOptions( $info['cacheSetOptions'], $dbCacheOpts )
588 unset( $this->usageSections
[$id] );
594 * Make PHP ignore user aborts/disconnects until the returned
595 * value leaves scope. This returns null and does nothing in CLI mode.
597 * @return ScopedCallback|null
599 final protected function getScopedPHPBehaviorForCommit() {
600 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
601 $old = ignore_user_abort( true ); // avoid half-finished operations
602 return new ScopedCallback( function () use ( $old ) {
603 ignore_user_abort( $old );
610 function __destruct() {