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 TransactionProfiler */
34 protected $trxProfiler;
35 /** @var LoggerInterface */
36 protected $replLogger;
37 /** @var LoggerInterface */
38 protected $connLogger;
39 /** @var LoggerInterface */
40 protected $queryLogger;
41 /** @var LoggerInterface */
42 protected $perfLogger;
43 /** @var callable Error logger */
44 protected $errorLogger;
49 /** @var WANObjectCache */
52 /** @var string Local domain */
54 /** @var string Local hostname of the app server */
58 /** @var string|bool String if a requested DBO_TRX transaction round is active */
59 protected $trxRoundId = false;
60 /** @var string|bool Reason all LBs are read-only or false if not */
61 protected $readOnlyReason = false;
62 /** @var callable[] */
63 protected $replicationWaitCallbacks = [];
65 const SHUTDOWN_NO_CHRONPROT
= 0; // don't save DB positions at all
66 const SHUTDOWN_CHRONPROT_ASYNC
= 1; // save DB positions, but don't wait on remote DCs
67 const SHUTDOWN_CHRONPROT_SYNC
= 2; // save DB positions, waiting on all DCs
69 private static $loggerFields =
70 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
73 * @TODO: document base params here
76 public function __construct( array $conf ) {
77 $this->domain
= isset( $conf['domain'] ) ?
$conf['domain'] : '';
78 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
79 $this->readOnlyReason
= $conf['readOnlyReason'];
82 $this->srvCache
= isset( $conf['srvCache'] ) ?
$conf['srvCache'] : new EmptyBagOStuff();
83 $this->memCache
= isset( $conf['memCache'] ) ?
$conf['memCache'] : new EmptyBagOStuff();
84 $this->wanCache
= isset( $conf['wanCache'] )
86 : WANObjectCache
::newEmpty();
88 foreach ( self
::$loggerFields as $key ) {
89 $this->$key = isset( $conf[$key] ) ?
$conf[$key] : new \Psr\Log\
NullLogger();
91 $this->errorLogger
= isset( $conf['errorLogger'] )
92 ?
$conf['errorLogger']
93 : function ( Exception
$e ) {
94 trigger_error( E_WARNING
, $e->getMessage() );
96 $this->hostname
= isset( $conf['hostname'] )
100 $this->chronProt
= isset( $conf['chronProt'] )
102 : $this->newChronologyProtector();
103 $this->trxProfiler
= isset( $conf['trxProfiler'] )
104 ?
$conf['trxProfiler']
105 : new TransactionProfiler();
107 $this->ticket
= mt_rand();
111 * Disables all load balancers. All connections are closed, and any attempt to
112 * open a new connection will result in a DBAccessError.
113 * @see LoadBalancer::disable()
115 public function destroy() {
116 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
117 $this->forEachLBCallMethod( 'disable' );
121 * Create a new load balancer object. The resulting object will be untracked,
122 * not chronology-protected, and the caller is responsible for cleaning it up.
124 * @param bool|string $domain Wiki ID, or false for the current wiki
125 * @return ILoadBalancer
127 abstract public function newMainLB( $domain = false );
130 * Get a cached (tracked) load balancer object.
132 * @param bool|string $domain Wiki ID, or false for the current wiki
133 * @return ILoadBalancer
135 abstract public function getMainLB( $domain = false );
138 * Create a new load balancer for external storage. The resulting object will be
139 * untracked, not chronology-protected, and the caller is responsible for
142 * @param string $cluster External storage cluster, or false for core
143 * @param bool|string $domain Wiki ID, or false for the current wiki
144 * @return ILoadBalancer
146 abstract protected function newExternalLB( $cluster, $domain = false );
149 * Get a cached (tracked) load balancer for external storage
151 * @param string $cluster External storage cluster, or false for core
152 * @param bool|string $domain Wiki ID, or false for the current wiki
153 * @return ILoadBalancer
155 abstract public function getExternalLB( $cluster, $domain = false );
158 * Execute a function for each tracked load balancer
159 * The callback is called with the load balancer as the first parameter,
160 * and $params passed as the subsequent parameters.
162 * @param callable $callback
163 * @param array $params
165 abstract public function forEachLB( $callback, array $params = [] );
168 * Prepare all tracked load balancers for shutdown
169 * @param integer $mode One of the class SHUTDOWN_* constants
170 * @param callable|null $workCallback Work to mask ChronologyProtector writes
172 public function shutdown(
173 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null
175 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
176 $this->shutdownChronologyProtector( $this->chronProt
, $workCallback, 'sync' );
177 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
178 $this->shutdownChronologyProtector( $this->chronProt
, null, 'async' );
181 $this->commitMasterChanges( __METHOD__
); // sanity
185 * Call a method of each tracked load balancer
187 * @param string $methodName
190 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
192 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
193 call_user_func_array( [ $loadBalancer, $methodName ], $args );
195 [ $methodName, $args ]
200 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
202 * @param string $fname Caller name
205 public function flushReplicaSnapshots( $fname = __METHOD__
) {
206 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
210 * Commit on all connections. Done for two reasons:
211 * 1. To commit changes to the masters.
212 * 2. To release the snapshot on all connections, master and replica DB.
213 * @param string $fname Caller name
214 * @param array $options Options map:
215 * - maxWriteDuration: abort if more than this much time was spent in write queries
217 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
218 $this->commitMasterChanges( $fname, $options );
219 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
223 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
225 * The DBO_TRX setting will be reverted to the default in each of these methods:
226 * - commitMasterChanges()
227 * - rollbackMasterChanges()
230 * This allows for custom transaction rounds from any outer transaction scope.
232 * @param string $fname
233 * @throws DBTransactionError
236 public function beginMasterChanges( $fname = __METHOD__
) {
237 if ( $this->trxRoundId
!== false ) {
238 throw new DBTransactionError(
240 "$fname: transaction round '{$this->trxRoundId}' already started."
243 $this->trxRoundId
= $fname;
244 // Set DBO_TRX flags on all appropriate DBs
245 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
249 * Commit changes on all master connections
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
255 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
256 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
257 throw new DBTransactionError(
259 "$fname: transaction round '{$this->trxRoundId}' still running."
262 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
263 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
264 $this->trxRoundId
= false;
265 // Perform pre-commit checks, aborting on failure
266 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
267 // Log the DBs and methods involved in multi-DB transactions
268 $this->logIfMultiDbTransaction();
269 // Actually perform the commit on all master DB connections and revert DBO_TRX
270 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
271 // Run all post-commit callbacks
272 /** @var Exception $e */
273 $e = null; // first callback exception
274 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
275 $ex = $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_COMMIT
);
278 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
279 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
280 // Throw any last post-commit callback error
281 if ( $e instanceof Exception
) {
287 * Rollback changes on all master connections
288 * @param string $fname Caller name
291 public function rollbackMasterChanges( $fname = __METHOD__
) {
292 $this->trxRoundId
= false;
293 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
294 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
295 // Run all post-rollback callbacks
296 $this->forEachLB( function ( ILoadBalancer
$lb ) {
297 $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_ROLLBACK
);
302 * Log query info if multi DB transactions are going to be committed now
304 private function logIfMultiDbTransaction() {
306 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
307 $masterName = $lb->getServerName( $lb->getWriterIndex() );
308 $callers = $lb->pendingMasterChangeCallers();
310 $callersByDB[$masterName] = $callers;
314 if ( count( $callersByDB ) >= 2 ) {
315 $dbs = implode( ', ', array_keys( $callersByDB ) );
316 $msg = "Multi-DB transaction [{$dbs}]:\n";
317 foreach ( $callersByDB as $db => $callers ) {
318 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
320 $this->queryLogger
->info( $msg );
325 * Determine if any master connection has pending changes
329 public function hasMasterChanges() {
331 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
332 $ret = $ret ||
$lb->hasMasterChanges();
339 * Detemine if any lagged replica DB connection was used
343 public function laggedReplicaUsed() {
345 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
346 $ret = $ret ||
$lb->laggedReplicaUsed();
353 * Determine if any master connection has pending/written changes from this request
354 * @param float $age How many seconds ago is "recent" [defaults to LB lag wait timeout]
358 public function hasOrMadeRecentMasterChanges( $age = null ) {
360 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
361 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
367 * Waits for the replica DBs to catch up to the current master position
369 * Use this when updating very large numbers of rows, as in maintenance scripts,
370 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
372 * By default this waits on all DB clusters actually used in this request.
373 * This makes sense when lag being waiting on is caused by the code that does this check.
374 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
375 * that were not changed since the last wait check. To forcefully wait on a specific cluster
376 * for a given wiki, use the 'wiki' parameter. To forcefully wait on an "external" cluster,
377 * use the "cluster" parameter.
379 * Never call this function after a large DB write that is *still* in a transaction.
380 * It only makes sense to call this after the possible lag inducing changes were committed.
382 * @param array $opts Optional fields that include:
383 * - wiki : wait on the load balancer DBs that handles the given wiki
384 * - cluster : wait on the given external load balancer DBs
385 * - timeout : Max wait time. Default: ~60 seconds
386 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
387 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
390 public function waitForReplication( array $opts = [] ) {
395 'ifWritesSince' => null
398 // Figure out which clusters need to be checked
399 /** @var ILoadBalancer[] $lbs */
401 if ( $opts['cluster'] !== false ) {
402 $lbs[] = $this->getExternalLB( $opts['cluster'] );
403 } elseif ( $opts['wiki'] !== false ) {
404 $lbs[] = $this->getMainLB( $opts['wiki'] );
406 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
410 return; // nothing actually used
414 // Get all the master positions of applicable DBs right now.
415 // This can be faster since waiting on one cluster reduces the
416 // time needed to wait on the next clusters.
417 $masterPositions = array_fill( 0, count( $lbs ), false );
418 foreach ( $lbs as $i => $lb ) {
419 if ( $lb->getServerCount() <= 1 ) {
420 // Bug 27975 - Don't try to wait for replica DBs if there are none
421 // Prevents permission error when getting master position
423 } elseif ( $opts['ifWritesSince']
424 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
426 continue; // no writes since the last wait
428 $masterPositions[$i] = $lb->getMasterPos();
431 // Run any listener callbacks *after* getting the DB positions. The more
432 // time spent in the callbacks, the less time is spent in waitForAll().
433 foreach ( $this->replicationWaitCallbacks
as $callback ) {
438 foreach ( $lbs as $i => $lb ) {
439 if ( $masterPositions[$i] ) {
440 // The DBMS may not support getMasterPos() or the whole
441 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
442 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
443 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
449 throw new DBReplicationWaitError(
450 "Could not wait for replica DBs to catch up to " .
451 implode( ', ', $failed )
457 * Add a callback to be run in every call to waitForReplication() before waiting
459 * Callbacks must clear any transactions that they start
461 * @param string $name Callback name
462 * @param callable|null $callback Use null to unset a callback
465 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
467 $this->replicationWaitCallbacks
[$name] = $callback;
469 unset( $this->replicationWaitCallbacks
[$name] );
474 * Get a token asserting that no transaction writes are active
476 * @param string $fname Caller name (e.g. __METHOD__)
477 * @return mixed A value to pass to commitAndWaitForReplication()
480 public function getEmptyTransactionTicket( $fname ) {
481 if ( $this->hasMasterChanges() ) {
482 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope." );
486 return $this->ticket
;
490 * Convenience method for safely running commitMasterChanges()/waitForReplication()
492 * This will commit and wait unless $ticket indicates it is unsafe to do so
494 * @param string $fname Caller name (e.g. __METHOD__)
495 * @param mixed $ticket Result of getEmptyTransactionTicket()
496 * @param array $opts Options to waitForReplication()
497 * @throws DBReplicationWaitError
500 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
501 if ( $ticket !== $this->ticket
) {
502 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope." );
506 // The transaction owner and any caller with the empty transaction ticket can commit
507 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
508 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
509 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
510 $fnameEffective = $this->trxRoundId
;
512 $fnameEffective = $fname;
515 $this->commitMasterChanges( $fnameEffective );
516 $this->waitForReplication( $opts );
517 // If a nested caller committed on behalf of $fname, start another empty $fname
518 // transaction, leaving the caller with the same empty transaction state as before.
519 if ( $fnameEffective !== $fname ) {
520 $this->beginMasterChanges( $fnameEffective );
525 * @param string $dbName DB master name (e.g. "db1052")
526 * @return float|bool UNIX timestamp when client last touched the DB or false if not recent
529 public function getChronologyProtectorTouched( $dbName ) {
530 return $this->chronProt
->getTouched( $dbName );
534 * Disable the ChronologyProtector for all load balancers
536 * This can be called at the start of special API entry points
540 public function disableChronologyProtection() {
541 $this->chronProt
->setEnabled( false );
545 * @return ChronologyProtector
547 protected function newChronologyProtector() {
548 $chronProt = new ChronologyProtector(
551 'ip' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ?
$_SERVER[ 'REMOTE_ADDR' ] : '',
552 'agent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ?
$_SERVER['HTTP_USER_AGENT'] : ''
554 isset( $_GET['cpPosTime'] ) ?
$_GET['cpPosTime'] : null
556 $chronProt->setLogger( $this->replLogger
);
557 if ( PHP_SAPI
=== 'cli' ) {
558 $chronProt->setEnabled( false );
565 * Get and record all of the staged DB positions into persistent memory storage
567 * @param ChronologyProtector $cp
568 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
569 * @param string $mode One of (sync, async); whether to wait on remote datacenters
571 protected function shutdownChronologyProtector(
572 ChronologyProtector
$cp, $workCallback, $mode
574 // Record all the master positions needed
575 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
576 $cp->shutdownLB( $lb );
578 // Write them to the persistent stash. Try to do something useful by running $work
579 // while ChronologyProtector waits for the stash write to replicate to all DCs.
580 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
581 if ( $unsavedPositions && $workCallback ) {
582 // Invoke callback in case it did not cache the result yet
583 $workCallback(); // work now to block for less time in waitForAll()
585 // If the positions failed to write to the stash, at least wait on local datacenter
586 // replica DBs to catch up before responding. Even if there are several DCs, this increases
587 // the chance that the user will see their own changes immediately afterwards. As long
588 // as the sticky DC cookie applies (same domain), this is not even an issue.
589 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
590 $masterName = $lb->getServerName( $lb->getWriterIndex() );
591 if ( isset( $unsavedPositions[$masterName] ) ) {
592 $lb->waitForAll( $unsavedPositions[$masterName] );
598 * Base parameters to LoadBalancer::__construct()
601 final protected function baseLoadBalancerParams() {
603 'localDomain' => $this->domain
,
604 'readOnlyReason' => $this->readOnlyReason
,
605 'srvCache' => $this->srvCache
,
606 'wanCache' => $this->wanCache
,
607 'trxProfiler' => $this->trxProfiler
,
608 'queryLogger' => $this->queryLogger
,
609 'connLogger' => $this->connLogger
,
610 'replLogger' => $this->replLogger
,
611 'errorLogger' => $this->errorLogger
,
612 'hostname' => $this->hostname
617 * @param ILoadBalancer $lb
619 protected function initLoadBalancer( ILoadBalancer
$lb ) {
620 if ( $this->trxRoundId
!== false ) {
621 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
626 * Define a new local domain (for testing)
628 * Caller should make sure no local connection are open to the old local domain
630 * @param string $domain
633 public function setDomainPrefix( $domain ) {
634 $this->domain
= $domain;
638 * Close all open database connections on all open load balancers.
641 public function closeAll() {
642 $this->forEachLBCallMethod( 'closeAll', [] );