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
{
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 const SHUTDOWN_NO_CHRONPROT
= 0; // don't save DB positions at all
76 const SHUTDOWN_CHRONPROT_ASYNC
= 1; // save DB positions, but don't wait on remote DCs
77 const SHUTDOWN_CHRONPROT_SYNC
= 2; // save DB positions, waiting on all DCs
79 private static $loggerFields =
80 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
83 * @TODO: document base params here
86 public function __construct( array $conf ) {
87 $this->localDomain
= isset( $conf['localDomain'] )
88 ? DatabaseDomain
::newFromId( $conf['localDomain'] )
89 : DatabaseDomain
::newUnspecified();
91 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
92 $this->readOnlyReason
= $conf['readOnlyReason'];
95 $this->srvCache
= isset( $conf['srvCache'] ) ?
$conf['srvCache'] : new EmptyBagOStuff();
96 $this->memCache
= isset( $conf['memCache'] ) ?
$conf['memCache'] : new EmptyBagOStuff();
97 $this->wanCache
= isset( $conf['wanCache'] )
99 : WANObjectCache
::newEmpty();
101 foreach ( self
::$loggerFields as $key ) {
102 $this->$key = isset( $conf[$key] ) ?
$conf[$key] : new \Psr\Log\
NullLogger();
104 $this->errorLogger
= isset( $conf['errorLogger'] )
105 ?
$conf['errorLogger']
106 : function ( Exception
$e ) {
107 trigger_error( E_WARNING
, get_class( $e ) . ': ' . $e->getMessage() );
110 $this->chronProt
= isset( $conf['chronProt'] ) ?
$conf['chronProt'] : null;
112 $this->profiler
= isset( $params['profiler'] ) ?
$params['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( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
124 $this->hostname
= isset( $conf['hostname'] ) ?
$conf['hostname'] : gethostname();
125 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
127 $this->ticket
= mt_rand();
131 * Disables all load balancers. All connections are closed, and any attempt to
132 * open a new connection will result in a DBAccessError.
133 * @see LoadBalancer::disable()
135 public function destroy() {
136 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
137 $this->forEachLBCallMethod( 'disable' );
141 * Create a new load balancer object. The resulting object will be untracked,
142 * not chronology-protected, and the caller is responsible for cleaning it up.
144 * @param bool|string $domain Domain ID, or false for the current domain
145 * @return ILoadBalancer
147 abstract public function newMainLB( $domain = false );
150 * Get a cached (tracked) load balancer object.
152 * @param bool|string $domain Domain ID, or false for the current domain
153 * @return ILoadBalancer
155 abstract public function getMainLB( $domain = false );
158 * Create a new load balancer for external storage. The resulting object will be
159 * untracked, not chronology-protected, and the caller is responsible for
162 * @param string $cluster External storage cluster, or false for core
163 * @param bool|string $domain Domain ID, or false for the current domain
164 * @return ILoadBalancer
166 abstract protected function newExternalLB( $cluster, $domain = false );
169 * Get a cached (tracked) load balancer for external storage
171 * @param string $cluster External storage cluster, or false for core
172 * @param bool|string $domain Domain ID, or false for the current domain
173 * @return ILoadBalancer
175 abstract public function getExternalLB( $cluster, $domain = false );
178 * Execute a function for each tracked load balancer
179 * The callback is called with the load balancer as the first parameter,
180 * and $params passed as the subsequent parameters.
182 * @param callable $callback
183 * @param array $params
185 abstract public function forEachLB( $callback, array $params = [] );
188 * Prepare all tracked load balancers for shutdown
189 * @param integer $mode One of the class SHUTDOWN_* constants
190 * @param callable|null $workCallback Work to mask ChronologyProtector writes
192 public function shutdown(
193 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null
195 $chronProt = $this->getChronologyProtector();
196 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
197 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync' );
198 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
199 $this->shutdownChronologyProtector( $chronProt, null, 'async' );
202 $this->commitMasterChanges( __METHOD__
); // sanity
206 * Call a method of each tracked load balancer
208 * @param string $methodName
211 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
213 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
214 call_user_func_array( [ $loadBalancer, $methodName ], $args );
216 [ $methodName, $args ]
221 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
223 * @param string $fname Caller name
226 public function flushReplicaSnapshots( $fname = __METHOD__
) {
227 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
231 * Commit on all connections. Done for two reasons:
232 * 1. To commit changes to the masters.
233 * 2. To release the snapshot on all connections, master and replica DB.
234 * @param string $fname Caller name
235 * @param array $options Options map:
236 * - maxWriteDuration: abort if more than this much time was spent in write queries
238 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
239 $this->commitMasterChanges( $fname, $options );
240 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
244 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
246 * The DBO_TRX setting will be reverted to the default in each of these methods:
247 * - commitMasterChanges()
248 * - rollbackMasterChanges()
251 * This allows for custom transaction rounds from any outer transaction scope.
253 * @param string $fname
254 * @throws DBTransactionError
257 public function beginMasterChanges( $fname = __METHOD__
) {
258 if ( $this->trxRoundId
!== false ) {
259 throw new DBTransactionError(
261 "$fname: transaction round '{$this->trxRoundId}' already started."
264 $this->trxRoundId
= $fname;
265 // Set DBO_TRX flags on all appropriate DBs
266 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
270 * Commit changes on all master connections
271 * @param string $fname Caller name
272 * @param array $options Options map:
273 * - maxWriteDuration: abort if more than this much time was spent in write queries
276 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
277 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
278 throw new DBTransactionError(
280 "$fname: transaction round '{$this->trxRoundId}' still running."
283 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
284 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
285 $this->trxRoundId
= false;
286 // Perform pre-commit checks, aborting on failure
287 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
288 // Log the DBs and methods involved in multi-DB transactions
289 $this->logIfMultiDbTransaction();
290 // Actually perform the commit on all master DB connections and revert DBO_TRX
291 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
292 // Run all post-commit callbacks
293 /** @var Exception $e */
294 $e = null; // first callback exception
295 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
296 $ex = $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_COMMIT
);
299 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
300 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
301 // Throw any last post-commit callback error
302 if ( $e instanceof Exception
) {
308 * Rollback changes on all master connections
309 * @param string $fname Caller name
312 public function rollbackMasterChanges( $fname = __METHOD__
) {
313 $this->trxRoundId
= false;
314 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
315 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
316 // Run all post-rollback callbacks
317 $this->forEachLB( function ( ILoadBalancer
$lb ) {
318 $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_ROLLBACK
);
323 * Log query info if multi DB transactions are going to be committed now
325 private function logIfMultiDbTransaction() {
327 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
328 $masterName = $lb->getServerName( $lb->getWriterIndex() );
329 $callers = $lb->pendingMasterChangeCallers();
331 $callersByDB[$masterName] = $callers;
335 if ( count( $callersByDB ) >= 2 ) {
336 $dbs = implode( ', ', array_keys( $callersByDB ) );
337 $msg = "Multi-DB transaction [{$dbs}]:\n";
338 foreach ( $callersByDB as $db => $callers ) {
339 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
341 $this->queryLogger
->info( $msg );
346 * Determine if any master connection has pending changes
350 public function hasMasterChanges() {
352 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
353 $ret = $ret ||
$lb->hasMasterChanges();
360 * Detemine if any lagged replica DB connection was used
364 public function laggedReplicaUsed() {
366 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
367 $ret = $ret ||
$lb->laggedReplicaUsed();
374 * Determine if any master connection has pending/written changes from this request
375 * @param float $age How many seconds ago is "recent" [defaults to LB lag wait timeout]
379 public function hasOrMadeRecentMasterChanges( $age = null ) {
381 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
382 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
388 * Waits for the replica DBs to catch up to the current master position
390 * Use this when updating very large numbers of rows, as in maintenance scripts,
391 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
393 * By default this waits on all DB clusters actually used in this request.
394 * This makes sense when lag being waiting on is caused by the code that does this check.
395 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
396 * that were not changed since the last wait check. To forcefully wait on a specific cluster
397 * for a given wiki, use the 'wiki' parameter. To forcefully wait on an "external" cluster,
398 * use the "cluster" parameter.
400 * Never call this function after a large DB write that is *still* in a transaction.
401 * It only makes sense to call this after the possible lag inducing changes were committed.
403 * @param array $opts Optional fields that include:
404 * - wiki : wait on the load balancer DBs that handles the given wiki
405 * - cluster : wait on the given external load balancer DBs
406 * - timeout : Max wait time. Default: ~60 seconds
407 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
408 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
411 public function waitForReplication( array $opts = [] ) {
416 'ifWritesSince' => null
419 // Figure out which clusters need to be checked
420 /** @var ILoadBalancer[] $lbs */
422 if ( $opts['cluster'] !== false ) {
423 $lbs[] = $this->getExternalLB( $opts['cluster'] );
424 } elseif ( $opts['wiki'] !== false ) {
425 $lbs[] = $this->getMainLB( $opts['wiki'] );
427 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
431 return; // nothing actually used
435 // Get all the master positions of applicable DBs right now.
436 // This can be faster since waiting on one cluster reduces the
437 // time needed to wait on the next clusters.
438 $masterPositions = array_fill( 0, count( $lbs ), false );
439 foreach ( $lbs as $i => $lb ) {
440 if ( $lb->getServerCount() <= 1 ) {
441 // Bug 27975 - Don't try to wait for replica DBs if there are none
442 // Prevents permission error when getting master position
444 } elseif ( $opts['ifWritesSince']
445 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
447 continue; // no writes since the last wait
449 $masterPositions[$i] = $lb->getMasterPos();
452 // Run any listener callbacks *after* getting the DB positions. The more
453 // time spent in the callbacks, the less time is spent in waitForAll().
454 foreach ( $this->replicationWaitCallbacks
as $callback ) {
459 foreach ( $lbs as $i => $lb ) {
460 if ( $masterPositions[$i] ) {
461 // The DBMS may not support getMasterPos()
462 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
463 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
469 throw new DBReplicationWaitError(
470 "Could not wait for replica DBs to catch up to " .
471 implode( ', ', $failed )
477 * Add a callback to be run in every call to waitForReplication() before waiting
479 * Callbacks must clear any transactions that they start
481 * @param string $name Callback name
482 * @param callable|null $callback Use null to unset a callback
485 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
487 $this->replicationWaitCallbacks
[$name] = $callback;
489 unset( $this->replicationWaitCallbacks
[$name] );
494 * Get a token asserting that no transaction writes are active
496 * @param string $fname Caller name (e.g. __METHOD__)
497 * @return mixed A value to pass to commitAndWaitForReplication()
500 public function getEmptyTransactionTicket( $fname ) {
501 if ( $this->hasMasterChanges() ) {
502 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope." );
506 return $this->ticket
;
510 * Convenience method for safely running commitMasterChanges()/waitForReplication()
512 * This will commit and wait unless $ticket indicates it is unsafe to do so
514 * @param string $fname Caller name (e.g. __METHOD__)
515 * @param mixed $ticket Result of getEmptyTransactionTicket()
516 * @param array $opts Options to waitForReplication()
517 * @throws DBReplicationWaitError
520 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
521 if ( $ticket !== $this->ticket
) {
522 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope." );
526 // The transaction owner and any caller with the empty transaction ticket can commit
527 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
528 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
529 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
530 $fnameEffective = $this->trxRoundId
;
532 $fnameEffective = $fname;
535 $this->commitMasterChanges( $fnameEffective );
536 $this->waitForReplication( $opts );
537 // If a nested caller committed on behalf of $fname, start another empty $fname
538 // transaction, leaving the caller with the same empty transaction state as before.
539 if ( $fnameEffective !== $fname ) {
540 $this->beginMasterChanges( $fnameEffective );
545 * @param string $dbName DB master name (e.g. "db1052")
546 * @return float|bool UNIX timestamp when client last touched the DB or false if not recent
549 public function getChronologyProtectorTouched( $dbName ) {
550 return $this->getChronologyProtector()->getTouched( $dbName );
554 * Disable the ChronologyProtector for all load balancers
556 * This can be called at the start of special API entry points
560 public function disableChronologyProtection() {
561 $this->getChronologyProtector()->setEnabled( false );
565 * @return ChronologyProtector
567 protected function getChronologyProtector() {
568 if ( $this->chronProt
) {
569 return $this->chronProt
;
572 $this->chronProt
= new ChronologyProtector(
575 'ip' => $this->requestInfo
['IPAddress'],
576 'agent' => $this->requestInfo
['UserAgent'],
578 isset( $_GET['cpPosTime'] ) ?
$_GET['cpPosTime'] : null
580 $this->chronProt
->setLogger( $this->replLogger
);
582 if ( $this->cliMode
) {
583 $this->chronProt
->setEnabled( false );
584 } elseif ( $this->requestInfo
['ChronologyProtection'] === 'false' ) {
585 // Request opted out of using position wait logic. This is useful for requests
586 // done by the job queue or background ETL that do not have a meaningful session.
587 $this->chronProt
->setWaitEnabled( false );
590 $this->replLogger
->debug( __METHOD__
. ': using request info ' .
591 json_encode( $this->requestInfo
, JSON_PRETTY_PRINT
) );
593 return $this->chronProt
;
597 * Get and record all of the staged DB positions into persistent memory storage
599 * @param ChronologyProtector $cp
600 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
601 * @param string $mode One of (sync, async); whether to wait on remote datacenters
603 protected function shutdownChronologyProtector(
604 ChronologyProtector
$cp, $workCallback, $mode
606 // Record all the master positions needed
607 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
608 $cp->shutdownLB( $lb );
610 // Write them to the persistent stash. Try to do something useful by running $work
611 // while ChronologyProtector waits for the stash write to replicate to all DCs.
612 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
613 if ( $unsavedPositions && $workCallback ) {
614 // Invoke callback in case it did not cache the result yet
615 $workCallback(); // work now to block for less time in waitForAll()
617 // If the positions failed to write to the stash, at least wait on local datacenter
618 // replica DBs to catch up before responding. Even if there are several DCs, this increases
619 // the chance that the user will see their own changes immediately afterwards. As long
620 // as the sticky DC cookie applies (same domain), this is not even an issue.
621 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
622 $masterName = $lb->getServerName( $lb->getWriterIndex() );
623 if ( isset( $unsavedPositions[$masterName] ) ) {
624 $lb->waitForAll( $unsavedPositions[$masterName] );
630 * Base parameters to LoadBalancer::__construct()
633 final protected function baseLoadBalancerParams() {
635 'localDomain' => $this->localDomain
,
636 'readOnlyReason' => $this->readOnlyReason
,
637 'srvCache' => $this->srvCache
,
638 'wanCache' => $this->wanCache
,
639 'profiler' => $this->profiler
,
640 'trxProfiler' => $this->trxProfiler
,
641 'queryLogger' => $this->queryLogger
,
642 'connLogger' => $this->connLogger
,
643 'replLogger' => $this->replLogger
,
644 'errorLogger' => $this->errorLogger
,
645 'hostname' => $this->hostname
,
646 'cliMode' => $this->cliMode
,
647 'agent' => $this->agent
652 * @param ILoadBalancer $lb
654 protected function initLoadBalancer( ILoadBalancer
$lb ) {
655 if ( $this->trxRoundId
!== false ) {
656 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
661 * Set a new table prefix for the existing local domain ID for testing
663 * @param string $prefix
666 public function setDomainPrefix( $prefix ) {
667 $this->localDomain
= new DatabaseDomain(
668 $this->localDomain
->getDatabase(),
673 $this->forEachLB( function( LoadBalancer
$lb ) use ( $prefix ) {
674 $lb->setDomainPrefix( $prefix );
679 * Close all open database connections on all open load balancers.
682 public function closeAll() {
683 $this->forEachLBCallMethod( 'closeAll', [] );
687 * @param string $agent Agent name for query profiling
690 public function setAgentName( $agent ) {
691 $this->agent
= $agent;
695 * Append ?cpPosTime parameter to a URL for ChronologyProtector purposes if needed
697 * Note that unlike cookies, this works accross domains
700 * @param float $time UNIX timestamp just before shutdown() was called
704 public function appendPreShutdownTimeAsQuery( $url, $time ) {
706 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$usedCluster ) {
707 $usedCluster |
= ( $lb->getServerCount() > 1 );
710 if ( !$usedCluster ) {
711 return $url; // no master/replica clusters touched
714 return strpos( $url, '?' ) === false ?
"$url?cpPosTime=$time" : "$url&cpPosTime=$time";
718 * @param array $info Map of fields, including:
719 * - IPAddress : IP address
720 * - UserAgent : User-Agent HTTP header
721 * - ChronologyProtection : cookie/header value specifying ChronologyProtector usage
724 public function setRequestInfo( array $info ) {
725 $this->requestInfo
= $info +
$this->requestInfo
;
728 function __destruct() {