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
;
33 use DBTransactionError
;
34 use DBReplicationWaitError
;
37 * An interface for generating database load balancers
40 abstract class LBFactory
implements ILBFactory
{
41 /** @var ChronologyProtector */
43 /** @var object|string Class name or object With profileIn/profileOut methods */
45 /** @var TransactionProfiler */
46 protected $trxProfiler;
47 /** @var LoggerInterface */
48 protected $replLogger;
49 /** @var LoggerInterface */
50 protected $connLogger;
51 /** @var LoggerInterface */
52 protected $queryLogger;
53 /** @var LoggerInterface */
54 protected $perfLogger;
55 /** @var callable Error logger */
56 protected $errorLogger;
61 /** @var WANObjectCache */
64 /** @var DatabaseDomain Local domain */
65 protected $localDomain;
66 /** @var string Local hostname of the app server */
68 /** @var array Web request information about the client */
69 protected $requestInfo;
73 /** @var string|bool String if a requested DBO_TRX transaction round is active */
74 protected $trxRoundId = false;
75 /** @var string|bool Reason all LBs are read-only or false if not */
76 protected $readOnlyReason = false;
77 /** @var callable[] */
78 protected $replicationWaitCallbacks = [];
80 /** @var bool Whether this PHP instance is for a CLI script */
82 /** @var string Agent name for query profiling */
85 private static $loggerFields =
86 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
88 public function __construct( array $conf ) {
89 $this->localDomain
= isset( $conf['localDomain'] )
90 ? DatabaseDomain
::newFromId( $conf['localDomain'] )
91 : DatabaseDomain
::newUnspecified();
93 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
94 $this->readOnlyReason
= $conf['readOnlyReason'];
97 $this->srvCache
= isset( $conf['srvCache'] ) ?
$conf['srvCache'] : new EmptyBagOStuff();
98 $this->memCache
= isset( $conf['memCache'] ) ?
$conf['memCache'] : new EmptyBagOStuff();
99 $this->wanCache
= isset( $conf['wanCache'] )
101 : WANObjectCache
::newEmpty();
103 foreach ( self
::$loggerFields as $key ) {
104 $this->$key = isset( $conf[$key] ) ?
$conf[$key] : new \Psr\Log\
NullLogger();
106 $this->errorLogger
= isset( $conf['errorLogger'] )
107 ?
$conf['errorLogger']
108 : function ( Exception
$e ) {
109 trigger_error( E_USER_WARNING
, get_class( $e ) . ': ' . $e->getMessage() );
112 $this->profiler
= isset( $conf['profiler'] ) ?
$conf['profiler'] : null;
113 $this->trxProfiler
= isset( $conf['trxProfiler'] )
114 ?
$conf['trxProfiler']
115 : new TransactionProfiler();
117 $this->requestInfo
= [
118 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ?
$_SERVER[ 'REMOTE_ADDR' ] : '',
119 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ?
$_SERVER['HTTP_USER_AGENT'] : '',
120 'ChronologyProtection' => 'true'
123 $this->cliMode
= isset( $conf['cliMode'] ) ?
$conf['cliMode'] : PHP_SAPI
=== 'cli';
124 $this->hostname
= isset( $conf['hostname'] ) ?
$conf['hostname'] : gethostname();
125 $this->agent
= isset( $conf['agent'] ) ?
$conf['agent'] : '';
127 $this->ticket
= mt_rand();
130 public function destroy() {
131 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
132 $this->forEachLBCallMethod( 'disable' );
135 public function shutdown(
136 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null
138 $chronProt = $this->getChronologyProtector();
139 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
140 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync' );
141 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
142 $this->shutdownChronologyProtector( $chronProt, null, 'async' );
145 $this->commitMasterChanges( __METHOD__
); // sanity
149 * @see ILBFactory::newMainLB()
150 * @param bool $domain
151 * @return LoadBalancer
153 abstract public function newMainLB( $domain = false );
156 * @see ILBFactory::getMainLB()
157 * @param bool $domain
158 * @return LoadBalancer
160 abstract public function getMainLB( $domain = false );
163 * @see ILBFactory::newExternalLB()
164 * @param string $cluster
165 * @return LoadBalancer
167 abstract public function newExternalLB( $cluster );
170 * @see ILBFactory::getExternalLB()
171 * @param string $cluster
172 * @return LoadBalancer
174 abstract public function getExternalLB( $cluster );
177 * Call a method of each tracked load balancer
179 * @param string $methodName
182 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
184 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
185 call_user_func_array( [ $loadBalancer, $methodName ], $args );
187 [ $methodName, $args ]
191 public function flushReplicaSnapshots( $fname = __METHOD__
) {
192 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
195 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
196 $this->commitMasterChanges( $fname, $options );
197 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
200 public function beginMasterChanges( $fname = __METHOD__
) {
201 if ( $this->trxRoundId
!== false ) {
202 throw new DBTransactionError(
204 "$fname: transaction round '{$this->trxRoundId}' already started."
207 $this->trxRoundId
= $fname;
208 // Set DBO_TRX flags on all appropriate DBs
209 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
212 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
213 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
214 throw new DBTransactionError(
216 "$fname: transaction round '{$this->trxRoundId}' still running."
219 /** @noinspection PhpUnusedLocalVariableInspection */
220 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
221 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
222 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
223 $this->trxRoundId
= false;
224 // Perform pre-commit checks, aborting on failure
225 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
226 // Log the DBs and methods involved in multi-DB transactions
227 $this->logIfMultiDbTransaction();
228 // Actually perform the commit on all master DB connections and revert DBO_TRX
229 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
230 // Run all post-commit callbacks
231 /** @var Exception $e */
232 $e = null; // first callback exception
233 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
234 $ex = $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_COMMIT
);
237 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
238 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
239 // Throw any last post-commit callback error
240 if ( $e instanceof Exception
) {
245 public function rollbackMasterChanges( $fname = __METHOD__
) {
246 $this->trxRoundId
= false;
247 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
248 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
249 // Run all post-rollback callbacks
250 $this->forEachLB( function ( ILoadBalancer
$lb ) {
251 $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_ROLLBACK
);
256 * Log query info if multi DB transactions are going to be committed now
258 private function logIfMultiDbTransaction() {
260 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
261 $masterName = $lb->getServerName( $lb->getWriterIndex() );
262 $callers = $lb->pendingMasterChangeCallers();
264 $callersByDB[$masterName] = $callers;
268 if ( count( $callersByDB ) >= 2 ) {
269 $dbs = implode( ', ', array_keys( $callersByDB ) );
270 $msg = "Multi-DB transaction [{$dbs}]:\n";
271 foreach ( $callersByDB as $db => $callers ) {
272 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
274 $this->queryLogger
->info( $msg );
278 public function hasMasterChanges() {
280 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
281 $ret = $ret ||
$lb->hasMasterChanges();
287 public function laggedReplicaUsed() {
289 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
290 $ret = $ret ||
$lb->laggedReplicaUsed();
296 public function hasOrMadeRecentMasterChanges( $age = null ) {
298 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
299 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
304 public function waitForReplication( array $opts = [] ) {
309 'ifWritesSince' => null
312 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
313 $opts['domain'] = $opts['wiki']; // b/c
316 // Figure out which clusters need to be checked
317 /** @var ILoadBalancer[] $lbs */
319 if ( $opts['cluster'] !== false ) {
320 $lbs[] = $this->getExternalLB( $opts['cluster'] );
321 } elseif ( $opts['domain'] !== false ) {
322 $lbs[] = $this->getMainLB( $opts['domain'] );
324 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
328 return; // nothing actually used
332 // Get all the master positions of applicable DBs right now.
333 // This can be faster since waiting on one cluster reduces the
334 // time needed to wait on the next clusters.
335 $masterPositions = array_fill( 0, count( $lbs ), false );
336 foreach ( $lbs as $i => $lb ) {
337 if ( $lb->getServerCount() <= 1 ) {
338 // T29975 - Don't try to wait for replica DBs if there are none
339 // Prevents permission error when getting master position
341 } elseif ( $opts['ifWritesSince']
342 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
344 continue; // no writes since the last wait
346 $masterPositions[$i] = $lb->getMasterPos();
349 // Run any listener callbacks *after* getting the DB positions. The more
350 // time spent in the callbacks, the less time is spent in waitForAll().
351 foreach ( $this->replicationWaitCallbacks
as $callback ) {
356 foreach ( $lbs as $i => $lb ) {
357 if ( $masterPositions[$i] ) {
358 // The DBMS may not support getMasterPos()
359 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
360 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
366 throw new DBReplicationWaitError(
368 "Could not wait for replica DBs to catch up to " .
369 implode( ', ', $failed )
374 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
376 $this->replicationWaitCallbacks
[$name] = $callback;
378 unset( $this->replicationWaitCallbacks
[$name] );
382 public function getEmptyTransactionTicket( $fname ) {
383 if ( $this->hasMasterChanges() ) {
384 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
385 ( new RuntimeException() )->getTraceAsString() );
390 return $this->ticket
;
393 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
394 if ( $ticket !== $this->ticket
) {
395 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
396 ( new RuntimeException() )->getTraceAsString() );
401 // The transaction owner and any caller with the empty transaction ticket can commit
402 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
403 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
404 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
405 $fnameEffective = $this->trxRoundId
;
407 $fnameEffective = $fname;
410 $this->commitMasterChanges( $fnameEffective );
411 $this->waitForReplication( $opts );
412 // If a nested caller committed on behalf of $fname, start another empty $fname
413 // transaction, leaving the caller with the same empty transaction state as before.
414 if ( $fnameEffective !== $fname ) {
415 $this->beginMasterChanges( $fnameEffective );
419 public function getChronologyProtectorTouched( $dbName ) {
420 return $this->getChronologyProtector()->getTouched( $dbName );
423 public function disableChronologyProtection() {
424 $this->getChronologyProtector()->setEnabled( false );
428 * @return ChronologyProtector
430 protected function getChronologyProtector() {
431 if ( $this->chronProt
) {
432 return $this->chronProt
;
435 $this->chronProt
= new ChronologyProtector(
438 'ip' => $this->requestInfo
['IPAddress'],
439 'agent' => $this->requestInfo
['UserAgent'],
441 isset( $_GET['cpPosTime'] ) ?
$_GET['cpPosTime'] : null
443 $this->chronProt
->setLogger( $this->replLogger
);
445 if ( $this->cliMode
) {
446 $this->chronProt
->setEnabled( false );
447 } elseif ( $this->requestInfo
['ChronologyProtection'] === 'false' ) {
448 // Request opted out of using position wait logic. This is useful for requests
449 // done by the job queue or background ETL that do not have a meaningful session.
450 $this->chronProt
->setWaitEnabled( false );
453 $this->replLogger
->debug( __METHOD__
. ': using request info ' .
454 json_encode( $this->requestInfo
, JSON_PRETTY_PRINT
) );
456 return $this->chronProt
;
460 * Get and record all of the staged DB positions into persistent memory storage
462 * @param ChronologyProtector $cp
463 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
464 * @param string $mode One of (sync, async); whether to wait on remote datacenters
466 protected function shutdownChronologyProtector(
467 ChronologyProtector
$cp, $workCallback, $mode
469 // Record all the master positions needed
470 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
471 $cp->shutdownLB( $lb );
473 // Write them to the persistent stash. Try to do something useful by running $work
474 // while ChronologyProtector waits for the stash write to replicate to all DCs.
475 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
476 if ( $unsavedPositions && $workCallback ) {
477 // Invoke callback in case it did not cache the result yet
478 $workCallback(); // work now to block for less time in waitForAll()
480 // If the positions failed to write to the stash, at least wait on local datacenter
481 // replica DBs to catch up before responding. Even if there are several DCs, this increases
482 // the chance that the user will see their own changes immediately afterwards. As long
483 // as the sticky DC cookie applies (same domain), this is not even an issue.
484 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
485 $masterName = $lb->getServerName( $lb->getWriterIndex() );
486 if ( isset( $unsavedPositions[$masterName] ) ) {
487 $lb->waitForAll( $unsavedPositions[$masterName] );
493 * Base parameters to LoadBalancer::__construct()
496 final protected function baseLoadBalancerParams() {
498 'localDomain' => $this->localDomain
,
499 'readOnlyReason' => $this->readOnlyReason
,
500 'srvCache' => $this->srvCache
,
501 'wanCache' => $this->wanCache
,
502 'profiler' => $this->profiler
,
503 'trxProfiler' => $this->trxProfiler
,
504 'queryLogger' => $this->queryLogger
,
505 'connLogger' => $this->connLogger
,
506 'replLogger' => $this->replLogger
,
507 'errorLogger' => $this->errorLogger
,
508 'hostname' => $this->hostname
,
509 'cliMode' => $this->cliMode
,
510 'agent' => $this->agent
515 * @param ILoadBalancer $lb
517 protected function initLoadBalancer( ILoadBalancer
$lb ) {
518 if ( $this->trxRoundId
!== false ) {
519 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
523 public function setDomainPrefix( $prefix ) {
524 $this->localDomain
= new DatabaseDomain(
525 $this->localDomain
->getDatabase(),
530 $this->forEachLB( function( ILoadBalancer
$lb ) use ( $prefix ) {
531 $lb->setDomainPrefix( $prefix );
535 public function closeAll() {
536 $this->forEachLBCallMethod( 'closeAll', [] );
539 public function setAgentName( $agent ) {
540 $this->agent
= $agent;
543 public function appendPreShutdownTimeAsQuery( $url, $time ) {
545 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$usedCluster ) {
546 $usedCluster |
= ( $lb->getServerCount() > 1 );
549 if ( !$usedCluster ) {
550 return $url; // no master/replica clusters touched
553 return strpos( $url, '?' ) === false ?
"$url?cpPosTime=$time" : "$url&cpPosTime=$time";
556 public function setRequestInfo( array $info ) {
557 $this->requestInfo
= $info +
$this->requestInfo
;
561 * Make PHP ignore user aborts/disconnects until the returned
562 * value leaves scope. This returns null and does nothing in CLI mode.
564 * @return ScopedCallback|null
566 final protected function getScopedPHPBehaviorForCommit() {
567 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
568 $old = ignore_user_abort( true ); // avoid half-finished operations
569 return new ScopedCallback( function () use ( $old ) {
570 ignore_user_abort( $old );
577 function __destruct() {