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
;
34 use DBTransactionError
;
35 use DBReplicationWaitError
;
38 * An interface for generating database load balancers
41 abstract class LBFactory
implements ILBFactory
{
42 /** @var ChronologyProtector */
44 /** @var object|string Class name or object With profileIn/profileOut methods */
46 /** @var TransactionProfiler */
47 protected $trxProfiler;
48 /** @var LoggerInterface */
49 protected $replLogger;
50 /** @var LoggerInterface */
51 protected $connLogger;
52 /** @var LoggerInterface */
53 protected $queryLogger;
54 /** @var LoggerInterface */
55 protected $perfLogger;
56 /** @var callable Error logger */
57 protected $errorLogger;
62 /** @var WANObjectCache */
65 /** @var DatabaseDomain Local domain */
66 protected $localDomain;
67 /** @var string Local hostname of the app server */
69 /** @var array Web request information about the client */
70 protected $requestInfo;
74 /** @var string|bool String if a requested DBO_TRX transaction round is active */
75 protected $trxRoundId = false;
76 /** @var string|bool Reason all LBs are read-only or false if not */
77 protected $readOnlyReason = false;
78 /** @var callable[] */
79 protected $replicationWaitCallbacks = [];
81 /** @var bool Whether this PHP instance is for a CLI script */
83 /** @var string Agent name for query profiling */
86 private static $loggerFields =
87 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
89 public function __construct( array $conf ) {
90 $this->localDomain
= isset( $conf['localDomain'] )
91 ? DatabaseDomain
::newFromId( $conf['localDomain'] )
92 : DatabaseDomain
::newUnspecified();
94 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
95 $this->readOnlyReason
= $conf['readOnlyReason'];
98 $this->srvCache
= isset( $conf['srvCache'] ) ?
$conf['srvCache'] : new EmptyBagOStuff();
99 $this->memCache
= isset( $conf['memCache'] ) ?
$conf['memCache'] : new EmptyBagOStuff();
100 $this->wanCache
= isset( $conf['wanCache'] )
102 : WANObjectCache
::newEmpty();
104 foreach ( self
::$loggerFields as $key ) {
105 $this->$key = isset( $conf[$key] ) ?
$conf[$key] : new \Psr\Log\
NullLogger();
107 $this->errorLogger
= isset( $conf['errorLogger'] )
108 ?
$conf['errorLogger']
109 : function ( Exception
$e ) {
110 trigger_error( E_USER_WARNING
, get_class( $e ) . ': ' . $e->getMessage() );
113 $this->profiler
= isset( $conf['profiler'] ) ?
$conf['profiler'] : null;
114 $this->trxProfiler
= isset( $conf['trxProfiler'] )
115 ?
$conf['trxProfiler']
116 : new TransactionProfiler();
118 $this->requestInfo
= [
119 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ?
$_SERVER[ 'REMOTE_ADDR' ] : '',
120 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ?
$_SERVER['HTTP_USER_AGENT'] : '',
121 'ChronologyProtection' => 'true'
124 $this->cliMode
= isset( $conf['cliMode'] ) ?
$conf['cliMode'] : PHP_SAPI
=== 'cli';
125 $this->hostname
= isset( $conf['hostname'] ) ?
$conf['hostname'] : gethostname();
126 $this->agent
= isset( $conf['agent'] ) ?
$conf['agent'] : '';
128 $this->ticket
= mt_rand();
131 public function destroy() {
132 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
133 $this->forEachLBCallMethod( 'disable' );
136 public function shutdown(
137 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null
139 $chronProt = $this->getChronologyProtector();
140 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
141 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync' );
142 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
143 $this->shutdownChronologyProtector( $chronProt, null, 'async' );
146 $this->commitMasterChanges( __METHOD__
); // sanity
150 * @see ILBFactory::newMainLB()
151 * @param bool $domain
152 * @return LoadBalancer
154 abstract public function newMainLB( $domain = false );
157 * @see ILBFactory::getMainLB()
158 * @param bool $domain
159 * @return LoadBalancer
161 abstract public function getMainLB( $domain = false );
164 * @see ILBFactory::newExternalLB()
165 * @param string $cluster
166 * @return LoadBalancer
168 abstract public function newExternalLB( $cluster );
171 * @see ILBFactory::getExternalLB()
172 * @param string $cluster
173 * @return LoadBalancer
175 abstract public function getExternalLB( $cluster );
178 * Call a method of each tracked load balancer
180 * @param string $methodName
183 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
185 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
186 call_user_func_array( [ $loadBalancer, $methodName ], $args );
188 [ $methodName, $args ]
192 public function flushReplicaSnapshots( $fname = __METHOD__
) {
193 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
196 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
197 $this->commitMasterChanges( $fname, $options );
198 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
201 public function beginMasterChanges( $fname = __METHOD__
) {
202 if ( $this->trxRoundId
!== false ) {
203 throw new DBTransactionError(
205 "$fname: transaction round '{$this->trxRoundId}' already started."
208 $this->trxRoundId
= $fname;
209 // Set DBO_TRX flags on all appropriate DBs
210 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
213 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
214 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
215 throw new DBTransactionError(
217 "$fname: transaction round '{$this->trxRoundId}' still running."
220 /** @noinspection PhpUnusedLocalVariableInspection */
221 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
222 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
223 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
224 $this->trxRoundId
= false;
225 // Perform pre-commit checks, aborting on failure
226 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
227 // Log the DBs and methods involved in multi-DB transactions
228 $this->logIfMultiDbTransaction();
229 // Actually perform the commit on all master DB connections and revert DBO_TRX
230 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
231 // Run all post-commit callbacks
232 /** @var Exception $e */
233 $e = null; // first callback exception
234 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
235 $ex = $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_COMMIT
);
238 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
239 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
240 // Throw any last post-commit callback error
241 if ( $e instanceof Exception
) {
246 public function rollbackMasterChanges( $fname = __METHOD__
) {
247 $this->trxRoundId
= false;
248 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
249 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
250 // Run all post-rollback callbacks
251 $this->forEachLB( function ( ILoadBalancer
$lb ) {
252 $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_ROLLBACK
);
257 * Log query info if multi DB transactions are going to be committed now
259 private function logIfMultiDbTransaction() {
261 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
262 $masterName = $lb->getServerName( $lb->getWriterIndex() );
263 $callers = $lb->pendingMasterChangeCallers();
265 $callersByDB[$masterName] = $callers;
269 if ( count( $callersByDB ) >= 2 ) {
270 $dbs = implode( ', ', array_keys( $callersByDB ) );
271 $msg = "Multi-DB transaction [{$dbs}]:\n";
272 foreach ( $callersByDB as $db => $callers ) {
273 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
275 $this->queryLogger
->info( $msg );
279 public function hasMasterChanges() {
281 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
282 $ret = $ret ||
$lb->hasMasterChanges();
288 public function laggedReplicaUsed() {
290 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
291 $ret = $ret ||
$lb->laggedReplicaUsed();
297 public function hasOrMadeRecentMasterChanges( $age = null ) {
299 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
300 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
305 public function waitForReplication( array $opts = [] ) {
310 'ifWritesSince' => null
313 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
314 $opts['domain'] = $opts['wiki']; // b/c
317 // Figure out which clusters need to be checked
318 /** @var ILoadBalancer[] $lbs */
320 if ( $opts['cluster'] !== false ) {
321 $lbs[] = $this->getExternalLB( $opts['cluster'] );
322 } elseif ( $opts['domain'] !== false ) {
323 $lbs[] = $this->getMainLB( $opts['domain'] );
325 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
329 return; // nothing actually used
333 // Get all the master positions of applicable DBs right now.
334 // This can be faster since waiting on one cluster reduces the
335 // time needed to wait on the next clusters.
336 $masterPositions = array_fill( 0, count( $lbs ), false );
337 foreach ( $lbs as $i => $lb ) {
338 if ( $lb->getServerCount() <= 1 ) {
339 // T29975 - Don't try to wait for replica DBs if there are none
340 // Prevents permission error when getting master position
342 } elseif ( $opts['ifWritesSince']
343 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
345 continue; // no writes since the last wait
347 $masterPositions[$i] = $lb->getMasterPos();
350 // Run any listener callbacks *after* getting the DB positions. The more
351 // time spent in the callbacks, the less time is spent in waitForAll().
352 foreach ( $this->replicationWaitCallbacks
as $callback ) {
357 foreach ( $lbs as $i => $lb ) {
358 if ( $masterPositions[$i] ) {
359 // The DBMS may not support getMasterPos()
360 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
361 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
367 throw new DBReplicationWaitError(
369 "Could not wait for replica DBs to catch up to " .
370 implode( ', ', $failed )
375 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
377 $this->replicationWaitCallbacks
[$name] = $callback;
379 unset( $this->replicationWaitCallbacks
[$name] );
383 public function getEmptyTransactionTicket( $fname ) {
384 if ( $this->hasMasterChanges() ) {
385 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
386 ( new RuntimeException() )->getTraceAsString() );
391 return $this->ticket
;
394 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
395 if ( $ticket !== $this->ticket
) {
396 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
397 ( new RuntimeException() )->getTraceAsString() );
402 // The transaction owner and any caller with the empty transaction ticket can commit
403 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
404 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
405 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
406 $fnameEffective = $this->trxRoundId
;
408 $fnameEffective = $fname;
411 $this->commitMasterChanges( $fnameEffective );
412 $this->waitForReplication( $opts );
413 // If a nested caller committed on behalf of $fname, start another empty $fname
414 // transaction, leaving the caller with the same empty transaction state as before.
415 if ( $fnameEffective !== $fname ) {
416 $this->beginMasterChanges( $fnameEffective );
420 public function getChronologyProtectorTouched( $dbName ) {
421 return $this->getChronologyProtector()->getTouched( $dbName );
424 public function disableChronologyProtection() {
425 $this->getChronologyProtector()->setEnabled( false );
429 * @return ChronologyProtector
431 protected function getChronologyProtector() {
432 if ( $this->chronProt
) {
433 return $this->chronProt
;
436 $this->chronProt
= new ChronologyProtector(
439 'ip' => $this->requestInfo
['IPAddress'],
440 'agent' => $this->requestInfo
['UserAgent'],
442 isset( $_GET['cpPosTime'] ) ?
$_GET['cpPosTime'] : null
444 $this->chronProt
->setLogger( $this->replLogger
);
446 if ( $this->cliMode
) {
447 $this->chronProt
->setEnabled( false );
448 } elseif ( $this->requestInfo
['ChronologyProtection'] === 'false' ) {
449 // Request opted out of using position wait logic. This is useful for requests
450 // done by the job queue or background ETL that do not have a meaningful session.
451 $this->chronProt
->setWaitEnabled( false );
454 $this->replLogger
->debug( __METHOD__
. ': using request info ' .
455 json_encode( $this->requestInfo
, JSON_PRETTY_PRINT
) );
457 return $this->chronProt
;
461 * Get and record all of the staged DB positions into persistent memory storage
463 * @param ChronologyProtector $cp
464 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
465 * @param string $mode One of (sync, async); whether to wait on remote datacenters
467 protected function shutdownChronologyProtector(
468 ChronologyProtector
$cp, $workCallback, $mode
470 // Record all the master positions needed
471 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
472 $cp->shutdownLB( $lb );
474 // Write them to the persistent stash. Try to do something useful by running $work
475 // while ChronologyProtector waits for the stash write to replicate to all DCs.
476 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
477 if ( $unsavedPositions && $workCallback ) {
478 // Invoke callback in case it did not cache the result yet
479 $workCallback(); // work now to block for less time in waitForAll()
481 // If the positions failed to write to the stash, at least wait on local datacenter
482 // replica DBs to catch up before responding. Even if there are several DCs, this increases
483 // the chance that the user will see their own changes immediately afterwards. As long
484 // as the sticky DC cookie applies (same domain), this is not even an issue.
485 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
486 $masterName = $lb->getServerName( $lb->getWriterIndex() );
487 if ( isset( $unsavedPositions[$masterName] ) ) {
488 $lb->waitForAll( $unsavedPositions[$masterName] );
494 * Base parameters to LoadBalancer::__construct()
497 final protected function baseLoadBalancerParams() {
499 'localDomain' => $this->localDomain
,
500 'readOnlyReason' => $this->readOnlyReason
,
501 'srvCache' => $this->srvCache
,
502 'wanCache' => $this->wanCache
,
503 'profiler' => $this->profiler
,
504 'trxProfiler' => $this->trxProfiler
,
505 'queryLogger' => $this->queryLogger
,
506 'connLogger' => $this->connLogger
,
507 'replLogger' => $this->replLogger
,
508 'errorLogger' => $this->errorLogger
,
509 'hostname' => $this->hostname
,
510 'cliMode' => $this->cliMode
,
511 'agent' => $this->agent
516 * @param ILoadBalancer $lb
518 protected function initLoadBalancer( ILoadBalancer
$lb ) {
519 if ( $this->trxRoundId
!== false ) {
520 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
524 public function setDomainPrefix( $prefix ) {
525 $this->localDomain
= new DatabaseDomain(
526 $this->localDomain
->getDatabase(),
531 $this->forEachLB( function( ILoadBalancer
$lb ) use ( $prefix ) {
532 $lb->setDomainPrefix( $prefix );
536 public function closeAll() {
537 $this->forEachLBCallMethod( 'closeAll', [] );
540 public function setAgentName( $agent ) {
541 $this->agent
= $agent;
544 public function appendPreShutdownTimeAsQuery( $url, $time ) {
546 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$usedCluster ) {
547 $usedCluster |
= ( $lb->getServerCount() > 1 );
550 if ( !$usedCluster ) {
551 return $url; // no master/replica clusters touched
554 return strpos( $url, '?' ) === false ?
"$url?cpPosTime=$time" : "$url&cpPosTime=$time";
557 public function setRequestInfo( array $info ) {
558 $this->requestInfo
= $info +
$this->requestInfo
;
562 * Make PHP ignore user aborts/disconnects until the returned
563 * value leaves scope. This returns null and does nothing in CLI mode.
565 * @return ScopedCallback|null
567 final protected function getScopedPHPBehaviorForCommit() {
568 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
569 $old = ignore_user_abort( true ); // avoid half-finished operations
570 return new ScopedCallback( function () use ( $old ) {
571 ignore_user_abort( $old );
578 function __destruct() {