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
;
27 * An interface for generating database load balancers
30 abstract class LBFactory
implements ILBFactory
{
31 /** @var ChronologyProtector */
33 /** @var object|string Class name or object With profileIn/profileOut methods */
35 /** @var TransactionProfiler */
36 protected $trxProfiler;
37 /** @var LoggerInterface */
38 protected $replLogger;
39 /** @var LoggerInterface */
40 protected $connLogger;
41 /** @var LoggerInterface */
42 protected $queryLogger;
43 /** @var LoggerInterface */
44 protected $perfLogger;
45 /** @var callable Error logger */
46 protected $errorLogger;
51 /** @var WANObjectCache */
54 /** @var DatabaseDomain Local domain */
55 protected $localDomain;
56 /** @var string Local hostname of the app server */
58 /** @var array Web request information about the client */
59 protected $requestInfo;
63 /** @var string|bool String if a requested DBO_TRX transaction round is active */
64 protected $trxRoundId = false;
65 /** @var string|bool Reason all LBs are read-only or false if not */
66 protected $readOnlyReason = false;
67 /** @var callable[] */
68 protected $replicationWaitCallbacks = [];
70 /** @var bool Whether this PHP instance is for a CLI script */
72 /** @var string Agent name for query profiling */
75 private static $loggerFields =
76 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
78 public function __construct( array $conf ) {
79 $this->localDomain
= isset( $conf['localDomain'] )
80 ? DatabaseDomain
::newFromId( $conf['localDomain'] )
81 : DatabaseDomain
::newUnspecified();
83 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
84 $this->readOnlyReason
= $conf['readOnlyReason'];
87 $this->srvCache
= isset( $conf['srvCache'] ) ?
$conf['srvCache'] : new EmptyBagOStuff();
88 $this->memCache
= isset( $conf['memCache'] ) ?
$conf['memCache'] : new EmptyBagOStuff();
89 $this->wanCache
= isset( $conf['wanCache'] )
91 : WANObjectCache
::newEmpty();
93 foreach ( self
::$loggerFields as $key ) {
94 $this->$key = isset( $conf[$key] ) ?
$conf[$key] : new \Psr\Log\
NullLogger();
96 $this->errorLogger
= isset( $conf['errorLogger'] )
97 ?
$conf['errorLogger']
98 : function ( Exception
$e ) {
99 trigger_error( E_USER_WARNING
, get_class( $e ) . ': ' . $e->getMessage() );
102 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
103 $this->trxProfiler
= isset( $conf['trxProfiler'] )
104 ?
$conf['trxProfiler']
105 : new TransactionProfiler();
107 $this->requestInfo
= [
108 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ?
$_SERVER[ 'REMOTE_ADDR' ] : '',
109 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ?
$_SERVER['HTTP_USER_AGENT'] : '',
110 'ChronologyProtection' => 'true'
113 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
114 $this->hostname
= isset( $conf['hostname'] ) ?
$conf['hostname'] : gethostname();
115 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
117 $this->ticket
= mt_rand();
120 public function destroy() {
121 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
122 $this->forEachLBCallMethod( 'disable' );
125 public function shutdown(
126 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null
128 $chronProt = $this->getChronologyProtector();
129 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
130 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync' );
131 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
132 $this->shutdownChronologyProtector( $chronProt, null, 'async' );
135 $this->commitMasterChanges( __METHOD__
); // sanity
139 * @see ILBFactory::newMainLB()
140 * @param bool $domain
141 * @return LoadBalancer
143 abstract public function newMainLB( $domain = false );
146 * @see ILBFactory::getMainLB()
147 * @param bool $domain
148 * @return LoadBalancer
150 abstract public function getMainLB( $domain = false );
153 * @see ILBFactory::newExternalLB()
154 * @param string $cluster
155 * @param bool $domain
156 * @return LoadBalancer
158 abstract public function newExternalLB( $cluster, $domain = false );
161 * @see ILBFactory::getExternalLB()
162 * @param string $cluster
163 * @param bool $domain
164 * @return LoadBalancer
166 abstract public function getExternalLB( $cluster, $domain = false );
169 * Call a method of each tracked load balancer
171 * @param string $methodName
174 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
176 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
177 call_user_func_array( [ $loadBalancer, $methodName ], $args );
179 [ $methodName, $args ]
183 public function flushReplicaSnapshots( $fname = __METHOD__
) {
184 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
187 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
188 $this->commitMasterChanges( $fname, $options );
189 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
192 public function beginMasterChanges( $fname = __METHOD__
) {
193 if ( $this->trxRoundId
!== false ) {
194 throw new DBTransactionError(
196 "$fname: transaction round '{$this->trxRoundId}' already started."
199 $this->trxRoundId
= $fname;
200 // Set DBO_TRX flags on all appropriate DBs
201 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
204 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
205 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
206 throw new DBTransactionError(
208 "$fname: transaction round '{$this->trxRoundId}' still running."
211 /** @noinspection PhpUnusedLocalVariableInspection */
212 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
213 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
214 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
215 $this->trxRoundId
= false;
216 // Perform pre-commit checks, aborting on failure
217 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
218 // Log the DBs and methods involved in multi-DB transactions
219 $this->logIfMultiDbTransaction();
220 // Actually perform the commit on all master DB connections and revert DBO_TRX
221 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
222 // Run all post-commit callbacks
223 /** @var Exception $e */
224 $e = null; // first callback exception
225 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
226 $ex = $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_COMMIT
);
229 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
230 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
231 // Throw any last post-commit callback error
232 if ( $e instanceof Exception
) {
237 public function rollbackMasterChanges( $fname = __METHOD__
) {
238 $this->trxRoundId
= false;
239 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
240 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
241 // Run all post-rollback callbacks
242 $this->forEachLB( function ( ILoadBalancer
$lb ) {
243 $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_ROLLBACK
);
248 * Log query info if multi DB transactions are going to be committed now
250 private function logIfMultiDbTransaction() {
252 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
253 $masterName = $lb->getServerName( $lb->getWriterIndex() );
254 $callers = $lb->pendingMasterChangeCallers();
256 $callersByDB[$masterName] = $callers;
260 if ( count( $callersByDB ) >= 2 ) {
261 $dbs = implode( ', ', array_keys( $callersByDB ) );
262 $msg = "Multi-DB transaction [{$dbs}]:\n";
263 foreach ( $callersByDB as $db => $callers ) {
264 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
266 $this->queryLogger
->info( $msg );
270 public function hasMasterChanges() {
272 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
273 $ret = $ret ||
$lb->hasMasterChanges();
279 public function laggedReplicaUsed() {
281 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
282 $ret = $ret ||
$lb->laggedReplicaUsed();
288 public function hasOrMadeRecentMasterChanges( $age = null ) {
290 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
291 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
296 public function waitForReplication( array $opts = [] ) {
301 'ifWritesSince' => null
304 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
305 $opts['domain'] = $opts['wiki']; // b/c
308 // Figure out which clusters need to be checked
309 /** @var ILoadBalancer[] $lbs */
311 if ( $opts['cluster'] !== false ) {
312 $lbs[] = $this->getExternalLB( $opts['cluster'] );
313 } elseif ( $opts['domain'] !== false ) {
314 $lbs[] = $this->getMainLB( $opts['domain'] );
316 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
320 return; // nothing actually used
324 // Get all the master positions of applicable DBs right now.
325 // This can be faster since waiting on one cluster reduces the
326 // time needed to wait on the next clusters.
327 $masterPositions = array_fill( 0, count( $lbs ), false );
328 foreach ( $lbs as $i => $lb ) {
329 if ( $lb->getServerCount() <= 1 ) {
330 // Bug 27975 - Don't try to wait for replica DBs if there are none
331 // Prevents permission error when getting master position
333 } elseif ( $opts['ifWritesSince']
334 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
336 continue; // no writes since the last wait
338 $masterPositions[$i] = $lb->getMasterPos();
341 // Run any listener callbacks *after* getting the DB positions. The more
342 // time spent in the callbacks, the less time is spent in waitForAll().
343 foreach ( $this->replicationWaitCallbacks
as $callback ) {
348 foreach ( $lbs as $i => $lb ) {
349 if ( $masterPositions[$i] ) {
350 // The DBMS may not support getMasterPos()
351 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
352 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
358 throw new DBReplicationWaitError(
359 "Could not wait for replica DBs to catch up to " .
360 implode( ', ', $failed )
365 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
367 $this->replicationWaitCallbacks
[$name] = $callback;
369 unset( $this->replicationWaitCallbacks
[$name] );
373 public function getEmptyTransactionTicket( $fname ) {
374 if ( $this->hasMasterChanges() ) {
375 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
376 ( new RuntimeException() )->getTraceAsString() );
381 return $this->ticket
;
384 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
385 if ( $ticket !== $this->ticket
) {
386 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope.\n" .
387 ( new RuntimeException() )->getTraceAsString() );
392 // The transaction owner and any caller with the empty transaction ticket can commit
393 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
394 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
395 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
396 $fnameEffective = $this->trxRoundId
;
398 $fnameEffective = $fname;
401 $this->commitMasterChanges( $fnameEffective );
402 $this->waitForReplication( $opts );
403 // If a nested caller committed on behalf of $fname, start another empty $fname
404 // transaction, leaving the caller with the same empty transaction state as before.
405 if ( $fnameEffective !== $fname ) {
406 $this->beginMasterChanges( $fnameEffective );
410 public function getChronologyProtectorTouched( $dbName ) {
411 return $this->getChronologyProtector()->getTouched( $dbName );
414 public function disableChronologyProtection() {
415 $this->getChronologyProtector()->setEnabled( false );
419 * @return ChronologyProtector
421 protected function getChronologyProtector() {
422 if ( $this->chronProt
) {
423 return $this->chronProt
;
426 $this->chronProt
= new ChronologyProtector(
429 'ip' => $this->requestInfo
['IPAddress'],
430 'agent' => $this->requestInfo
['UserAgent'],
432 isset( $_GET['cpPosTime'] ) ?
$_GET['cpPosTime'] : null
434 $this->chronProt
->setLogger( $this->replLogger
);
436 if ( $this->cliMode
) {
437 $this->chronProt
->setEnabled( false );
438 } elseif ( $this->requestInfo
['ChronologyProtection'] === 'false' ) {
439 // Request opted out of using position wait logic. This is useful for requests
440 // done by the job queue or background ETL that do not have a meaningful session.
441 $this->chronProt
->setWaitEnabled( false );
444 $this->replLogger
->debug( __METHOD__
. ': using request info ' .
445 json_encode( $this->requestInfo
, JSON_PRETTY_PRINT
) );
447 return $this->chronProt
;
451 * Get and record all of the staged DB positions into persistent memory storage
453 * @param ChronologyProtector $cp
454 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
455 * @param string $mode One of (sync, async); whether to wait on remote datacenters
457 protected function shutdownChronologyProtector(
458 ChronologyProtector
$cp, $workCallback, $mode
460 // Record all the master positions needed
461 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
462 $cp->shutdownLB( $lb );
464 // Write them to the persistent stash. Try to do something useful by running $work
465 // while ChronologyProtector waits for the stash write to replicate to all DCs.
466 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
467 if ( $unsavedPositions && $workCallback ) {
468 // Invoke callback in case it did not cache the result yet
469 $workCallback(); // work now to block for less time in waitForAll()
471 // If the positions failed to write to the stash, at least wait on local datacenter
472 // replica DBs to catch up before responding. Even if there are several DCs, this increases
473 // the chance that the user will see their own changes immediately afterwards. As long
474 // as the sticky DC cookie applies (same domain), this is not even an issue.
475 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
476 $masterName = $lb->getServerName( $lb->getWriterIndex() );
477 if ( isset( $unsavedPositions[$masterName] ) ) {
478 $lb->waitForAll( $unsavedPositions[$masterName] );
484 * Base parameters to LoadBalancer::__construct()
487 final protected function baseLoadBalancerParams() {
489 'localDomain' => $this->localDomain
,
490 'readOnlyReason' => $this->readOnlyReason
,
491 'srvCache' => $this->srvCache
,
492 'wanCache' => $this->wanCache
,
493 'profiler' => $this->profiler
,
494 'trxProfiler' => $this->trxProfiler
,
495 'queryLogger' => $this->queryLogger
,
496 'connLogger' => $this->connLogger
,
497 'replLogger' => $this->replLogger
,
498 'errorLogger' => $this->errorLogger
,
499 'hostname' => $this->hostname
,
500 'cliMode' => $this->cliMode
,
501 'agent' => $this->agent
506 * @param ILoadBalancer $lb
508 protected function initLoadBalancer( ILoadBalancer
$lb ) {
509 if ( $this->trxRoundId
!== false ) {
510 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
514 public function setDomainPrefix( $prefix ) {
515 $this->localDomain
= new DatabaseDomain(
516 $this->localDomain
->getDatabase(),
521 $this->forEachLB( function( ILoadBalancer
$lb ) use ( $prefix ) {
522 $lb->setDomainPrefix( $prefix );
526 public function closeAll() {
527 $this->forEachLBCallMethod( 'closeAll', [] );
530 public function setAgentName( $agent ) {
531 $this->agent
= $agent;
534 public function appendPreShutdownTimeAsQuery( $url, $time ) {
536 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$usedCluster ) {
537 $usedCluster |
= ( $lb->getServerCount() > 1 );
540 if ( !$usedCluster ) {
541 return $url; // no master/replica clusters touched
544 return strpos( $url, '?' ) === false ?
"$url?cpPosTime=$time" : "$url&cpPosTime=$time";
547 public function setRequestInfo( array $info ) {
548 $this->requestInfo
= $info +
$this->requestInfo
;
552 * Make PHP ignore user aborts/disconnects until the returned
553 * value leaves scope. This returns null and does nothing in CLI mode.
555 * @return ScopedCallback|null
557 final protected function getScopedPHPBehaviorForCommit() {
558 if ( PHP_SAPI
!= 'cli' ) { // http://bugs.php.net/bug.php?id=47540
559 $old = ignore_user_abort( true ); // avoid half-finished operations
560 return new ScopedCallback( function () use ( $old ) {
561 ignore_user_abort( $old );
568 function __destruct() {