3 * Generator 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
;
25 use MediaWiki\MediaWikiServices
;
26 use MediaWiki\Services\DestructibleService
;
27 use MediaWiki\Logger\LoggerFactory
;
30 * An interface for generating database load balancers
33 abstract class LBFactory
implements DestructibleService
{
34 /** @var ChronologyProtector */
36 /** @var TransactionProfiler */
37 protected $trxProfiler;
38 /** @var LoggerInterface */
40 /** @var LoggerInterface */
41 protected $replLogger;
44 /** @var WANObjectCache */
49 /** @var string|bool String if a requested DBO_TRX transaction round is active */
50 protected $trxRoundId = false;
51 /** @var string|bool Reason all LBs are read-only or false if not */
52 protected $readOnlyReason = false;
53 /** @var callable[] */
54 protected $replicationWaitCallbacks = [];
56 const SHUTDOWN_NO_CHRONPROT
= 0; // don't save DB positions at all
57 const SHUTDOWN_CHRONPROT_ASYNC
= 1; // save DB positions, but don't wait on remote DCs
58 const SHUTDOWN_CHRONPROT_SYNC
= 2; // save DB positions, waiting on all DCs
61 * Construct a factory based on a configuration array (typically from $wgLBFactoryConf)
63 * @TODO: inject objects via dependency framework
65 public function __construct( array $conf ) {
66 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
67 $this->readOnlyReason
= $conf['readOnlyReason'];
69 $this->chronProt
= $this->newChronologyProtector();
70 $this->trxProfiler
= Profiler
::instance()->getTransactionProfiler();
71 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
72 $cache = ObjectCache
::getLocalServerInstance();
73 if ( $cache->getQoS( $cache::ATTR_EMULATION
) > $cache::QOS_EMULATION_SQL
) {
74 $this->srvCache
= $cache;
76 $this->srvCache
= new EmptyBagOStuff();
78 $wCache = ObjectCache
::getMainWANInstance();
79 if ( $wCache->getQoS( $wCache::ATTR_EMULATION
) > $wCache::QOS_EMULATION_SQL
) {
80 $this->wanCache
= $wCache;
82 $this->wanCache
= WANObjectCache
::newEmpty();
84 $this->trxLogger
= LoggerFactory
::getInstance( 'DBTransaction' );
85 $this->replLogger
= LoggerFactory
::getInstance( 'DBReplication' );
86 $this->ticket
= mt_rand();
90 * Disables all load balancers. All connections are closed, and any attempt to
91 * open a new connection will result in a DBAccessError.
92 * @see LoadBalancer::disable()
94 public function destroy() {
95 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
96 $this->forEachLBCallMethod( 'disable' );
100 * Disables all access to the load balancer, will cause all database access
101 * to throw a DBAccessError
103 public static function disableBackend() {
104 MediaWikiServices
::disableStorageBackend();
108 * Get an LBFactory instance
110 * @deprecated since 1.27, use MediaWikiServices::getDBLoadBalancerFactory() instead.
114 public static function singleton() {
115 return MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
119 * Returns the LBFactory class to use and the load balancer configuration.
121 * @todo instead of this, use a ServiceContainer for managing the different implementations.
123 * @param array $config (e.g. $wgLBFactoryConf)
124 * @return string Class name
126 public static function getLBFactoryClass( array $config ) {
127 // For configuration backward compatibility after removing
128 // underscores from class names in MediaWiki 1.23.
130 'LBFactory_Simple' => 'LBFactorySimple',
131 'LBFactory_Single' => 'LBFactorySingle',
132 'LBFactory_Multi' => 'LBFactoryMulti',
133 'LBFactory_Fake' => 'LBFactoryFake',
136 $class = $config['class'];
138 if ( isset( $bcClasses[$class] ) ) {
139 $class = $bcClasses[$class];
141 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
150 * Shut down, close connections and destroy the cached instance.
152 * @deprecated since 1.27, use LBFactory::destroy()
154 public static function destroyInstance() {
155 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
159 * Create a new load balancer object. The resulting object will be untracked,
160 * not chronology-protected, and the caller is responsible for cleaning it up.
162 * @param bool|string $wiki Wiki ID, or false for the current wiki
163 * @return LoadBalancer
165 abstract public function newMainLB( $wiki = false );
168 * Get a cached (tracked) load balancer object.
170 * @param bool|string $wiki Wiki ID, or false for the current wiki
171 * @return LoadBalancer
173 abstract public function getMainLB( $wiki = false );
176 * Create a new load balancer for external storage. The resulting object will be
177 * untracked, not chronology-protected, and the caller is responsible for
180 * @param string $cluster External storage cluster, or false for core
181 * @param bool|string $wiki Wiki ID, or false for the current wiki
182 * @return LoadBalancer
184 abstract protected function newExternalLB( $cluster, $wiki = false );
187 * Get a cached (tracked) load balancer for external storage
189 * @param string $cluster External storage cluster, or false for core
190 * @param bool|string $wiki Wiki ID, or false for the current wiki
191 * @return LoadBalancer
193 abstract public function getExternalLB( $cluster, $wiki = false );
196 * Execute a function for each tracked load balancer
197 * The callback is called with the load balancer as the first parameter,
198 * and $params passed as the subsequent parameters.
200 * @param callable $callback
201 * @param array $params
203 abstract public function forEachLB( $callback, array $params = [] );
206 * Prepare all tracked load balancers for shutdown
207 * @param integer $mode One of the class SHUTDOWN_* constants
208 * @param callable|null $workCallback Work to mask ChronologyProtector writes
210 public function shutdown(
211 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null
213 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
214 $this->shutdownChronologyProtector( $this->chronProt
, $workCallback, 'sync' );
215 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
216 $this->shutdownChronologyProtector( $this->chronProt
, null, 'async' );
219 $this->commitMasterChanges( __METHOD__
); // sanity
223 * Call a method of each tracked load balancer
225 * @param string $methodName
228 private function forEachLBCallMethod( $methodName, array $args = [] ) {
230 function ( LoadBalancer
$loadBalancer, $methodName, array $args ) {
231 call_user_func_array( [ $loadBalancer, $methodName ], $args );
233 [ $methodName, $args ]
238 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
240 * @param string $fname Caller name
243 public function flushReplicaSnapshots( $fname = __METHOD__
) {
244 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
248 * Commit on all connections. Done for two reasons:
249 * 1. To commit changes to the masters.
250 * 2. To release the snapshot on all connections, master and replica DB.
251 * @param string $fname Caller name
252 * @param array $options Options map:
253 * - maxWriteDuration: abort if more than this much time was spent in write queries
255 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
256 $this->commitMasterChanges( $fname, $options );
257 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
261 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
263 * The DBO_TRX setting will be reverted to the default in each of these methods:
264 * - commitMasterChanges()
265 * - rollbackMasterChanges()
268 * This allows for custom transaction rounds from any outer transaction scope.
270 * @param string $fname
271 * @throws DBTransactionError
274 public function beginMasterChanges( $fname = __METHOD__
) {
275 if ( $this->trxRoundId
!== false ) {
276 throw new DBTransactionError(
278 "$fname: transaction round '{$this->trxRoundId}' already started."
281 $this->trxRoundId
= $fname;
282 // Set DBO_TRX flags on all appropriate DBs
283 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
287 * Commit changes on all master connections
288 * @param string $fname Caller name
289 * @param array $options Options map:
290 * - maxWriteDuration: abort if more than this much time was spent in write queries
293 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
294 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
295 throw new DBTransactionError(
297 "$fname: transaction round '{$this->trxRoundId}' still running."
300 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
301 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
302 $this->trxRoundId
= false;
303 // Perform pre-commit checks, aborting on failure
304 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
305 // Log the DBs and methods involved in multi-DB transactions
306 $this->logIfMultiDbTransaction();
307 // Actually perform the commit on all master DB connections and revert DBO_TRX
308 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
309 // Run all post-commit callbacks
310 /** @var Exception $e */
311 $e = null; // first callback exception
312 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$e ) {
313 $ex = $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_COMMIT
);
316 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
317 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
318 // Throw any last post-commit callback error
319 if ( $e instanceof Exception
) {
325 * Rollback changes on all master connections
326 * @param string $fname Caller name
329 public function rollbackMasterChanges( $fname = __METHOD__
) {
330 $this->trxRoundId
= false;
331 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
332 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
333 // Run all post-rollback callbacks
334 $this->forEachLB( function ( LoadBalancer
$lb ) {
335 $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_ROLLBACK
);
340 * Log query info if multi DB transactions are going to be committed now
342 private function logIfMultiDbTransaction() {
344 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$callersByDB ) {
345 $masterName = $lb->getServerName( $lb->getWriterIndex() );
346 $callers = $lb->pendingMasterChangeCallers();
348 $callersByDB[$masterName] = $callers;
352 if ( count( $callersByDB ) >= 2 ) {
353 $dbs = implode( ', ', array_keys( $callersByDB ) );
354 $msg = "Multi-DB transaction [{$dbs}]:\n";
355 foreach ( $callersByDB as $db => $callers ) {
356 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
358 $this->trxLogger
->info( $msg );
363 * Determine if any master connection has pending changes
367 public function hasMasterChanges() {
369 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
370 $ret = $ret ||
$lb->hasMasterChanges();
377 * Detemine if any lagged replica DB connection was used
381 public function laggedReplicaUsed() {
383 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
384 $ret = $ret ||
$lb->laggedReplicaUsed();
393 * @deprecated Since 1.28; use laggedReplicaUsed()
395 public function laggedSlaveUsed() {
396 return $this->laggedReplicaUsed();
400 * Determine if any master connection has pending/written changes from this request
401 * @param float $age How many seconds ago is "recent" [defaults to LB lag wait timeout]
405 public function hasOrMadeRecentMasterChanges( $age = null ) {
407 $this->forEachLB( function ( LoadBalancer
$lb ) use ( $age, &$ret ) {
408 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
414 * Waits for the replica DBs to catch up to the current master position
416 * Use this when updating very large numbers of rows, as in maintenance scripts,
417 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
419 * By default this waits on all DB clusters actually used in this request.
420 * This makes sense when lag being waiting on is caused by the code that does this check.
421 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
422 * that were not changed since the last wait check. To forcefully wait on a specific cluster
423 * for a given wiki, use the 'wiki' parameter. To forcefully wait on an "external" cluster,
424 * use the "cluster" parameter.
426 * Never call this function after a large DB write that is *still* in a transaction.
427 * It only makes sense to call this after the possible lag inducing changes were committed.
429 * @param array $opts Optional fields that include:
430 * - wiki : wait on the load balancer DBs that handles the given wiki
431 * - cluster : wait on the given external load balancer DBs
432 * - timeout : Max wait time. Default: ~60 seconds
433 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
434 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
437 public function waitForReplication( array $opts = [] ) {
442 'ifWritesSince' => null
445 // Figure out which clusters need to be checked
446 /** @var LoadBalancer[] $lbs */
448 if ( $opts['cluster'] !== false ) {
449 $lbs[] = $this->getExternalLB( $opts['cluster'] );
450 } elseif ( $opts['wiki'] !== false ) {
451 $lbs[] = $this->getMainLB( $opts['wiki'] );
453 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$lbs ) {
457 return; // nothing actually used
461 // Get all the master positions of applicable DBs right now.
462 // This can be faster since waiting on one cluster reduces the
463 // time needed to wait on the next clusters.
464 $masterPositions = array_fill( 0, count( $lbs ), false );
465 foreach ( $lbs as $i => $lb ) {
466 if ( $lb->getServerCount() <= 1 ) {
467 // Bug 27975 - Don't try to wait for replica DBs if there are none
468 // Prevents permission error when getting master position
470 } elseif ( $opts['ifWritesSince']
471 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
473 continue; // no writes since the last wait
475 $masterPositions[$i] = $lb->getMasterPos();
478 // Run any listener callbacks *after* getting the DB positions. The more
479 // time spent in the callbacks, the less time is spent in waitForAll().
480 foreach ( $this->replicationWaitCallbacks
as $callback ) {
485 foreach ( $lbs as $i => $lb ) {
486 if ( $masterPositions[$i] ) {
487 // The DBMS may not support getMasterPos() or the whole
488 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
489 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
490 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
496 throw new DBReplicationWaitError(
497 "Could not wait for replica DBs to catch up to " .
498 implode( ', ', $failed )
504 * Add a callback to be run in every call to waitForReplication() before waiting
506 * Callbacks must clear any transactions that they start
508 * @param string $name Callback name
509 * @param callable|null $callback Use null to unset a callback
512 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
514 $this->replicationWaitCallbacks
[$name] = $callback;
516 unset( $this->replicationWaitCallbacks
[$name] );
521 * Get a token asserting that no transaction writes are active
523 * @param string $fname Caller name (e.g. __METHOD__)
524 * @return mixed A value to pass to commitAndWaitForReplication()
527 public function getEmptyTransactionTicket( $fname ) {
528 if ( $this->hasMasterChanges() ) {
529 $this->trxLogger
->error( __METHOD__
. ": $fname does not have outer scope." );
533 return $this->ticket
;
537 * Convenience method for safely running commitMasterChanges()/waitForReplication()
539 * This will commit and wait unless $ticket indicates it is unsafe to do so
541 * @param string $fname Caller name (e.g. __METHOD__)
542 * @param mixed $ticket Result of getEmptyTransactionTicket()
543 * @param array $opts Options to waitForReplication()
544 * @throws DBReplicationWaitError
547 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
548 if ( $ticket !== $this->ticket
) {
549 $logger = LoggerFactory
::getInstance( 'DBPerformance' );
550 $logger->error( __METHOD__
. ": cannot commit; $fname does not have outer scope." );
554 // The transaction owner and any caller with the empty transaction ticket can commit
555 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
556 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
557 $this->trxLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
558 $fnameEffective = $this->trxRoundId
;
560 $fnameEffective = $fname;
563 $this->commitMasterChanges( $fnameEffective );
564 $this->waitForReplication( $opts );
565 // If a nested caller committed on behalf of $fname, start another empty $fname
566 // transaction, leaving the caller with the same empty transaction state as before.
567 if ( $fnameEffective !== $fname ) {
568 $this->beginMasterChanges( $fnameEffective );
573 * @param string $dbName DB master name (e.g. "db1052")
574 * @return float|bool UNIX timestamp when client last touched the DB or false if not recent
577 public function getChronologyProtectorTouched( $dbName ) {
578 return $this->chronProt
->getTouched( $dbName );
582 * Disable the ChronologyProtector for all load balancers
584 * This can be called at the start of special API entry points
588 public function disableChronologyProtection() {
589 $this->chronProt
->setEnabled( false );
593 * @return ChronologyProtector
595 protected function newChronologyProtector() {
596 $request = RequestContext
::getMain()->getRequest();
597 $chronProt = new ChronologyProtector(
598 ObjectCache
::getMainStashInstance(),
600 'ip' => $request->getIP(),
601 'agent' => $request->getHeader( 'User-Agent' ),
603 $request->getFloat( 'cpPosTime', null )
605 if ( PHP_SAPI
=== 'cli' ) {
606 $chronProt->setEnabled( false );
607 } elseif ( $request->getHeader( 'ChronologyProtection' ) === 'false' ) {
608 // Request opted out of using position wait logic. This is useful for requests
609 // done by the job queue or background ETL that do not have a meaningful session.
610 $chronProt->setWaitEnabled( false );
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 ( LoadBalancer
$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 ( LoadBalancer
$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' => wfWikiID(),
656 'readOnlyReason' => $this->readOnlyReason
,
657 'srvCache' => $this->srvCache
,
658 'wanCache' => $this->wanCache
,
659 'trxProfiler' => $this->trxProfiler
,
660 'queryLogger' => LoggerFactory
::getInstance( 'DBQuery' ),
661 'connLogger' => LoggerFactory
::getInstance( 'DBConnection' ),
662 'replLogger' => LoggerFactory
::getInstance( 'DBReplication' ),
663 'errorLogger' => [ MWExceptionHandler
::class, 'logException' ]
668 * @param LoadBalancer $lb
670 protected function initLoadBalancer( LoadBalancer
$lb ) {
671 if ( $this->trxRoundId
!== false ) {
672 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
677 * Append ?cpPosTime parameter to a URL for ChronologyProtector purposes if needed
679 * Note that unlike cookies, this works accross domains
682 * @param float $time UNIX timestamp just before shutdown() was called
686 public function appendPreShutdownTimeAsQuery( $url, $time ) {
688 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$usedCluster ) {
689 $usedCluster |
= ( $lb->getServerCount() > 1 );
692 if ( !$usedCluster ) {
693 return $url; // no master/replica clusters touched
696 return wfAppendQuery( $url, [ 'cpPosTime' => $time ] );
700 * Close all open database connections on all open load balancers.
703 public function closeAll() {
704 $this->forEachLBCallMethod( 'closeAll', [] );