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 /** @var bool Whether this PHP instance is for a CLI script */
67 /** @var string Agent name for query profiling */
70 const SHUTDOWN_NO_CHRONPROT
= 0; // don't save DB positions at all
71 const SHUTDOWN_CHRONPROT_ASYNC
= 1; // save DB positions, but don't wait on remote DCs
72 const SHUTDOWN_CHRONPROT_SYNC
= 2; // save DB positions, waiting on all DCs
74 private static $loggerFields =
75 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
78 * @TODO: document base params here
81 public function __construct( array $conf ) {
82 $this->domain
= isset( $conf['domain'] ) ?
$conf['domain'] : '';
84 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
85 $this->readOnlyReason
= $conf['readOnlyReason'];
88 $this->srvCache
= isset( $conf['srvCache'] ) ?
$conf['srvCache'] : new EmptyBagOStuff();
89 $this->memCache
= isset( $conf['memCache'] ) ?
$conf['memCache'] : new EmptyBagOStuff();
90 $this->wanCache
= isset( $conf['wanCache'] )
92 : WANObjectCache
::newEmpty();
94 foreach ( self
::$loggerFields as $key ) {
95 $this->$key = isset( $conf[$key] ) ?
$conf[$key] : new \Psr\Log\
NullLogger();
97 $this->errorLogger
= isset( $conf['errorLogger'] )
98 ?
$conf['errorLogger']
99 : function ( Exception
$e ) {
100 trigger_error( E_WARNING
, get_class( $e ) . ': ' . $e->getMessage() );
102 $this->hostname
= isset( $conf['hostname'] )
106 $this->chronProt
= isset( $conf['chronProt'] )
108 : $this->newChronologyProtector();
109 $this->trxProfiler
= isset( $conf['trxProfiler'] )
110 ?
$conf['trxProfiler']
111 : new TransactionProfiler();
113 $this->ticket
= mt_rand();
114 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
115 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
119 * Disables all load balancers. All connections are closed, and any attempt to
120 * open a new connection will result in a DBAccessError.
121 * @see LoadBalancer::disable()
123 public function destroy() {
124 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
125 $this->forEachLBCallMethod( 'disable' );
129 * Create a new load balancer object. The resulting object will be untracked,
130 * not chronology-protected, and the caller is responsible for cleaning it up.
132 * @param bool|string $domain Wiki ID, or false for the current wiki
133 * @return ILoadBalancer
135 abstract public function newMainLB( $domain = false );
138 * Get a cached (tracked) load balancer object.
140 * @param bool|string $domain Wiki ID, or false for the current wiki
141 * @return ILoadBalancer
143 abstract public function getMainLB( $domain = false );
146 * Create a new load balancer for external storage. The resulting object will be
147 * untracked, not chronology-protected, and the caller is responsible for
150 * @param string $cluster External storage cluster, or false for core
151 * @param bool|string $domain Wiki ID, or false for the current wiki
152 * @return ILoadBalancer
154 abstract protected function newExternalLB( $cluster, $domain = false );
157 * Get a cached (tracked) load balancer for external storage
159 * @param string $cluster External storage cluster, or false for core
160 * @param bool|string $domain Wiki ID, or false for the current wiki
161 * @return ILoadBalancer
163 abstract public function getExternalLB( $cluster, $domain = false );
166 * Execute a function for each tracked load balancer
167 * The callback is called with the load balancer as the first parameter,
168 * and $params passed as the subsequent parameters.
170 * @param callable $callback
171 * @param array $params
173 abstract public function forEachLB( $callback, array $params = [] );
176 * Prepare all tracked load balancers for shutdown
177 * @param integer $mode One of the class SHUTDOWN_* constants
178 * @param callable|null $workCallback Work to mask ChronologyProtector writes
180 public function shutdown(
181 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null
183 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
184 $this->shutdownChronologyProtector( $this->chronProt
, $workCallback, 'sync' );
185 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
186 $this->shutdownChronologyProtector( $this->chronProt
, null, 'async' );
189 $this->commitMasterChanges( __METHOD__
); // sanity
193 * Call a method of each tracked load balancer
195 * @param string $methodName
198 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
200 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
201 call_user_func_array( [ $loadBalancer, $methodName ], $args );
203 [ $methodName, $args ]
208 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
210 * @param string $fname Caller name
213 public function flushReplicaSnapshots( $fname = __METHOD__
) {
214 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
218 * Commit on all connections. Done for two reasons:
219 * 1. To commit changes to the masters.
220 * 2. To release the snapshot on all connections, master and replica DB.
221 * @param string $fname Caller name
222 * @param array $options Options map:
223 * - maxWriteDuration: abort if more than this much time was spent in write queries
225 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
226 $this->commitMasterChanges( $fname, $options );
227 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
231 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
233 * The DBO_TRX setting will be reverted to the default in each of these methods:
234 * - commitMasterChanges()
235 * - rollbackMasterChanges()
238 * This allows for custom transaction rounds from any outer transaction scope.
240 * @param string $fname
241 * @throws DBTransactionError
244 public function beginMasterChanges( $fname = __METHOD__
) {
245 if ( $this->trxRoundId
!== false ) {
246 throw new DBTransactionError(
248 "$fname: transaction round '{$this->trxRoundId}' already started."
251 $this->trxRoundId
= $fname;
252 // Set DBO_TRX flags on all appropriate DBs
253 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
257 * Commit changes on all master connections
258 * @param string $fname Caller name
259 * @param array $options Options map:
260 * - maxWriteDuration: abort if more than this much time was spent in write queries
263 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
264 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
265 throw new DBTransactionError(
267 "$fname: transaction round '{$this->trxRoundId}' still running."
270 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
271 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
272 $this->trxRoundId
= false;
273 // Perform pre-commit checks, aborting on failure
274 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
275 // Log the DBs and methods involved in multi-DB transactions
276 $this->logIfMultiDbTransaction();
277 // Actually perform the commit on all master DB connections and revert DBO_TRX
278 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
279 // Run all post-commit callbacks
280 /** @var Exception $e */
281 $e = null; // first callback exception
282 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
283 $ex = $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_COMMIT
);
286 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
287 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
288 // Throw any last post-commit callback error
289 if ( $e instanceof Exception
) {
295 * Rollback changes on all master connections
296 * @param string $fname Caller name
299 public function rollbackMasterChanges( $fname = __METHOD__
) {
300 $this->trxRoundId
= false;
301 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
302 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
303 // Run all post-rollback callbacks
304 $this->forEachLB( function ( ILoadBalancer
$lb ) {
305 $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_ROLLBACK
);
310 * Log query info if multi DB transactions are going to be committed now
312 private function logIfMultiDbTransaction() {
314 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
315 $masterName = $lb->getServerName( $lb->getWriterIndex() );
316 $callers = $lb->pendingMasterChangeCallers();
318 $callersByDB[$masterName] = $callers;
322 if ( count( $callersByDB ) >= 2 ) {
323 $dbs = implode( ', ', array_keys( $callersByDB ) );
324 $msg = "Multi-DB transaction [{$dbs}]:\n";
325 foreach ( $callersByDB as $db => $callers ) {
326 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
328 $this->queryLogger
->info( $msg );
333 * Determine if any master connection has pending changes
337 public function hasMasterChanges() {
339 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
340 $ret = $ret ||
$lb->hasMasterChanges();
347 * Detemine if any lagged replica DB connection was used
351 public function laggedReplicaUsed() {
353 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
354 $ret = $ret ||
$lb->laggedReplicaUsed();
361 * Determine if any master connection has pending/written changes from this request
362 * @param float $age How many seconds ago is "recent" [defaults to LB lag wait timeout]
366 public function hasOrMadeRecentMasterChanges( $age = null ) {
368 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
369 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
375 * Waits for the replica DBs to catch up to the current master position
377 * Use this when updating very large numbers of rows, as in maintenance scripts,
378 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
380 * By default this waits on all DB clusters actually used in this request.
381 * This makes sense when lag being waiting on is caused by the code that does this check.
382 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
383 * that were not changed since the last wait check. To forcefully wait on a specific cluster
384 * for a given wiki, use the 'wiki' parameter. To forcefully wait on an "external" cluster,
385 * use the "cluster" parameter.
387 * Never call this function after a large DB write that is *still* in a transaction.
388 * It only makes sense to call this after the possible lag inducing changes were committed.
390 * @param array $opts Optional fields that include:
391 * - wiki : wait on the load balancer DBs that handles the given wiki
392 * - cluster : wait on the given external load balancer DBs
393 * - timeout : Max wait time. Default: ~60 seconds
394 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
395 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
398 public function waitForReplication( array $opts = [] ) {
403 'ifWritesSince' => null
406 // Figure out which clusters need to be checked
407 /** @var ILoadBalancer[] $lbs */
409 if ( $opts['cluster'] !== false ) {
410 $lbs[] = $this->getExternalLB( $opts['cluster'] );
411 } elseif ( $opts['wiki'] !== false ) {
412 $lbs[] = $this->getMainLB( $opts['wiki'] );
414 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
418 return; // nothing actually used
422 // Get all the master positions of applicable DBs right now.
423 // This can be faster since waiting on one cluster reduces the
424 // time needed to wait on the next clusters.
425 $masterPositions = array_fill( 0, count( $lbs ), false );
426 foreach ( $lbs as $i => $lb ) {
427 if ( $lb->getServerCount() <= 1 ) {
428 // Bug 27975 - Don't try to wait for replica DBs if there are none
429 // Prevents permission error when getting master position
431 } elseif ( $opts['ifWritesSince']
432 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
434 continue; // no writes since the last wait
436 $masterPositions[$i] = $lb->getMasterPos();
439 // Run any listener callbacks *after* getting the DB positions. The more
440 // time spent in the callbacks, the less time is spent in waitForAll().
441 foreach ( $this->replicationWaitCallbacks
as $callback ) {
446 foreach ( $lbs as $i => $lb ) {
447 if ( $masterPositions[$i] ) {
448 // The DBMS may not support getMasterPos() or the whole
449 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
450 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
451 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
457 throw new DBReplicationWaitError(
458 "Could not wait for replica DBs to catch up to " .
459 implode( ', ', $failed )
465 * Add a callback to be run in every call to waitForReplication() before waiting
467 * Callbacks must clear any transactions that they start
469 * @param string $name Callback name
470 * @param callable|null $callback Use null to unset a callback
473 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
475 $this->replicationWaitCallbacks
[$name] = $callback;
477 unset( $this->replicationWaitCallbacks
[$name] );
482 * Get a token asserting that no transaction writes are active
484 * @param string $fname Caller name (e.g. __METHOD__)
485 * @return mixed A value to pass to commitAndWaitForReplication()
488 public function getEmptyTransactionTicket( $fname ) {
489 if ( $this->hasMasterChanges() ) {
490 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope." );
494 return $this->ticket
;
498 * Convenience method for safely running commitMasterChanges()/waitForReplication()
500 * This will commit and wait unless $ticket indicates it is unsafe to do so
502 * @param string $fname Caller name (e.g. __METHOD__)
503 * @param mixed $ticket Result of getEmptyTransactionTicket()
504 * @param array $opts Options to waitForReplication()
505 * @throws DBReplicationWaitError
508 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
509 if ( $ticket !== $this->ticket
) {
510 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope." );
514 // The transaction owner and any caller with the empty transaction ticket can commit
515 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
516 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
517 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
518 $fnameEffective = $this->trxRoundId
;
520 $fnameEffective = $fname;
523 $this->commitMasterChanges( $fnameEffective );
524 $this->waitForReplication( $opts );
525 // If a nested caller committed on behalf of $fname, start another empty $fname
526 // transaction, leaving the caller with the same empty transaction state as before.
527 if ( $fnameEffective !== $fname ) {
528 $this->beginMasterChanges( $fnameEffective );
533 * @param string $dbName DB master name (e.g. "db1052")
534 * @return float|bool UNIX timestamp when client last touched the DB or false if not recent
537 public function getChronologyProtectorTouched( $dbName ) {
538 return $this->chronProt
->getTouched( $dbName );
542 * Disable the ChronologyProtector for all load balancers
544 * This can be called at the start of special API entry points
548 public function disableChronologyProtection() {
549 $this->chronProt
->setEnabled( false );
553 * @return ChronologyProtector
555 protected function newChronologyProtector() {
556 $chronProt = new ChronologyProtector(
559 'ip' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ?
$_SERVER[ 'REMOTE_ADDR' ] : '',
560 'agent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ?
$_SERVER['HTTP_USER_AGENT'] : ''
562 isset( $_GET['cpPosTime'] ) ?
$_GET['cpPosTime'] : null
564 $chronProt->setLogger( $this->replLogger
);
565 if ( $this->cliMode
) {
566 $chronProt->setEnabled( false );
573 * Get and record all of the staged DB positions into persistent memory storage
575 * @param ChronologyProtector $cp
576 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
577 * @param string $mode One of (sync, async); whether to wait on remote datacenters
579 protected function shutdownChronologyProtector(
580 ChronologyProtector
$cp, $workCallback, $mode
582 // Record all the master positions needed
583 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
584 $cp->shutdownLB( $lb );
586 // Write them to the persistent stash. Try to do something useful by running $work
587 // while ChronologyProtector waits for the stash write to replicate to all DCs.
588 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
589 if ( $unsavedPositions && $workCallback ) {
590 // Invoke callback in case it did not cache the result yet
591 $workCallback(); // work now to block for less time in waitForAll()
593 // If the positions failed to write to the stash, at least wait on local datacenter
594 // replica DBs to catch up before responding. Even if there are several DCs, this increases
595 // the chance that the user will see their own changes immediately afterwards. As long
596 // as the sticky DC cookie applies (same domain), this is not even an issue.
597 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
598 $masterName = $lb->getServerName( $lb->getWriterIndex() );
599 if ( isset( $unsavedPositions[$masterName] ) ) {
600 $lb->waitForAll( $unsavedPositions[$masterName] );
606 * Base parameters to LoadBalancer::__construct()
609 final protected function baseLoadBalancerParams() {
611 'localDomain' => $this->domain
,
612 'readOnlyReason' => $this->readOnlyReason
,
613 'srvCache' => $this->srvCache
,
614 'wanCache' => $this->wanCache
,
615 'trxProfiler' => $this->trxProfiler
,
616 'queryLogger' => $this->queryLogger
,
617 'connLogger' => $this->connLogger
,
618 'replLogger' => $this->replLogger
,
619 'errorLogger' => $this->errorLogger
,
620 'hostname' => $this->hostname
,
621 'cliMode' => $this->cliMode
,
622 'agent' => $this->agent
627 * @param ILoadBalancer $lb
629 protected function initLoadBalancer( ILoadBalancer
$lb ) {
630 if ( $this->trxRoundId
!== false ) {
631 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
636 * Define a new local domain (for testing)
638 * Caller should make sure no local connection are open to the old local domain
640 * @param string $domain
643 public function setDomainPrefix( $domain ) {
644 $this->domain
= $domain;
648 * Close all open database connections on all open load balancers.
651 public function closeAll() {
652 $this->forEachLBCallMethod( 'closeAll', [] );
656 * @param string $agent Agent name for query profiling
659 public function setAgentName( $agent ) {
660 $this->agent
= $agent;