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
;
26 use Wikimedia\Rdbms\TransactionProfiler
;
27 use Wikimedia\Rdbms\ChronologyProtector
;
30 * An interface for generating database load balancers
33 abstract class LBFactory
implements ILBFactory
{
34 /** @var ChronologyProtector */
36 /** @var object|string Class name or object With profileIn/profileOut methods */
38 /** @var TransactionProfiler */
39 protected $trxProfiler;
40 /** @var LoggerInterface */
41 protected $replLogger;
42 /** @var LoggerInterface */
43 protected $connLogger;
44 /** @var LoggerInterface */
45 protected $queryLogger;
46 /** @var LoggerInterface */
47 protected $perfLogger;
48 /** @var callable Error logger */
49 protected $errorLogger;
54 /** @var WANObjectCache */
57 /** @var DatabaseDomain Local domain */
58 protected $localDomain;
59 /** @var string Local hostname of the app server */
61 /** @var array Web request information about the client */
62 protected $requestInfo;
66 /** @var string|bool String if a requested DBO_TRX transaction round is active */
67 protected $trxRoundId = false;
68 /** @var string|bool Reason all LBs are read-only or false if not */
69 protected $readOnlyReason = false;
70 /** @var callable[] */
71 protected $replicationWaitCallbacks = [];
73 /** @var bool Whether this PHP instance is for a CLI script */
75 /** @var string Agent name for query profiling */
78 private static $loggerFields =
79 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
81 public function __construct( array $conf ) {
82 $this->localDomain
= isset( $conf['localDomain'] )
83 ? DatabaseDomain
::newFromId( $conf['localDomain'] )
84 : DatabaseDomain
::newUnspecified();
86 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
87 $this->readOnlyReason
= $conf['readOnlyReason'];
90 $this->srvCache
= isset( $conf['srvCache'] ) ?
$conf['srvCache'] : new EmptyBagOStuff();
91 $this->memCache
= isset( $conf['memCache'] ) ?
$conf['memCache'] : new EmptyBagOStuff();
92 $this->wanCache
= isset( $conf['wanCache'] )
94 : WANObjectCache
::newEmpty();
96 foreach ( self
::$loggerFields as $key ) {
97 $this->$key = isset( $conf[$key] ) ?
$conf[$key] : new \Psr\Log\
NullLogger();
99 $this->errorLogger
= isset( $conf['errorLogger'] )
100 ?
$conf['errorLogger']
101 : function ( Exception
$e ) {
102 trigger_error( E_USER_WARNING
, get_class( $e ) . ': ' . $e->getMessage() );
105 $this->profiler
= isset( $conf['profiler'] ) ?
$conf['profiler'] : null;
106 $this->trxProfiler
= isset( $conf['trxProfiler'] )
107 ?
$conf['trxProfiler']
108 : new TransactionProfiler();
110 $this->requestInfo
= [
111 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ?
$_SERVER[ 'REMOTE_ADDR' ] : '',
112 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ?
$_SERVER['HTTP_USER_AGENT'] : '',
113 'ChronologyProtection' => 'true'
116 $this->cliMode
= isset( $conf['cliMode'] ) ?
$conf['cliMode'] : PHP_SAPI
=== 'cli';
117 $this->hostname
= isset( $conf['hostname'] ) ?
$conf['hostname'] : gethostname();
118 $this->agent
= isset( $conf['agent'] ) ?
$conf['agent'] : '';
120 $this->ticket
= mt_rand();
123 public function destroy() {
124 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
125 $this->forEachLBCallMethod( 'disable' );
128 public function shutdown(
129 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null
131 $chronProt = $this->getChronologyProtector();
132 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
133 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync' );
134 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
135 $this->shutdownChronologyProtector( $chronProt, null, 'async' );
138 $this->commitMasterChanges( __METHOD__
); // sanity
142 * @see ILBFactory::newMainLB()
143 * @param bool $domain
144 * @return LoadBalancer
146 abstract public function newMainLB( $domain = false );
149 * @see ILBFactory::getMainLB()
150 * @param bool $domain
151 * @return LoadBalancer
153 abstract public function getMainLB( $domain = false );
156 * @see ILBFactory::newExternalLB()
157 * @param string $cluster
158 * @return LoadBalancer
160 abstract public function newExternalLB( $cluster );
163 * @see ILBFactory::getExternalLB()
164 * @param string $cluster
165 * @return LoadBalancer
167 abstract public function getExternalLB( $cluster );
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(
361 "Could not wait for replica DBs to catch up to " .
362 implode( ', ', $failed )
367 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
369 $this->replicationWaitCallbacks
[$name] = $callback;
371 unset( $this->replicationWaitCallbacks
[$name] );
375 public function getEmptyTransactionTicket( $fname ) {
376 if ( $this->hasMasterChanges() ) {
377 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
378 ( new RuntimeException() )->getTraceAsString() );
383 return $this->ticket
;
386 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
387 if ( $ticket !== $this->ticket
) {
388 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
389 ( new RuntimeException() )->getTraceAsString() );
394 // The transaction owner and any caller with the empty transaction ticket can commit
395 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
396 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
397 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
398 $fnameEffective = $this->trxRoundId
;
400 $fnameEffective = $fname;
403 $this->commitMasterChanges( $fnameEffective );
404 $this->waitForReplication( $opts );
405 // If a nested caller committed on behalf of $fname, start another empty $fname
406 // transaction, leaving the caller with the same empty transaction state as before.
407 if ( $fnameEffective !== $fname ) {
408 $this->beginMasterChanges( $fnameEffective );
412 public function getChronologyProtectorTouched( $dbName ) {
413 return $this->getChronologyProtector()->getTouched( $dbName );
416 public function disableChronologyProtection() {
417 $this->getChronologyProtector()->setEnabled( false );
421 * @return ChronologyProtector
423 protected function getChronologyProtector() {
424 if ( $this->chronProt
) {
425 return $this->chronProt
;
428 $this->chronProt
= new ChronologyProtector(
431 'ip' => $this->requestInfo
['IPAddress'],
432 'agent' => $this->requestInfo
['UserAgent'],
434 isset( $_GET['cpPosTime'] ) ?
$_GET['cpPosTime'] : null
436 $this->chronProt
->setLogger( $this->replLogger
);
438 if ( $this->cliMode
) {
439 $this->chronProt
->setEnabled( false );
440 } elseif ( $this->requestInfo
['ChronologyProtection'] === 'false' ) {
441 // Request opted out of using position wait logic. This is useful for requests
442 // done by the job queue or background ETL that do not have a meaningful session.
443 $this->chronProt
->setWaitEnabled( false );
446 $this->replLogger
->debug( __METHOD__
. ': using request info ' .
447 json_encode( $this->requestInfo
, JSON_PRETTY_PRINT
) );
449 return $this->chronProt
;
453 * Get and record all of the staged DB positions into persistent memory storage
455 * @param ChronologyProtector $cp
456 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
457 * @param string $mode One of (sync, async); whether to wait on remote datacenters
459 protected function shutdownChronologyProtector(
460 ChronologyProtector
$cp, $workCallback, $mode
462 // Record all the master positions needed
463 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
464 $cp->shutdownLB( $lb );
466 // Write them to the persistent stash. Try to do something useful by running $work
467 // while ChronologyProtector waits for the stash write to replicate to all DCs.
468 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
469 if ( $unsavedPositions && $workCallback ) {
470 // Invoke callback in case it did not cache the result yet
471 $workCallback(); // work now to block for less time in waitForAll()
473 // If the positions failed to write to the stash, at least wait on local datacenter
474 // replica DBs to catch up before responding. Even if there are several DCs, this increases
475 // the chance that the user will see their own changes immediately afterwards. As long
476 // as the sticky DC cookie applies (same domain), this is not even an issue.
477 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
478 $masterName = $lb->getServerName( $lb->getWriterIndex() );
479 if ( isset( $unsavedPositions[$masterName] ) ) {
480 $lb->waitForAll( $unsavedPositions[$masterName] );
486 * Base parameters to LoadBalancer::__construct()
489 final protected function baseLoadBalancerParams() {
491 'localDomain' => $this->localDomain
,
492 'readOnlyReason' => $this->readOnlyReason
,
493 'srvCache' => $this->srvCache
,
494 'wanCache' => $this->wanCache
,
495 'profiler' => $this->profiler
,
496 'trxProfiler' => $this->trxProfiler
,
497 'queryLogger' => $this->queryLogger
,
498 'connLogger' => $this->connLogger
,
499 'replLogger' => $this->replLogger
,
500 'errorLogger' => $this->errorLogger
,
501 'hostname' => $this->hostname
,
502 'cliMode' => $this->cliMode
,
503 'agent' => $this->agent
508 * @param ILoadBalancer $lb
510 protected function initLoadBalancer( ILoadBalancer
$lb ) {
511 if ( $this->trxRoundId
!== false ) {
512 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
516 public function setDomainPrefix( $prefix ) {
517 $this->localDomain
= new DatabaseDomain(
518 $this->localDomain
->getDatabase(),
523 $this->forEachLB( function( ILoadBalancer
$lb ) use ( $prefix ) {
524 $lb->setDomainPrefix( $prefix );
528 public function closeAll() {
529 $this->forEachLBCallMethod( 'closeAll', [] );
532 public function setAgentName( $agent ) {
533 $this->agent
= $agent;
536 public function appendPreShutdownTimeAsQuery( $url, $time ) {
538 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$usedCluster ) {
539 $usedCluster |
= ( $lb->getServerCount() > 1 );
542 if ( !$usedCluster ) {
543 return $url; // no master/replica clusters touched
546 return strpos( $url, '?' ) === false ?
"$url?cpPosTime=$time" : "$url&cpPosTime=$time";
549 public function setRequestInfo( array $info ) {
550 $this->requestInfo
= $info +
$this->requestInfo
;
554 * Make PHP ignore user aborts/disconnects until the returned
555 * value leaves scope. This returns null and does nothing in CLI mode.
557 * @return ScopedCallback|null
559 final protected function getScopedPHPBehaviorForCommit() {
560 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
561 $old = ignore_user_abort( true ); // avoid half-finished operations
562 return new ScopedCallback( function () use ( $old ) {
563 ignore_user_abort( $old );
570 function __destruct() {