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;
64 /** @var string|bool String if a requested DBO_TRX transaction round is active */
65 protected $trxRoundId = false;
66 /** @var string|bool Reason all LBs are read-only or false if not */
67 protected $readOnlyReason = false;
68 /** @var callable[] */
69 protected $replicationWaitCallbacks = [];
71 /** @var bool Whether this PHP instance is for a CLI script */
73 /** @var string Agent name for query profiling */
76 private static $loggerFields =
77 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
79 public function __construct( array $conf ) {
80 $this->localDomain
= isset( $conf['localDomain'] )
81 ? DatabaseDomain
::newFromId( $conf['localDomain'] )
82 : DatabaseDomain
::newUnspecified();
84 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
85 $this->readOnlyReason
= $conf['readOnlyReason'];
88 $this->srvCache
= isset( $conf['srvCache'] ) ?
$conf['srvCache'] : new EmptyBagOStuff();
89 $this->memCache
= isset( $conf['memCache'] ) ?
$conf['memCache'] : new EmptyBagOStuff();
90 $this->wanCache
= isset( $conf['wanCache'] )
92 : WANObjectCache
::newEmpty();
94 foreach ( self
::$loggerFields as $key ) {
95 $this->$key = isset( $conf[$key] ) ?
$conf[$key] : new \Psr\Log\
NullLogger();
97 $this->errorLogger
= isset( $conf['errorLogger'] )
98 ?
$conf['errorLogger']
99 : function ( Exception
$e ) {
100 trigger_error( E_WARNING
, get_class( $e ) . ': ' . $e->getMessage() );
103 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
104 $this->trxProfiler
= isset( $conf['trxProfiler'] )
105 ?
$conf['trxProfiler']
106 : new TransactionProfiler();
108 $this->requestInfo
= [
109 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ?
$_SERVER[ 'REMOTE_ADDR' ] : '',
110 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ?
$_SERVER['HTTP_USER_AGENT'] : '',
111 'ChronologyProtection' => 'true'
114 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
115 $this->hostname
= isset( $conf['hostname'] ) ?
$conf['hostname'] : gethostname();
116 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
118 $this->ticket
= mt_rand();
121 public function destroy() {
122 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
123 $this->forEachLBCallMethod( 'disable' );
126 public function shutdown(
127 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null
129 $chronProt = $this->getChronologyProtector();
130 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
131 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync' );
132 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
133 $this->shutdownChronologyProtector( $chronProt, null, 'async' );
136 $this->commitMasterChanges( __METHOD__
); // sanity
140 * @see ILBFactory::newMainLB()
141 * @param bool $domain
142 * @return LoadBalancer
144 abstract public function newMainLB( $domain = false );
147 * @see ILBFactory::getMainLB()
148 * @param bool $domain
149 * @return LoadBalancer
151 abstract public function getMainLB( $domain = false );
154 * @see ILBFactory::newExternalLB()
155 * @param string $cluster
156 * @param bool $domain
157 * @return LoadBalancer
159 abstract public function newExternalLB( $cluster, $domain = false );
162 * @see ILBFactory::getExternalLB()
163 * @param string $cluster
164 * @param bool $domain
165 * @return LoadBalancer
167 abstract public function getExternalLB( $cluster, $domain = false );
170 * Call a method of each tracked load balancer
172 * @param string $methodName
175 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
177 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
178 call_user_func_array( [ $loadBalancer, $methodName ], $args );
180 [ $methodName, $args ]
184 public function flushReplicaSnapshots( $fname = __METHOD__
) {
185 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
188 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
189 $this->commitMasterChanges( $fname, $options );
190 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
193 public function beginMasterChanges( $fname = __METHOD__
) {
194 if ( $this->trxRoundId
!== false ) {
195 throw new DBTransactionError(
197 "$fname: transaction round '{$this->trxRoundId}' already started."
200 $this->trxRoundId
= $fname;
201 // Set DBO_TRX flags on all appropriate DBs
202 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
205 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
206 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
207 throw new DBTransactionError(
209 "$fname: transaction round '{$this->trxRoundId}' still running."
212 /** @noinspection PhpUnusedLocalVariableInspection */
213 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
214 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
215 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
216 $this->trxRoundId
= false;
217 // Perform pre-commit checks, aborting on failure
218 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
219 // Log the DBs and methods involved in multi-DB transactions
220 $this->logIfMultiDbTransaction();
221 // Actually perform the commit on all master DB connections and revert DBO_TRX
222 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
223 // Run all post-commit callbacks
224 /** @var Exception $e */
225 $e = null; // first callback exception
226 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
227 $ex = $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_COMMIT
);
230 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
231 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
232 // Throw any last post-commit callback error
233 if ( $e instanceof Exception
) {
238 public function rollbackMasterChanges( $fname = __METHOD__
) {
239 $this->trxRoundId
= false;
240 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
241 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
242 // Run all post-rollback callbacks
243 $this->forEachLB( function ( ILoadBalancer
$lb ) {
244 $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_ROLLBACK
);
249 * Log query info if multi DB transactions are going to be committed now
251 private function logIfMultiDbTransaction() {
253 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
254 $masterName = $lb->getServerName( $lb->getWriterIndex() );
255 $callers = $lb->pendingMasterChangeCallers();
257 $callersByDB[$masterName] = $callers;
261 if ( count( $callersByDB ) >= 2 ) {
262 $dbs = implode( ', ', array_keys( $callersByDB ) );
263 $msg = "Multi-DB transaction [{$dbs}]:\n";
264 foreach ( $callersByDB as $db => $callers ) {
265 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
267 $this->queryLogger
->info( $msg );
271 public function hasMasterChanges() {
273 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
274 $ret = $ret ||
$lb->hasMasterChanges();
280 public function laggedReplicaUsed() {
282 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
283 $ret = $ret ||
$lb->laggedReplicaUsed();
289 public function hasOrMadeRecentMasterChanges( $age = null ) {
291 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
292 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
297 public function waitForReplication( array $opts = [] ) {
302 'ifWritesSince' => null
305 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
306 $opts['domain'] = $opts['wiki']; // b/c
309 // Figure out which clusters need to be checked
310 /** @var ILoadBalancer[] $lbs */
312 if ( $opts['cluster'] !== false ) {
313 $lbs[] = $this->getExternalLB( $opts['cluster'] );
314 } elseif ( $opts['domain'] !== false ) {
315 $lbs[] = $this->getMainLB( $opts['domain'] );
317 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
321 return; // nothing actually used
325 // Get all the master positions of applicable DBs right now.
326 // This can be faster since waiting on one cluster reduces the
327 // time needed to wait on the next clusters.
328 $masterPositions = array_fill( 0, count( $lbs ), false );
329 foreach ( $lbs as $i => $lb ) {
330 if ( $lb->getServerCount() <= 1 ) {
331 // Bug 27975 - Don't try to wait for replica DBs if there are none
332 // Prevents permission error when getting master position
334 } elseif ( $opts['ifWritesSince']
335 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
337 continue; // no writes since the last wait
339 $masterPositions[$i] = $lb->getMasterPos();
342 // Run any listener callbacks *after* getting the DB positions. The more
343 // time spent in the callbacks, the less time is spent in waitForAll().
344 foreach ( $this->replicationWaitCallbacks
as $callback ) {
349 foreach ( $lbs as $i => $lb ) {
350 if ( $masterPositions[$i] ) {
351 // The DBMS may not support getMasterPos()
352 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
353 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
359 throw new DBReplicationWaitError(
360 "Could not wait for replica DBs to catch up to " .
361 implode( ', ', $failed )
366 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
368 $this->replicationWaitCallbacks
[$name] = $callback;
370 unset( $this->replicationWaitCallbacks
[$name] );
374 public function getEmptyTransactionTicket( $fname ) {
375 if ( $this->hasMasterChanges() ) {
376 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
377 ( new RuntimeException() )->getTraceAsString() );
382 return $this->ticket
;
385 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
386 if ( $ticket !== $this->ticket
) {
387 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
388 ( new RuntimeException() )->getTraceAsString() );
393 // The transaction owner and any caller with the empty transaction ticket can commit
394 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
395 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
396 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
397 $fnameEffective = $this->trxRoundId
;
399 $fnameEffective = $fname;
402 $this->commitMasterChanges( $fnameEffective );
403 $this->waitForReplication( $opts );
404 // If a nested caller committed on behalf of $fname, start another empty $fname
405 // transaction, leaving the caller with the same empty transaction state as before.
406 if ( $fnameEffective !== $fname ) {
407 $this->beginMasterChanges( $fnameEffective );
411 public function getChronologyProtectorTouched( $dbName ) {
412 return $this->getChronologyProtector()->getTouched( $dbName );
415 public function disableChronologyProtection() {
416 $this->getChronologyProtector()->setEnabled( false );
420 * @return ChronologyProtector
422 protected function getChronologyProtector() {
423 if ( $this->chronProt
) {
424 return $this->chronProt
;
427 $this->chronProt
= new ChronologyProtector(
430 'ip' => $this->requestInfo
['IPAddress'],
431 'agent' => $this->requestInfo
['UserAgent'],
433 isset( $_GET['cpPosTime'] ) ?
$_GET['cpPosTime'] : null
435 $this->chronProt
->setLogger( $this->replLogger
);
437 if ( $this->cliMode
) {
438 $this->chronProt
->setEnabled( false );
439 } elseif ( $this->requestInfo
['ChronologyProtection'] === 'false' ) {
440 // Request opted out of using position wait logic. This is useful for requests
441 // done by the job queue or background ETL that do not have a meaningful session.
442 $this->chronProt
->setWaitEnabled( false );
445 $this->replLogger
->debug( __METHOD__
. ': using request info ' .
446 json_encode( $this->requestInfo
, JSON_PRETTY_PRINT
) );
448 return $this->chronProt
;
452 * Get and record all of the staged DB positions into persistent memory storage
454 * @param ChronologyProtector $cp
455 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
456 * @param string $mode One of (sync, async); whether to wait on remote datacenters
458 protected function shutdownChronologyProtector(
459 ChronologyProtector
$cp, $workCallback, $mode
461 // Record all the master positions needed
462 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
463 $cp->shutdownLB( $lb );
465 // Write them to the persistent stash. Try to do something useful by running $work
466 // while ChronologyProtector waits for the stash write to replicate to all DCs.
467 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
468 if ( $unsavedPositions && $workCallback ) {
469 // Invoke callback in case it did not cache the result yet
470 $workCallback(); // work now to block for less time in waitForAll()
472 // If the positions failed to write to the stash, at least wait on local datacenter
473 // replica DBs to catch up before responding. Even if there are several DCs, this increases
474 // the chance that the user will see their own changes immediately afterwards. As long
475 // as the sticky DC cookie applies (same domain), this is not even an issue.
476 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
477 $masterName = $lb->getServerName( $lb->getWriterIndex() );
478 if ( isset( $unsavedPositions[$masterName] ) ) {
479 $lb->waitForAll( $unsavedPositions[$masterName] );
485 * Base parameters to LoadBalancer::__construct()
488 final protected function baseLoadBalancerParams() {
490 'localDomain' => $this->localDomain
,
491 'readOnlyReason' => $this->readOnlyReason
,
492 'srvCache' => $this->srvCache
,
493 'wanCache' => $this->wanCache
,
494 'profiler' => $this->profiler
,
495 'trxProfiler' => $this->trxProfiler
,
496 'queryLogger' => $this->queryLogger
,
497 'connLogger' => $this->connLogger
,
498 'replLogger' => $this->replLogger
,
499 'errorLogger' => $this->errorLogger
,
500 'hostname' => $this->hostname
,
501 'cliMode' => $this->cliMode
,
502 'agent' => $this->agent
507 * @param ILoadBalancer $lb
509 protected function initLoadBalancer( ILoadBalancer
$lb ) {
510 if ( $this->trxRoundId
!== false ) {
511 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
515 public function setDomainPrefix( $prefix ) {
516 $this->localDomain
= new DatabaseDomain(
517 $this->localDomain
->getDatabase(),
522 $this->forEachLB( function( ILoadBalancer
$lb ) use ( $prefix ) {
523 $lb->setDomainPrefix( $prefix );
527 public function closeAll() {
528 $this->forEachLBCallMethod( 'closeAll', [] );
531 public function setAgentName( $agent ) {
532 $this->agent
= $agent;
535 public function appendPreShutdownTimeAsQuery( $url, $time ) {
537 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$usedCluster ) {
538 $usedCluster |
= ( $lb->getServerCount() > 1 );
541 if ( !$usedCluster ) {
542 return $url; // no master/replica clusters touched
545 return strpos( $url, '?' ) === false ?
"$url?cpPosTime=$time" : "$url&cpPosTime=$time";
548 public function setRequestInfo( array $info ) {
549 $this->requestInfo
= $info +
$this->requestInfo
;
553 * Make PHP ignore user aborts/disconnects until the returned
554 * value leaves scope. This returns null and does nothing in CLI mode.
556 * @return ScopedCallback|null
558 final protected function getScopedPHPBehaviorForCommit() {
559 if ( PHP_SAPI
!= 'cli' ) { // http://bugs.php.net/bug.php?id=47540
560 $old = ignore_user_abort( true ); // avoid half-finished operations
561 return new ScopedCallback( function () use ( $old ) {
562 ignore_user_abort( $old );
569 function __destruct() {