b2bd7ca727ee8d6a047cfb846760f144763a7188
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 use DBTransactionError
;
36 use DBReplicationWaitError
;
39 * An interface for generating database load balancers
42 abstract class LBFactory
implements ILBFactory
{
43 /** @var ChronologyProtector */
45 /** @var object|string Class name or object With profileIn/profileOut methods */
47 /** @var TransactionProfiler */
48 protected $trxProfiler;
49 /** @var LoggerInterface */
50 protected $replLogger;
51 /** @var LoggerInterface */
52 protected $connLogger;
53 /** @var LoggerInterface */
54 protected $queryLogger;
55 /** @var LoggerInterface */
56 protected $perfLogger;
57 /** @var callable Error logger */
58 protected $errorLogger;
63 /** @var WANObjectCache */
66 /** @var DatabaseDomain Local domain */
67 protected $localDomain;
68 /** @var string Local hostname of the app server */
70 /** @var array Web request information about the client */
71 protected $requestInfo;
75 /** @var string|bool String if a requested DBO_TRX transaction round is active */
76 protected $trxRoundId = false;
77 /** @var string|bool Reason all LBs are read-only or false if not */
78 protected $readOnlyReason = false;
79 /** @var callable[] */
80 protected $replicationWaitCallbacks = [];
82 /** @var bool Whether this PHP instance is for a CLI script */
84 /** @var string Agent name for query profiling */
87 private static $loggerFields =
88 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
90 public function __construct( array $conf ) {
91 $this->localDomain
= isset( $conf['localDomain'] )
92 ? DatabaseDomain
::newFromId( $conf['localDomain'] )
93 : DatabaseDomain
::newUnspecified();
95 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
96 $this->readOnlyReason
= $conf['readOnlyReason'];
99 $this->srvCache
= isset( $conf['srvCache'] ) ?
$conf['srvCache'] : new EmptyBagOStuff();
100 $this->memCache
= isset( $conf['memCache'] ) ?
$conf['memCache'] : new EmptyBagOStuff();
101 $this->wanCache
= isset( $conf['wanCache'] )
103 : WANObjectCache
::newEmpty();
105 foreach ( self
::$loggerFields as $key ) {
106 $this->$key = isset( $conf[$key] ) ?
$conf[$key] : new \Psr\Log\
NullLogger();
108 $this->errorLogger
= isset( $conf['errorLogger'] )
109 ?
$conf['errorLogger']
110 : function ( Exception
$e ) {
111 trigger_error( E_USER_WARNING
, get_class( $e ) . ': ' . $e->getMessage() );
114 $this->profiler
= isset( $conf['profiler'] ) ?
$conf['profiler'] : null;
115 $this->trxProfiler
= isset( $conf['trxProfiler'] )
116 ?
$conf['trxProfiler']
117 : new TransactionProfiler();
119 $this->requestInfo
= [
120 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ?
$_SERVER[ 'REMOTE_ADDR' ] : '',
121 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ?
$_SERVER['HTTP_USER_AGENT'] : '',
122 'ChronologyProtection' => 'true'
125 $this->cliMode
= isset( $conf['cliMode'] ) ?
$conf['cliMode'] : PHP_SAPI
=== 'cli';
126 $this->hostname
= isset( $conf['hostname'] ) ?
$conf['hostname'] : gethostname();
127 $this->agent
= isset( $conf['agent'] ) ?
$conf['agent'] : '';
129 $this->ticket
= mt_rand();
132 public function destroy() {
133 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
134 $this->forEachLBCallMethod( 'disable' );
137 public function shutdown(
138 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null
140 $chronProt = $this->getChronologyProtector();
141 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
142 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync' );
143 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
144 $this->shutdownChronologyProtector( $chronProt, null, 'async' );
147 $this->commitMasterChanges( __METHOD__
); // sanity
151 * @see ILBFactory::newMainLB()
152 * @param bool $domain
153 * @return LoadBalancer
155 abstract public function newMainLB( $domain = false );
158 * @see ILBFactory::getMainLB()
159 * @param bool $domain
160 * @return LoadBalancer
162 abstract public function getMainLB( $domain = false );
165 * @see ILBFactory::newExternalLB()
166 * @param string $cluster
167 * @return LoadBalancer
169 abstract public function newExternalLB( $cluster );
172 * @see ILBFactory::getExternalLB()
173 * @param string $cluster
174 * @return LoadBalancer
176 abstract public function getExternalLB( $cluster );
179 * Call a method of each tracked load balancer
181 * @param string $methodName
184 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
186 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
187 call_user_func_array( [ $loadBalancer, $methodName ], $args );
189 [ $methodName, $args ]
193 public function flushReplicaSnapshots( $fname = __METHOD__
) {
194 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
197 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
198 $this->commitMasterChanges( $fname, $options );
199 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
202 public function beginMasterChanges( $fname = __METHOD__
) {
203 if ( $this->trxRoundId
!== false ) {
204 throw new DBTransactionError(
206 "$fname: transaction round '{$this->trxRoundId}' already started."
209 $this->trxRoundId
= $fname;
210 // Set DBO_TRX flags on all appropriate DBs
211 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
214 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
215 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
216 throw new DBTransactionError(
218 "$fname: transaction round '{$this->trxRoundId}' still running."
221 /** @noinspection PhpUnusedLocalVariableInspection */
222 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
223 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
224 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
225 $this->trxRoundId
= false;
226 // Perform pre-commit checks, aborting on failure
227 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
228 // Log the DBs and methods involved in multi-DB transactions
229 $this->logIfMultiDbTransaction();
230 // Actually perform the commit on all master DB connections and revert DBO_TRX
231 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
232 // Run all post-commit callbacks
233 /** @var Exception $e */
234 $e = null; // first callback exception
235 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
236 $ex = $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_COMMIT
);
239 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
240 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
241 // Throw any last post-commit callback error
242 if ( $e instanceof Exception
) {
247 public function rollbackMasterChanges( $fname = __METHOD__
) {
248 $this->trxRoundId
= false;
249 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
250 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
251 // Run all post-rollback callbacks
252 $this->forEachLB( function ( ILoadBalancer
$lb ) {
253 $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_ROLLBACK
);
258 * Log query info if multi DB transactions are going to be committed now
260 private function logIfMultiDbTransaction() {
262 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
263 $masterName = $lb->getServerName( $lb->getWriterIndex() );
264 $callers = $lb->pendingMasterChangeCallers();
266 $callersByDB[$masterName] = $callers;
270 if ( count( $callersByDB ) >= 2 ) {
271 $dbs = implode( ', ', array_keys( $callersByDB ) );
272 $msg = "Multi-DB transaction [{$dbs}]:\n";
273 foreach ( $callersByDB as $db => $callers ) {
274 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
276 $this->queryLogger
->info( $msg );
280 public function hasMasterChanges() {
282 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
283 $ret = $ret ||
$lb->hasMasterChanges();
289 public function laggedReplicaUsed() {
291 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
292 $ret = $ret ||
$lb->laggedReplicaUsed();
298 public function hasOrMadeRecentMasterChanges( $age = null ) {
300 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
301 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
306 public function waitForReplication( array $opts = [] ) {
311 'ifWritesSince' => null
314 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
315 $opts['domain'] = $opts['wiki']; // b/c
318 // Figure out which clusters need to be checked
319 /** @var ILoadBalancer[] $lbs */
321 if ( $opts['cluster'] !== false ) {
322 $lbs[] = $this->getExternalLB( $opts['cluster'] );
323 } elseif ( $opts['domain'] !== false ) {
324 $lbs[] = $this->getMainLB( $opts['domain'] );
326 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
330 return; // nothing actually used
334 // Get all the master positions of applicable DBs right now.
335 // This can be faster since waiting on one cluster reduces the
336 // time needed to wait on the next clusters.
337 $masterPositions = array_fill( 0, count( $lbs ), false );
338 foreach ( $lbs as $i => $lb ) {
339 if ( $lb->getServerCount() <= 1 ) {
340 // Bug 27975 - Don't try to wait for replica DBs if there are none
341 // Prevents permission error when getting master position
343 } elseif ( $opts['ifWritesSince']
344 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
346 continue; // no writes since the last wait
348 $masterPositions[$i] = $lb->getMasterPos();
351 // Run any listener callbacks *after* getting the DB positions. The more
352 // time spent in the callbacks, the less time is spent in waitForAll().
353 foreach ( $this->replicationWaitCallbacks
as $callback ) {
358 foreach ( $lbs as $i => $lb ) {
359 if ( $masterPositions[$i] ) {
360 // The DBMS may not support getMasterPos()
361 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
362 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
368 throw new DBReplicationWaitError(
370 "Could not wait for replica DBs to catch up to " .
371 implode( ', ', $failed )
376 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
378 $this->replicationWaitCallbacks
[$name] = $callback;
380 unset( $this->replicationWaitCallbacks
[$name] );
384 public function getEmptyTransactionTicket( $fname ) {
385 if ( $this->hasMasterChanges() ) {
386 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
387 ( new RuntimeException() )->getTraceAsString() );
392 return $this->ticket
;
395 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
396 if ( $ticket !== $this->ticket
) {
397 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
398 ( new RuntimeException() )->getTraceAsString() );
403 // The transaction owner and any caller with the empty transaction ticket can commit
404 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
405 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
406 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
407 $fnameEffective = $this->trxRoundId
;
409 $fnameEffective = $fname;
412 $this->commitMasterChanges( $fnameEffective );
413 $this->waitForReplication( $opts );
414 // If a nested caller committed on behalf of $fname, start another empty $fname
415 // transaction, leaving the caller with the same empty transaction state as before.
416 if ( $fnameEffective !== $fname ) {
417 $this->beginMasterChanges( $fnameEffective );
421 public function getChronologyProtectorTouched( $dbName ) {
422 return $this->getChronologyProtector()->getTouched( $dbName );
425 public function disableChronologyProtection() {
426 $this->getChronologyProtector()->setEnabled( false );
430 * @return ChronologyProtector
432 protected function getChronologyProtector() {
433 if ( $this->chronProt
) {
434 return $this->chronProt
;
437 $this->chronProt
= new ChronologyProtector(
440 'ip' => $this->requestInfo
['IPAddress'],
441 'agent' => $this->requestInfo
['UserAgent'],
443 isset( $_GET['cpPosTime'] ) ?
$_GET['cpPosTime'] : null
445 $this->chronProt
->setLogger( $this->replLogger
);
447 if ( $this->cliMode
) {
448 $this->chronProt
->setEnabled( false );
449 } elseif ( $this->requestInfo
['ChronologyProtection'] === 'false' ) {
450 // Request opted out of using position wait logic. This is useful for requests
451 // done by the job queue or background ETL that do not have a meaningful session.
452 $this->chronProt
->setWaitEnabled( false );
455 $this->replLogger
->debug( __METHOD__
. ': using request info ' .
456 json_encode( $this->requestInfo
, JSON_PRETTY_PRINT
) );
458 return $this->chronProt
;
462 * Get and record all of the staged DB positions into persistent memory storage
464 * @param ChronologyProtector $cp
465 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
466 * @param string $mode One of (sync, async); whether to wait on remote datacenters
468 protected function shutdownChronologyProtector(
469 ChronologyProtector
$cp, $workCallback, $mode
471 // Record all the master positions needed
472 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
473 $cp->shutdownLB( $lb );
475 // Write them to the persistent stash. Try to do something useful by running $work
476 // while ChronologyProtector waits for the stash write to replicate to all DCs.
477 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
478 if ( $unsavedPositions && $workCallback ) {
479 // Invoke callback in case it did not cache the result yet
480 $workCallback(); // work now to block for less time in waitForAll()
482 // If the positions failed to write to the stash, at least wait on local datacenter
483 // replica DBs to catch up before responding. Even if there are several DCs, this increases
484 // the chance that the user will see their own changes immediately afterwards. As long
485 // as the sticky DC cookie applies (same domain), this is not even an issue.
486 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
487 $masterName = $lb->getServerName( $lb->getWriterIndex() );
488 if ( isset( $unsavedPositions[$masterName] ) ) {
489 $lb->waitForAll( $unsavedPositions[$masterName] );
495 * Base parameters to LoadBalancer::__construct()
498 final protected function baseLoadBalancerParams() {
500 'localDomain' => $this->localDomain
,
501 'readOnlyReason' => $this->readOnlyReason
,
502 'srvCache' => $this->srvCache
,
503 'wanCache' => $this->wanCache
,
504 'profiler' => $this->profiler
,
505 'trxProfiler' => $this->trxProfiler
,
506 'queryLogger' => $this->queryLogger
,
507 'connLogger' => $this->connLogger
,
508 'replLogger' => $this->replLogger
,
509 'errorLogger' => $this->errorLogger
,
510 'hostname' => $this->hostname
,
511 'cliMode' => $this->cliMode
,
512 'agent' => $this->agent
517 * @param ILoadBalancer $lb
519 protected function initLoadBalancer( ILoadBalancer
$lb ) {
520 if ( $this->trxRoundId
!== false ) {
521 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
525 public function setDomainPrefix( $prefix ) {
526 $this->localDomain
= new DatabaseDomain(
527 $this->localDomain
->getDatabase(),
532 $this->forEachLB( function( ILoadBalancer
$lb ) use ( $prefix ) {
533 $lb->setDomainPrefix( $prefix );
537 public function closeAll() {
538 $this->forEachLBCallMethod( 'closeAll', [] );
541 public function setAgentName( $agent ) {
542 $this->agent
= $agent;
545 public function appendPreShutdownTimeAsQuery( $url, $time ) {
547 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$usedCluster ) {
548 $usedCluster |
= ( $lb->getServerCount() > 1 );
551 if ( !$usedCluster ) {
552 return $url; // no master/replica clusters touched
555 return strpos( $url, '?' ) === false ?
"$url?cpPosTime=$time" : "$url&cpPosTime=$time";
558 public function setRequestInfo( array $info ) {
559 $this->requestInfo
= $info +
$this->requestInfo
;
563 * Make PHP ignore user aborts/disconnects until the returned
564 * value leaves scope. This returns null and does nothing in CLI mode.
566 * @return ScopedCallback|null
568 final protected function getScopedPHPBehaviorForCommit() {
569 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
570 $old = ignore_user_abort( true ); // avoid half-finished operations
571 return new ScopedCallback( function () use ( $old ) {
572 ignore_user_abort( $old );
579 function __destruct() {