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
;
37 use DBTransactionError
;
38 use DBReplicationWaitError
;
41 * An interface for generating database load balancers
44 abstract class LBFactory
implements ILBFactory
{
45 /** @var ChronologyProtector */
47 /** @var object|string Class name or object With profileIn/profileOut methods */
49 /** @var TransactionProfiler */
50 protected $trxProfiler;
51 /** @var LoggerInterface */
52 protected $replLogger;
53 /** @var LoggerInterface */
54 protected $connLogger;
55 /** @var LoggerInterface */
56 protected $queryLogger;
57 /** @var LoggerInterface */
58 protected $perfLogger;
59 /** @var callable Error logger */
60 protected $errorLogger;
65 /** @var WANObjectCache */
68 /** @var DatabaseDomain Local domain */
69 protected $localDomain;
70 /** @var string Local hostname of the app server */
72 /** @var array Web request information about the client */
73 protected $requestInfo;
77 /** @var string|bool String if a requested DBO_TRX transaction round is active */
78 protected $trxRoundId = false;
79 /** @var string|bool Reason all LBs are read-only or false if not */
80 protected $readOnlyReason = false;
81 /** @var callable[] */
82 protected $replicationWaitCallbacks = [];
84 /** @var bool Whether this PHP instance is for a CLI script */
86 /** @var string Agent name for query profiling */
89 private static $loggerFields =
90 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
92 public function __construct( array $conf ) {
93 $this->localDomain
= isset( $conf['localDomain'] )
94 ? DatabaseDomain
::newFromId( $conf['localDomain'] )
95 : DatabaseDomain
::newUnspecified();
97 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
98 $this->readOnlyReason
= $conf['readOnlyReason'];
101 $this->srvCache
= isset( $conf['srvCache'] ) ?
$conf['srvCache'] : new EmptyBagOStuff();
102 $this->memCache
= isset( $conf['memCache'] ) ?
$conf['memCache'] : new EmptyBagOStuff();
103 $this->wanCache
= isset( $conf['wanCache'] )
105 : WANObjectCache
::newEmpty();
107 foreach ( self
::$loggerFields as $key ) {
108 $this->$key = isset( $conf[$key] ) ?
$conf[$key] : new \Psr\Log\
NullLogger();
110 $this->errorLogger
= isset( $conf['errorLogger'] )
111 ?
$conf['errorLogger']
112 : function ( Exception
$e ) {
113 trigger_error( E_USER_WARNING
, get_class( $e ) . ': ' . $e->getMessage() );
116 $this->profiler
= isset( $conf['profiler'] ) ?
$conf['profiler'] : null;
117 $this->trxProfiler
= isset( $conf['trxProfiler'] )
118 ?
$conf['trxProfiler']
119 : new TransactionProfiler();
121 $this->requestInfo
= [
122 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ?
$_SERVER[ 'REMOTE_ADDR' ] : '',
123 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ?
$_SERVER['HTTP_USER_AGENT'] : '',
124 'ChronologyProtection' => 'true'
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
142 $chronProt = $this->getChronologyProtector();
143 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
144 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync' );
145 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
146 $this->shutdownChronologyProtector( $chronProt, null, 'async' );
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
);
260 * Log query info if multi DB transactions are going to be committed now
262 private function logIfMultiDbTransaction() {
264 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
265 $masterName = $lb->getServerName( $lb->getWriterIndex() );
266 $callers = $lb->pendingMasterChangeCallers();
268 $callersByDB[$masterName] = $callers;
272 if ( count( $callersByDB ) >= 2 ) {
273 $dbs = implode( ', ', array_keys( $callersByDB ) );
274 $msg = "Multi-DB transaction [{$dbs}]:\n";
275 foreach ( $callersByDB as $db => $callers ) {
276 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
278 $this->queryLogger
->info( $msg );
282 public function hasMasterChanges() {
284 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
285 $ret = $ret ||
$lb->hasMasterChanges();
291 public function laggedReplicaUsed() {
293 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
294 $ret = $ret ||
$lb->laggedReplicaUsed();
300 public function hasOrMadeRecentMasterChanges( $age = null ) {
302 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
303 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
308 public function waitForReplication( array $opts = [] ) {
313 'ifWritesSince' => null
316 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
317 $opts['domain'] = $opts['wiki']; // b/c
320 // Figure out which clusters need to be checked
321 /** @var ILoadBalancer[] $lbs */
323 if ( $opts['cluster'] !== false ) {
324 $lbs[] = $this->getExternalLB( $opts['cluster'] );
325 } elseif ( $opts['domain'] !== false ) {
326 $lbs[] = $this->getMainLB( $opts['domain'] );
328 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
332 return; // nothing actually used
336 // Get all the master positions of applicable DBs right now.
337 // This can be faster since waiting on one cluster reduces the
338 // time needed to wait on the next clusters.
339 $masterPositions = array_fill( 0, count( $lbs ), false );
340 foreach ( $lbs as $i => $lb ) {
341 if ( $lb->getServerCount() <= 1 ) {
342 // Bug 27975 - Don't try to wait for replica DBs if there are none
343 // Prevents permission error when getting master position
345 } elseif ( $opts['ifWritesSince']
346 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
348 continue; // no writes since the last wait
350 $masterPositions[$i] = $lb->getMasterPos();
353 // Run any listener callbacks *after* getting the DB positions. The more
354 // time spent in the callbacks, the less time is spent in waitForAll().
355 foreach ( $this->replicationWaitCallbacks
as $callback ) {
360 foreach ( $lbs as $i => $lb ) {
361 if ( $masterPositions[$i] ) {
362 // The DBMS may not support getMasterPos()
363 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
364 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
370 throw new DBReplicationWaitError(
372 "Could not wait for replica DBs to catch up to " .
373 implode( ', ', $failed )
378 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
380 $this->replicationWaitCallbacks
[$name] = $callback;
382 unset( $this->replicationWaitCallbacks
[$name] );
386 public function getEmptyTransactionTicket( $fname ) {
387 if ( $this->hasMasterChanges() ) {
388 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
389 ( new RuntimeException() )->getTraceAsString() );
394 return $this->ticket
;
397 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
398 if ( $ticket !== $this->ticket
) {
399 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
400 ( new RuntimeException() )->getTraceAsString() );
405 // The transaction owner and any caller with the empty transaction ticket can commit
406 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
407 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
408 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
409 $fnameEffective = $this->trxRoundId
;
411 $fnameEffective = $fname;
414 $this->commitMasterChanges( $fnameEffective );
415 $this->waitForReplication( $opts );
416 // If a nested caller committed on behalf of $fname, start another empty $fname
417 // transaction, leaving the caller with the same empty transaction state as before.
418 if ( $fnameEffective !== $fname ) {
419 $this->beginMasterChanges( $fnameEffective );
423 public function getChronologyProtectorTouched( $dbName ) {
424 return $this->getChronologyProtector()->getTouched( $dbName );
427 public function disableChronologyProtection() {
428 $this->getChronologyProtector()->setEnabled( false );
432 * @return ChronologyProtector
434 protected function getChronologyProtector() {
435 if ( $this->chronProt
) {
436 return $this->chronProt
;
439 $this->chronProt
= new ChronologyProtector(
442 'ip' => $this->requestInfo
['IPAddress'],
443 'agent' => $this->requestInfo
['UserAgent'],
445 isset( $_GET['cpPosTime'] ) ?
$_GET['cpPosTime'] : null
447 $this->chronProt
->setLogger( $this->replLogger
);
449 if ( $this->cliMode
) {
450 $this->chronProt
->setEnabled( false );
451 } elseif ( $this->requestInfo
['ChronologyProtection'] === 'false' ) {
452 // Request opted out of using position wait logic. This is useful for requests
453 // done by the job queue or background ETL that do not have a meaningful session.
454 $this->chronProt
->setWaitEnabled( false );
457 $this->replLogger
->debug( __METHOD__
. ': using request info ' .
458 json_encode( $this->requestInfo
, JSON_PRETTY_PRINT
) );
460 return $this->chronProt
;
464 * Get and record all of the staged DB positions into persistent memory storage
466 * @param ChronologyProtector $cp
467 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
468 * @param string $mode One of (sync, async); whether to wait on remote datacenters
470 protected function shutdownChronologyProtector(
471 ChronologyProtector
$cp, $workCallback, $mode
473 // Record all the master positions needed
474 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
475 $cp->shutdownLB( $lb );
477 // Write them to the persistent stash. Try to do something useful by running $work
478 // while ChronologyProtector waits for the stash write to replicate to all DCs.
479 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
480 if ( $unsavedPositions && $workCallback ) {
481 // Invoke callback in case it did not cache the result yet
482 $workCallback(); // work now to block for less time in waitForAll()
484 // If the positions failed to write to the stash, at least wait on local datacenter
485 // replica DBs to catch up before responding. Even if there are several DCs, this increases
486 // the chance that the user will see their own changes immediately afterwards. As long
487 // as the sticky DC cookie applies (same domain), this is not even an issue.
488 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
489 $masterName = $lb->getServerName( $lb->getWriterIndex() );
490 if ( isset( $unsavedPositions[$masterName] ) ) {
491 $lb->waitForAll( $unsavedPositions[$masterName] );
497 * Base parameters to LoadBalancer::__construct()
500 final protected function baseLoadBalancerParams() {
502 'localDomain' => $this->localDomain
,
503 'readOnlyReason' => $this->readOnlyReason
,
504 'srvCache' => $this->srvCache
,
505 'wanCache' => $this->wanCache
,
506 'profiler' => $this->profiler
,
507 'trxProfiler' => $this->trxProfiler
,
508 'queryLogger' => $this->queryLogger
,
509 'connLogger' => $this->connLogger
,
510 'replLogger' => $this->replLogger
,
511 'errorLogger' => $this->errorLogger
,
512 'hostname' => $this->hostname
,
513 'cliMode' => $this->cliMode
,
514 'agent' => $this->agent
519 * @param ILoadBalancer $lb
521 protected function initLoadBalancer( ILoadBalancer
$lb ) {
522 if ( $this->trxRoundId
!== false ) {
523 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
527 public function setDomainPrefix( $prefix ) {
528 $this->localDomain
= new DatabaseDomain(
529 $this->localDomain
->getDatabase(),
534 $this->forEachLB( function( ILoadBalancer
$lb ) use ( $prefix ) {
535 $lb->setDomainPrefix( $prefix );
539 public function closeAll() {
540 $this->forEachLBCallMethod( 'closeAll', [] );
543 public function setAgentName( $agent ) {
544 $this->agent
= $agent;
547 public function appendPreShutdownTimeAsQuery( $url, $time ) {
549 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$usedCluster ) {
550 $usedCluster |
= ( $lb->getServerCount() > 1 );
553 if ( !$usedCluster ) {
554 return $url; // no master/replica clusters touched
557 return strpos( $url, '?' ) === false ?
"$url?cpPosTime=$time" : "$url&cpPosTime=$time";
560 public function setRequestInfo( array $info ) {
561 $this->requestInfo
= $info +
$this->requestInfo
;
565 * Make PHP ignore user aborts/disconnects until the returned
566 * value leaves scope. This returns null and does nothing in CLI mode.
568 * @return ScopedCallback|null
570 final protected function getScopedPHPBehaviorForCommit() {
571 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
572 $old = ignore_user_abort( true ); // avoid half-finished operations
573 return new ScopedCallback( function () use ( $old ) {
574 ignore_user_abort( $old );
581 function __destruct() {