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 * Construct a manager of ILoadBalancer objects
85 * Sub-classes will extend the required keys in $conf with additional parameters
87 * @param $conf $params Array with keys:
88 * - localDomain: A DatabaseDomain or domain ID string.
89 * - readOnlyReason : Reason the master DB is read-only if so [optional]
90 * - srvCache : BagOStuff object for server cache [optional]
91 * - memCache : BagOStuff object for cluster memory cache [optional]
92 * - wanCache : WANObjectCache object [optional]
93 * - hostname : The name of the current server [optional]
94 * - cliMode: Whether the execution context is a CLI script. [optional]
95 * - profiler : Class name or instance with profileIn()/profileOut() methods. [optional]
96 * - trxProfiler: TransactionProfiler instance. [optional]
97 * - replLogger: PSR-3 logger instance. [optional]
98 * - connLogger: PSR-3 logger instance. [optional]
99 * - queryLogger: PSR-3 logger instance. [optional]
100 * - perfLogger: PSR-3 logger instance. [optional]
101 * - errorLogger : Callback that takes an Exception and logs it. [optional]
102 * @throws InvalidArgumentException
104 public function __construct( array $conf ) {
105 $this->localDomain
= isset( $conf['localDomain'] )
106 ? DatabaseDomain
::newFromId( $conf['localDomain'] )
107 : DatabaseDomain
::newUnspecified();
109 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
110 $this->readOnlyReason
= $conf['readOnlyReason'];
113 $this->srvCache
= isset( $conf['srvCache'] ) ?
$conf['srvCache'] : new EmptyBagOStuff();
114 $this->memCache
= isset( $conf['memCache'] ) ?
$conf['memCache'] : new EmptyBagOStuff();
115 $this->wanCache
= isset( $conf['wanCache'] )
117 : WANObjectCache
::newEmpty();
119 foreach ( self
::$loggerFields as $key ) {
120 $this->$key = isset( $conf[$key] ) ?
$conf[$key] : new \Psr\Log\
NullLogger();
122 $this->errorLogger
= isset( $conf['errorLogger'] )
123 ?
$conf['errorLogger']
124 : function ( Exception
$e ) {
125 trigger_error( E_WARNING
, get_class( $e ) . ': ' . $e->getMessage() );
128 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
129 $this->trxProfiler
= isset( $conf['trxProfiler'] )
130 ?
$conf['trxProfiler']
131 : new TransactionProfiler();
133 $this->requestInfo
= [
134 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ?
$_SERVER[ 'REMOTE_ADDR' ] : '',
135 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ?
$_SERVER['HTTP_USER_AGENT'] : '',
136 'ChronologyProtection' => 'true'
139 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
140 $this->hostname
= isset( $conf['hostname'] ) ?
$conf['hostname'] : gethostname();
141 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
143 $this->ticket
= mt_rand();
147 * Disables all load balancers. All connections are closed, and any attempt to
148 * open a new connection will result in a DBAccessError.
149 * @see ILoadBalancer::disable()
151 public function destroy() {
152 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
153 $this->forEachLBCallMethod( 'disable' );
157 * Create a new load balancer object. The resulting object will be untracked,
158 * not chronology-protected, and the caller is responsible for cleaning it up.
160 * @param bool|string $domain Domain ID, or false for the current domain
161 * @return ILoadBalancer
163 abstract public function newMainLB( $domain = false );
166 * Get a cached (tracked) load balancer object.
168 * @param bool|string $domain Domain ID, or false for the current domain
169 * @return ILoadBalancer
171 abstract public function getMainLB( $domain = false );
174 * Create a new load balancer for external storage. The resulting object will be
175 * untracked, not chronology-protected, and the caller is responsible for
178 * @param string $cluster External storage cluster, or false for core
179 * @param bool|string $domain Domain ID, or false for the current domain
180 * @return ILoadBalancer
182 abstract protected function newExternalLB( $cluster, $domain = false );
185 * Get a cached (tracked) load balancer for external storage
187 * @param string $cluster External storage cluster, or false for core
188 * @param bool|string $domain Domain ID, or false for the current domain
189 * @return ILoadBalancer
191 abstract public function getExternalLB( $cluster, $domain = false );
194 * Execute a function for each tracked load balancer
195 * The callback is called with the load balancer as the first parameter,
196 * and $params passed as the subsequent parameters.
198 * @param callable $callback
199 * @param array $params
201 abstract public function forEachLB( $callback, array $params = [] );
204 * Prepare all tracked load balancers for shutdown
205 * @param integer $mode One of the class SHUTDOWN_* constants
206 * @param callable|null $workCallback Work to mask ChronologyProtector writes
208 public function shutdown(
209 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null
211 $chronProt = $this->getChronologyProtector();
212 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
213 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync' );
214 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
215 $this->shutdownChronologyProtector( $chronProt, null, 'async' );
218 $this->commitMasterChanges( __METHOD__
); // sanity
222 * Call a method of each tracked load balancer
224 * @param string $methodName
227 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
229 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
230 call_user_func_array( [ $loadBalancer, $methodName ], $args );
232 [ $methodName, $args ]
237 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
239 * @param string $fname Caller name
242 public function flushReplicaSnapshots( $fname = __METHOD__
) {
243 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
247 * Commit on all connections. Done for two reasons:
248 * 1. To commit changes to the masters.
249 * 2. To release the snapshot on all connections, master and replica DB.
250 * @param string $fname Caller name
251 * @param array $options Options map:
252 * - maxWriteDuration: abort if more than this much time was spent in write queries
254 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
255 $this->commitMasterChanges( $fname, $options );
256 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
260 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
262 * The DBO_TRX setting will be reverted to the default in each of these methods:
263 * - commitMasterChanges()
264 * - rollbackMasterChanges()
267 * This allows for custom transaction rounds from any outer transaction scope.
269 * @param string $fname
270 * @throws DBTransactionError
273 public function beginMasterChanges( $fname = __METHOD__
) {
274 if ( $this->trxRoundId
!== false ) {
275 throw new DBTransactionError(
277 "$fname: transaction round '{$this->trxRoundId}' already started."
280 $this->trxRoundId
= $fname;
281 // Set DBO_TRX flags on all appropriate DBs
282 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
286 * Commit changes on all master connections
287 * @param string $fname Caller name
288 * @param array $options Options map:
289 * - maxWriteDuration: abort if more than this much time was spent in write queries
292 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
293 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
294 throw new DBTransactionError(
296 "$fname: transaction round '{$this->trxRoundId}' still running."
299 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
300 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
301 $this->trxRoundId
= false;
302 // Perform pre-commit checks, aborting on failure
303 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
304 // Log the DBs and methods involved in multi-DB transactions
305 $this->logIfMultiDbTransaction();
306 // Actually perform the commit on all master DB connections and revert DBO_TRX
307 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
308 // Run all post-commit callbacks
309 /** @var Exception $e */
310 $e = null; // first callback exception
311 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
312 $ex = $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_COMMIT
);
315 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
316 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
317 // Throw any last post-commit callback error
318 if ( $e instanceof Exception
) {
324 * Rollback changes on all master connections
325 * @param string $fname Caller name
328 public function rollbackMasterChanges( $fname = __METHOD__
) {
329 $this->trxRoundId
= false;
330 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
331 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
332 // Run all post-rollback callbacks
333 $this->forEachLB( function ( ILoadBalancer
$lb ) {
334 $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_ROLLBACK
);
339 * Log query info if multi DB transactions are going to be committed now
341 private function logIfMultiDbTransaction() {
343 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
344 $masterName = $lb->getServerName( $lb->getWriterIndex() );
345 $callers = $lb->pendingMasterChangeCallers();
347 $callersByDB[$masterName] = $callers;
351 if ( count( $callersByDB ) >= 2 ) {
352 $dbs = implode( ', ', array_keys( $callersByDB ) );
353 $msg = "Multi-DB transaction [{$dbs}]:\n";
354 foreach ( $callersByDB as $db => $callers ) {
355 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
357 $this->queryLogger
->info( $msg );
362 * Determine if any master connection has pending changes
366 public function hasMasterChanges() {
368 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
369 $ret = $ret ||
$lb->hasMasterChanges();
376 * Detemine if any lagged replica DB connection was used
380 public function laggedReplicaUsed() {
382 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
383 $ret = $ret ||
$lb->laggedReplicaUsed();
390 * Determine if any master connection has pending/written changes from this request
391 * @param float $age How many seconds ago is "recent" [defaults to LB lag wait timeout]
395 public function hasOrMadeRecentMasterChanges( $age = null ) {
397 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
398 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
404 * Waits for the replica DBs to catch up to the current master position
406 * Use this when updating very large numbers of rows, as in maintenance scripts,
407 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
409 * By default this waits on all DB clusters actually used in this request.
410 * This makes sense when lag being waiting on is caused by the code that does this check.
411 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
412 * that were not changed since the last wait check. To forcefully wait on a specific cluster
413 * for a given domain, use the 'domain' parameter. To forcefully wait on an "external" cluster,
414 * use the "cluster" parameter.
416 * Never call this function after a large DB write that is *still* in a transaction.
417 * It only makes sense to call this after the possible lag inducing changes were committed.
419 * @param array $opts Optional fields that include:
420 * - domain : wait on the load balancer DBs that handles the given domain ID
421 * - cluster : wait on the given external load balancer DBs
422 * - timeout : Max wait time. Default: ~60 seconds
423 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
424 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
427 public function waitForReplication( array $opts = [] ) {
432 'ifWritesSince' => null
435 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
436 $opts['domain'] = $opts['wiki']; // b/c
439 // Figure out which clusters need to be checked
440 /** @var ILoadBalancer[] $lbs */
442 if ( $opts['cluster'] !== false ) {
443 $lbs[] = $this->getExternalLB( $opts['cluster'] );
444 } elseif ( $opts['domain'] !== false ) {
445 $lbs[] = $this->getMainLB( $opts['domain'] );
447 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
451 return; // nothing actually used
455 // Get all the master positions of applicable DBs right now.
456 // This can be faster since waiting on one cluster reduces the
457 // time needed to wait on the next clusters.
458 $masterPositions = array_fill( 0, count( $lbs ), false );
459 foreach ( $lbs as $i => $lb ) {
460 if ( $lb->getServerCount() <= 1 ) {
461 // Bug 27975 - Don't try to wait for replica DBs if there are none
462 // Prevents permission error when getting master position
464 } elseif ( $opts['ifWritesSince']
465 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
467 continue; // no writes since the last wait
469 $masterPositions[$i] = $lb->getMasterPos();
472 // Run any listener callbacks *after* getting the DB positions. The more
473 // time spent in the callbacks, the less time is spent in waitForAll().
474 foreach ( $this->replicationWaitCallbacks
as $callback ) {
479 foreach ( $lbs as $i => $lb ) {
480 if ( $masterPositions[$i] ) {
481 // The DBMS may not support getMasterPos()
482 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
483 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
489 throw new DBReplicationWaitError(
490 "Could not wait for replica DBs to catch up to " .
491 implode( ', ', $failed )
497 * Add a callback to be run in every call to waitForReplication() before waiting
499 * Callbacks must clear any transactions that they start
501 * @param string $name Callback name
502 * @param callable|null $callback Use null to unset a callback
505 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
507 $this->replicationWaitCallbacks
[$name] = $callback;
509 unset( $this->replicationWaitCallbacks
[$name] );
514 * Get a token asserting that no transaction writes are active
516 * @param string $fname Caller name (e.g. __METHOD__)
517 * @return mixed A value to pass to commitAndWaitForReplication()
520 public function getEmptyTransactionTicket( $fname ) {
521 if ( $this->hasMasterChanges() ) {
522 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope." );
526 return $this->ticket
;
530 * Convenience method for safely running commitMasterChanges()/waitForReplication()
532 * This will commit and wait unless $ticket indicates it is unsafe to do so
534 * @param string $fname Caller name (e.g. __METHOD__)
535 * @param mixed $ticket Result of getEmptyTransactionTicket()
536 * @param array $opts Options to waitForReplication()
537 * @throws DBReplicationWaitError
540 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
541 if ( $ticket !== $this->ticket
) {
542 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope." );
546 // The transaction owner and any caller with the empty transaction ticket can commit
547 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
548 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
549 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
550 $fnameEffective = $this->trxRoundId
;
552 $fnameEffective = $fname;
555 $this->commitMasterChanges( $fnameEffective );
556 $this->waitForReplication( $opts );
557 // If a nested caller committed on behalf of $fname, start another empty $fname
558 // transaction, leaving the caller with the same empty transaction state as before.
559 if ( $fnameEffective !== $fname ) {
560 $this->beginMasterChanges( $fnameEffective );
565 * @param string $dbName DB master name (e.g. "db1052")
566 * @return float|bool UNIX timestamp when client last touched the DB or false if not recent
569 public function getChronologyProtectorTouched( $dbName ) {
570 return $this->getChronologyProtector()->getTouched( $dbName );
574 * Disable the ChronologyProtector for all load balancers
576 * This can be called at the start of special API entry points
580 public function disableChronologyProtection() {
581 $this->getChronologyProtector()->setEnabled( false );
585 * @return ChronologyProtector
587 protected function getChronologyProtector() {
588 if ( $this->chronProt
) {
589 return $this->chronProt
;
592 $this->chronProt
= new ChronologyProtector(
595 'ip' => $this->requestInfo
['IPAddress'],
596 'agent' => $this->requestInfo
['UserAgent'],
598 isset( $_GET['cpPosTime'] ) ?
$_GET['cpPosTime'] : null
600 $this->chronProt
->setLogger( $this->replLogger
);
602 if ( $this->cliMode
) {
603 $this->chronProt
->setEnabled( false );
604 } elseif ( $this->requestInfo
['ChronologyProtection'] === 'false' ) {
605 // Request opted out of using position wait logic. This is useful for requests
606 // done by the job queue or background ETL that do not have a meaningful session.
607 $this->chronProt
->setWaitEnabled( false );
610 $this->replLogger
->debug( __METHOD__
. ': using request info ' .
611 json_encode( $this->requestInfo
, JSON_PRETTY_PRINT
) );
613 return $this->chronProt
;
617 * Get and record all of the staged DB positions into persistent memory storage
619 * @param ChronologyProtector $cp
620 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
621 * @param string $mode One of (sync, async); whether to wait on remote datacenters
623 protected function shutdownChronologyProtector(
624 ChronologyProtector
$cp, $workCallback, $mode
626 // Record all the master positions needed
627 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
628 $cp->shutdownLB( $lb );
630 // Write them to the persistent stash. Try to do something useful by running $work
631 // while ChronologyProtector waits for the stash write to replicate to all DCs.
632 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
633 if ( $unsavedPositions && $workCallback ) {
634 // Invoke callback in case it did not cache the result yet
635 $workCallback(); // work now to block for less time in waitForAll()
637 // If the positions failed to write to the stash, at least wait on local datacenter
638 // replica DBs to catch up before responding. Even if there are several DCs, this increases
639 // the chance that the user will see their own changes immediately afterwards. As long
640 // as the sticky DC cookie applies (same domain), this is not even an issue.
641 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
642 $masterName = $lb->getServerName( $lb->getWriterIndex() );
643 if ( isset( $unsavedPositions[$masterName] ) ) {
644 $lb->waitForAll( $unsavedPositions[$masterName] );
650 * Base parameters to LoadBalancer::__construct()
653 final protected function baseLoadBalancerParams() {
655 'localDomain' => $this->localDomain
,
656 'readOnlyReason' => $this->readOnlyReason
,
657 'srvCache' => $this->srvCache
,
658 'wanCache' => $this->wanCache
,
659 'profiler' => $this->profiler
,
660 'trxProfiler' => $this->trxProfiler
,
661 'queryLogger' => $this->queryLogger
,
662 'connLogger' => $this->connLogger
,
663 'replLogger' => $this->replLogger
,
664 'errorLogger' => $this->errorLogger
,
665 'hostname' => $this->hostname
,
666 'cliMode' => $this->cliMode
,
667 'agent' => $this->agent
672 * @param ILoadBalancer $lb
674 protected function initLoadBalancer( ILoadBalancer
$lb ) {
675 if ( $this->trxRoundId
!== false ) {
676 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
681 * Set a new table prefix for the existing local domain ID for testing
683 * @param string $prefix
686 public function setDomainPrefix( $prefix ) {
687 $this->localDomain
= new DatabaseDomain(
688 $this->localDomain
->getDatabase(),
693 $this->forEachLB( function( ILoadBalancer
$lb ) use ( $prefix ) {
694 $lb->setDomainPrefix( $prefix );
699 * Close all open database connections on all open load balancers.
702 public function closeAll() {
703 $this->forEachLBCallMethod( 'closeAll', [] );
707 * @param string $agent Agent name for query profiling
710 public function setAgentName( $agent ) {
711 $this->agent
= $agent;
715 * Append ?cpPosTime parameter to a URL for ChronologyProtector purposes if needed
717 * Note that unlike cookies, this works accross domains
720 * @param float $time UNIX timestamp just before shutdown() was called
724 public function appendPreShutdownTimeAsQuery( $url, $time ) {
726 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$usedCluster ) {
727 $usedCluster |
= ( $lb->getServerCount() > 1 );
730 if ( !$usedCluster ) {
731 return $url; // no master/replica clusters touched
734 return strpos( $url, '?' ) === false ?
"$url?cpPosTime=$time" : "$url&cpPosTime=$time";
738 * @param array $info Map of fields, including:
739 * - IPAddress : IP address
740 * - UserAgent : User-Agent HTTP header
741 * - ChronologyProtection : cookie/header value specifying ChronologyProtector usage
744 public function setRequestInfo( array $info ) {
745 $this->requestInfo
= $info +
$this->requestInfo
;
748 function __destruct() {