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 */
60 /** @var string|bool String if a requested DBO_TRX transaction round is active */
61 protected $trxRoundId = false;
62 /** @var string|bool Reason all LBs are read-only or false if not */
63 protected $readOnlyReason = false;
64 /** @var callable[] */
65 protected $replicationWaitCallbacks = [];
67 /** @var bool Whether this PHP instance is for a CLI script */
69 /** @var string Agent name for query profiling */
72 const SHUTDOWN_NO_CHRONPROT
= 0; // don't save DB positions at all
73 const SHUTDOWN_CHRONPROT_ASYNC
= 1; // save DB positions, but don't wait on remote DCs
74 const SHUTDOWN_CHRONPROT_SYNC
= 2; // save DB positions, waiting on all DCs
76 private static $loggerFields =
77 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
80 * @TODO: document base params here
83 public function __construct( array $conf ) {
84 $this->localDomain
= isset( $conf['localDomain'] )
85 ? DatabaseDomain
::newFromId( $conf['localDomain'] )
86 : DatabaseDomain
::newUnspecified();
88 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
89 $this->readOnlyReason
= $conf['readOnlyReason'];
92 $this->srvCache
= isset( $conf['srvCache'] ) ?
$conf['srvCache'] : new EmptyBagOStuff();
93 $this->memCache
= isset( $conf['memCache'] ) ?
$conf['memCache'] : new EmptyBagOStuff();
94 $this->wanCache
= isset( $conf['wanCache'] )
96 : WANObjectCache
::newEmpty();
98 foreach ( self
::$loggerFields as $key ) {
99 $this->$key = isset( $conf[$key] ) ?
$conf[$key] : new \Psr\Log\
NullLogger();
101 $this->errorLogger
= isset( $conf['errorLogger'] )
102 ?
$conf['errorLogger']
103 : function ( Exception
$e ) {
104 trigger_error( E_WARNING
, get_class( $e ) . ': ' . $e->getMessage() );
106 $this->hostname
= isset( $conf['hostname'] )
110 $this->chronProt
= isset( $conf['chronProt'] )
112 : $this->newChronologyProtector();
114 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
115 $this->trxProfiler
= isset( $conf['trxProfiler'] )
116 ?
$conf['trxProfiler']
117 : new TransactionProfiler();
119 $this->ticket
= mt_rand();
120 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
121 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
125 * Disables all load balancers. All connections are closed, and any attempt to
126 * open a new connection will result in a DBAccessError.
127 * @see LoadBalancer::disable()
129 public function destroy() {
130 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
131 $this->forEachLBCallMethod( 'disable' );
135 * Create a new load balancer object. The resulting object will be untracked,
136 * not chronology-protected, and the caller is responsible for cleaning it up.
138 * @param bool|string $domain Wiki ID, or false for the current wiki
139 * @return ILoadBalancer
141 abstract public function newMainLB( $domain = false );
144 * Get a cached (tracked) load balancer object.
146 * @param bool|string $domain Wiki ID, or false for the current wiki
147 * @return ILoadBalancer
149 abstract public function getMainLB( $domain = false );
152 * Create a new load balancer for external storage. The resulting object will be
153 * untracked, not chronology-protected, and the caller is responsible for
156 * @param string $cluster External storage cluster, or false for core
157 * @param bool|string $domain Wiki ID, or false for the current wiki
158 * @return ILoadBalancer
160 abstract protected function newExternalLB( $cluster, $domain = false );
163 * Get a cached (tracked) load balancer for external storage
165 * @param string $cluster External storage cluster, or false for core
166 * @param bool|string $domain Wiki ID, or false for the current wiki
167 * @return ILoadBalancer
169 abstract public function getExternalLB( $cluster, $domain = false );
172 * Execute a function for each tracked load balancer
173 * The callback is called with the load balancer as the first parameter,
174 * and $params passed as the subsequent parameters.
176 * @param callable $callback
177 * @param array $params
179 abstract public function forEachLB( $callback, array $params = [] );
182 * Prepare all tracked load balancers for shutdown
183 * @param integer $mode One of the class SHUTDOWN_* constants
184 * @param callable|null $workCallback Work to mask ChronologyProtector writes
186 public function shutdown(
187 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null
189 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
190 $this->shutdownChronologyProtector( $this->chronProt
, $workCallback, 'sync' );
191 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
192 $this->shutdownChronologyProtector( $this->chronProt
, null, 'async' );
195 $this->commitMasterChanges( __METHOD__
); // sanity
199 * Call a method of each tracked load balancer
201 * @param string $methodName
204 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
206 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
207 call_user_func_array( [ $loadBalancer, $methodName ], $args );
209 [ $methodName, $args ]
214 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
216 * @param string $fname Caller name
219 public function flushReplicaSnapshots( $fname = __METHOD__
) {
220 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
224 * Commit on all connections. Done for two reasons:
225 * 1. To commit changes to the masters.
226 * 2. To release the snapshot on all connections, master and replica DB.
227 * @param string $fname Caller name
228 * @param array $options Options map:
229 * - maxWriteDuration: abort if more than this much time was spent in write queries
231 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
232 $this->commitMasterChanges( $fname, $options );
233 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
237 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
239 * The DBO_TRX setting will be reverted to the default in each of these methods:
240 * - commitMasterChanges()
241 * - rollbackMasterChanges()
244 * This allows for custom transaction rounds from any outer transaction scope.
246 * @param string $fname
247 * @throws DBTransactionError
250 public function beginMasterChanges( $fname = __METHOD__
) {
251 if ( $this->trxRoundId
!== false ) {
252 throw new DBTransactionError(
254 "$fname: transaction round '{$this->trxRoundId}' already started."
257 $this->trxRoundId
= $fname;
258 // Set DBO_TRX flags on all appropriate DBs
259 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
263 * Commit changes on all master connections
264 * @param string $fname Caller name
265 * @param array $options Options map:
266 * - maxWriteDuration: abort if more than this much time was spent in write queries
269 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
270 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
271 throw new DBTransactionError(
273 "$fname: transaction round '{$this->trxRoundId}' still running."
276 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
277 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
278 $this->trxRoundId
= false;
279 // Perform pre-commit checks, aborting on failure
280 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
281 // Log the DBs and methods involved in multi-DB transactions
282 $this->logIfMultiDbTransaction();
283 // Actually perform the commit on all master DB connections and revert DBO_TRX
284 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
285 // Run all post-commit callbacks
286 /** @var Exception $e */
287 $e = null; // first callback exception
288 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e ) {
289 $ex = $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_COMMIT
);
292 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
293 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
294 // Throw any last post-commit callback error
295 if ( $e instanceof Exception
) {
301 * Rollback changes on all master connections
302 * @param string $fname Caller name
305 public function rollbackMasterChanges( $fname = __METHOD__
) {
306 $this->trxRoundId
= false;
307 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
308 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
309 // Run all post-rollback callbacks
310 $this->forEachLB( function ( ILoadBalancer
$lb ) {
311 $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_ROLLBACK
);
316 * Log query info if multi DB transactions are going to be committed now
318 private function logIfMultiDbTransaction() {
320 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
321 $masterName = $lb->getServerName( $lb->getWriterIndex() );
322 $callers = $lb->pendingMasterChangeCallers();
324 $callersByDB[$masterName] = $callers;
328 if ( count( $callersByDB ) >= 2 ) {
329 $dbs = implode( ', ', array_keys( $callersByDB ) );
330 $msg = "Multi-DB transaction [{$dbs}]:\n";
331 foreach ( $callersByDB as $db => $callers ) {
332 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
334 $this->queryLogger
->info( $msg );
339 * Determine if any master connection has pending changes
343 public function hasMasterChanges() {
345 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
346 $ret = $ret ||
$lb->hasMasterChanges();
353 * Detemine if any lagged replica DB connection was used
357 public function laggedReplicaUsed() {
359 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
360 $ret = $ret ||
$lb->laggedReplicaUsed();
367 * Determine if any master connection has pending/written changes from this request
368 * @param float $age How many seconds ago is "recent" [defaults to LB lag wait timeout]
372 public function hasOrMadeRecentMasterChanges( $age = null ) {
374 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
375 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
381 * Waits for the replica DBs to catch up to the current master position
383 * Use this when updating very large numbers of rows, as in maintenance scripts,
384 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
386 * By default this waits on all DB clusters actually used in this request.
387 * This makes sense when lag being waiting on is caused by the code that does this check.
388 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
389 * that were not changed since the last wait check. To forcefully wait on a specific cluster
390 * for a given wiki, use the 'wiki' parameter. To forcefully wait on an "external" cluster,
391 * use the "cluster" parameter.
393 * Never call this function after a large DB write that is *still* in a transaction.
394 * It only makes sense to call this after the possible lag inducing changes were committed.
396 * @param array $opts Optional fields that include:
397 * - wiki : wait on the load balancer DBs that handles the given wiki
398 * - cluster : wait on the given external load balancer DBs
399 * - timeout : Max wait time. Default: ~60 seconds
400 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
401 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
404 public function waitForReplication( array $opts = [] ) {
409 'ifWritesSince' => null
412 // Figure out which clusters need to be checked
413 /** @var ILoadBalancer[] $lbs */
415 if ( $opts['cluster'] !== false ) {
416 $lbs[] = $this->getExternalLB( $opts['cluster'] );
417 } elseif ( $opts['wiki'] !== false ) {
418 $lbs[] = $this->getMainLB( $opts['wiki'] );
420 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
424 return; // nothing actually used
428 // Get all the master positions of applicable DBs right now.
429 // This can be faster since waiting on one cluster reduces the
430 // time needed to wait on the next clusters.
431 $masterPositions = array_fill( 0, count( $lbs ), false );
432 foreach ( $lbs as $i => $lb ) {
433 if ( $lb->getServerCount() <= 1 ) {
434 // Bug 27975 - Don't try to wait for replica DBs if there are none
435 // Prevents permission error when getting master position
437 } elseif ( $opts['ifWritesSince']
438 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
440 continue; // no writes since the last wait
442 $masterPositions[$i] = $lb->getMasterPos();
445 // Run any listener callbacks *after* getting the DB positions. The more
446 // time spent in the callbacks, the less time is spent in waitForAll().
447 foreach ( $this->replicationWaitCallbacks
as $callback ) {
452 foreach ( $lbs as $i => $lb ) {
453 if ( $masterPositions[$i] ) {
454 // The DBMS may not support getMasterPos()
455 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
456 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
462 throw new DBReplicationWaitError(
463 "Could not wait for replica DBs to catch up to " .
464 implode( ', ', $failed )
470 * Add a callback to be run in every call to waitForReplication() before waiting
472 * Callbacks must clear any transactions that they start
474 * @param string $name Callback name
475 * @param callable|null $callback Use null to unset a callback
478 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
480 $this->replicationWaitCallbacks
[$name] = $callback;
482 unset( $this->replicationWaitCallbacks
[$name] );
487 * Get a token asserting that no transaction writes are active
489 * @param string $fname Caller name (e.g. __METHOD__)
490 * @return mixed A value to pass to commitAndWaitForReplication()
493 public function getEmptyTransactionTicket( $fname ) {
494 if ( $this->hasMasterChanges() ) {
495 $this->queryLogger
->error( __METHOD__
. ": $fname does not have outer scope." );
499 return $this->ticket
;
503 * Convenience method for safely running commitMasterChanges()/waitForReplication()
505 * This will commit and wait unless $ticket indicates it is unsafe to do so
507 * @param string $fname Caller name (e.g. __METHOD__)
508 * @param mixed $ticket Result of getEmptyTransactionTicket()
509 * @param array $opts Options to waitForReplication()
510 * @throws DBReplicationWaitError
513 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
514 if ( $ticket !== $this->ticket
) {
515 $this->perfLogger
->error( __METHOD__
. ": $fname does not have outer scope." );
519 // The transaction owner and any caller with the empty transaction ticket can commit
520 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
521 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
522 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
523 $fnameEffective = $this->trxRoundId
;
525 $fnameEffective = $fname;
528 $this->commitMasterChanges( $fnameEffective );
529 $this->waitForReplication( $opts );
530 // If a nested caller committed on behalf of $fname, start another empty $fname
531 // transaction, leaving the caller with the same empty transaction state as before.
532 if ( $fnameEffective !== $fname ) {
533 $this->beginMasterChanges( $fnameEffective );
538 * @param string $dbName DB master name (e.g. "db1052")
539 * @return float|bool UNIX timestamp when client last touched the DB or false if not recent
542 public function getChronologyProtectorTouched( $dbName ) {
543 return $this->chronProt
->getTouched( $dbName );
547 * Disable the ChronologyProtector for all load balancers
549 * This can be called at the start of special API entry points
553 public function disableChronologyProtection() {
554 $this->chronProt
->setEnabled( false );
558 * @return ChronologyProtector
560 protected function newChronologyProtector() {
561 $chronProt = new ChronologyProtector(
564 'ip' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ?
$_SERVER[ 'REMOTE_ADDR' ] : '',
565 'agent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ?
$_SERVER['HTTP_USER_AGENT'] : ''
567 isset( $_GET['cpPosTime'] ) ?
$_GET['cpPosTime'] : null
569 $chronProt->setLogger( $this->replLogger
);
570 if ( $this->cliMode
) {
571 $chronProt->setEnabled( false );
578 * Get and record all of the staged DB positions into persistent memory storage
580 * @param ChronologyProtector $cp
581 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
582 * @param string $mode One of (sync, async); whether to wait on remote datacenters
584 protected function shutdownChronologyProtector(
585 ChronologyProtector
$cp, $workCallback, $mode
587 // Record all the master positions needed
588 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
589 $cp->shutdownLB( $lb );
591 // Write them to the persistent stash. Try to do something useful by running $work
592 // while ChronologyProtector waits for the stash write to replicate to all DCs.
593 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
594 if ( $unsavedPositions && $workCallback ) {
595 // Invoke callback in case it did not cache the result yet
596 $workCallback(); // work now to block for less time in waitForAll()
598 // If the positions failed to write to the stash, at least wait on local datacenter
599 // replica DBs to catch up before responding. Even if there are several DCs, this increases
600 // the chance that the user will see their own changes immediately afterwards. As long
601 // as the sticky DC cookie applies (same domain), this is not even an issue.
602 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
603 $masterName = $lb->getServerName( $lb->getWriterIndex() );
604 if ( isset( $unsavedPositions[$masterName] ) ) {
605 $lb->waitForAll( $unsavedPositions[$masterName] );
611 * Base parameters to LoadBalancer::__construct()
614 final protected function baseLoadBalancerParams() {
616 'localDomain' => $this->localDomain
,
617 'readOnlyReason' => $this->readOnlyReason
,
618 'srvCache' => $this->srvCache
,
619 'wanCache' => $this->wanCache
,
620 'profiler' => $this->profiler
,
621 'trxProfiler' => $this->trxProfiler
,
622 'queryLogger' => $this->queryLogger
,
623 'connLogger' => $this->connLogger
,
624 'replLogger' => $this->replLogger
,
625 'errorLogger' => $this->errorLogger
,
626 'hostname' => $this->hostname
,
627 'cliMode' => $this->cliMode
,
628 'agent' => $this->agent
633 * @param ILoadBalancer $lb
635 protected function initLoadBalancer( ILoadBalancer
$lb ) {
636 if ( $this->trxRoundId
!== false ) {
637 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
642 * Set a new table prefix for the existing local domain ID for testing
644 * @param string $prefix
647 public function setDomainPrefix( $prefix ) {
648 $this->localDomain
= new DatabaseDomain(
649 $this->localDomain
->getDatabase(),
654 $this->forEachLB( function( LoadBalancer
$lb ) use ( $prefix ) {
655 $lb->setDomainPrefix( $prefix );
660 * Close all open database connections on all open load balancers.
663 public function closeAll() {
664 $this->forEachLBCallMethod( 'closeAll', [] );
668 * @param string $agent Agent name for query profiling
671 public function setAgentName( $agent ) {
672 $this->agent
= $agent;