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 MediaWiki\MediaWikiServices
;
25 use MediaWiki\Services\DestructibleService
;
26 use Psr\Log\LoggerInterface
;
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 */
42 /** @var WANObjectCache */
47 /** @var string|bool String if a requested DBO_TRX transaction round is active */
48 protected $trxRoundId = false;
49 /** @var string|bool Reason all LBs are read-only or false if not */
50 protected $readOnlyReason = false;
51 /** @var callable[] */
52 protected $replicationWaitCallbacks = [];
54 const SHUTDOWN_NO_CHRONPROT
= 0; // don't save DB positions at all
55 const SHUTDOWN_CHRONPROT_ASYNC
= 1; // save DB positions, but don't wait on remote DCs
56 const SHUTDOWN_CHRONPROT_SYNC
= 2; // save DB positions, waiting on all DCs
59 * Construct a factory based on a configuration array (typically from $wgLBFactoryConf)
61 * @TODO: inject objects via dependency framework
63 public function __construct( array $conf ) {
64 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
65 $this->readOnlyReason
= $conf['readOnlyReason'];
67 $this->chronProt
= $this->newChronologyProtector();
68 $this->trxProfiler
= Profiler
::instance()->getTransactionProfiler();
69 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
70 $cache = ObjectCache
::getLocalServerInstance();
71 if ( $cache->getQoS( $cache::ATTR_EMULATION
) > $cache::QOS_EMULATION_SQL
) {
72 $this->srvCache
= $cache;
74 $this->srvCache
= new EmptyBagOStuff();
76 $wCache = ObjectCache
::getMainWANInstance();
77 if ( $wCache->getQoS( $wCache::ATTR_EMULATION
) > $wCache::QOS_EMULATION_SQL
) {
78 $this->wanCache
= $wCache;
80 $this->wanCache
= WANObjectCache
::newEmpty();
82 $this->trxLogger
= LoggerFactory
::getInstance( 'DBTransaction' );
83 $this->ticket
= mt_rand();
87 * Disables all load balancers. All connections are closed, and any attempt to
88 * open a new connection will result in a DBAccessError.
89 * @see LoadBalancer::disable()
91 public function destroy() {
92 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
93 $this->forEachLBCallMethod( 'disable' );
97 * Disables all access to the load balancer, will cause all database access
98 * to throw a DBAccessError
100 public static function disableBackend() {
101 MediaWikiServices
::disableStorageBackend();
105 * Get an LBFactory instance
107 * @deprecated since 1.27, use MediaWikiServices::getDBLoadBalancerFactory() instead.
111 public static function singleton() {
112 return MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
116 * Returns the LBFactory class to use and the load balancer configuration.
118 * @todo instead of this, use a ServiceContainer for managing the different implementations.
120 * @param array $config (e.g. $wgLBFactoryConf)
121 * @return string Class name
123 public static function getLBFactoryClass( array $config ) {
124 // For configuration backward compatibility after removing
125 // underscores from class names in MediaWiki 1.23.
127 'LBFactory_Simple' => 'LBFactorySimple',
128 'LBFactory_Single' => 'LBFactorySingle',
129 'LBFactory_Multi' => 'LBFactoryMulti',
130 'LBFactory_Fake' => 'LBFactoryFake',
133 $class = $config['class'];
135 if ( isset( $bcClasses[$class] ) ) {
136 $class = $bcClasses[$class];
138 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
147 * Shut down, close connections and destroy the cached instance.
149 * @deprecated since 1.27, use LBFactory::destroy()
151 public static function destroyInstance() {
152 self
::singleton()->destroy();
156 * Create a new load balancer object. The resulting object will be untracked,
157 * not chronology-protected, and the caller is responsible for cleaning it up.
159 * @param bool|string $wiki Wiki ID, or false for the current wiki
160 * @return LoadBalancer
162 abstract public function newMainLB( $wiki = false );
165 * Get a cached (tracked) load balancer object.
167 * @param bool|string $wiki Wiki ID, or false for the current wiki
168 * @return LoadBalancer
170 abstract public function getMainLB( $wiki = false );
173 * Create a new load balancer for external storage. The resulting object will be
174 * untracked, not chronology-protected, and the caller is responsible for
177 * @param string $cluster External storage cluster, or false for core
178 * @param bool|string $wiki Wiki ID, or false for the current wiki
179 * @return LoadBalancer
181 abstract protected function newExternalLB( $cluster, $wiki = false );
184 * Get a cached (tracked) load balancer for external storage
186 * @param string $cluster External storage cluster, or false for core
187 * @param bool|string $wiki Wiki ID, or false for the current wiki
188 * @return LoadBalancer
190 abstract public function getExternalLB( $cluster, $wiki = false );
193 * Execute a function for each tracked load balancer
194 * The callback is called with the load balancer as the first parameter,
195 * and $params passed as the subsequent parameters.
197 * @param callable $callback
198 * @param array $params
200 abstract public function forEachLB( $callback, array $params = [] );
203 * Prepare all tracked load balancers for shutdown
204 * @param integer $mode One of the class SHUTDOWN_* constants
205 * @param callable|null $workCallback Work to mask ChronologyProtector writes
207 public function shutdown(
208 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null
210 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
211 $this->shutdownChronologyProtector( $this->chronProt
, $workCallback, 'sync' );
212 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
213 $this->shutdownChronologyProtector( $this->chronProt
, null, 'async' );
216 $this->commitMasterChanges( __METHOD__
); // sanity
220 * Call a method of each tracked load balancer
222 * @param string $methodName
225 private function forEachLBCallMethod( $methodName, array $args = [] ) {
227 function ( LoadBalancer
$loadBalancer, $methodName, array $args ) {
228 call_user_func_array( [ $loadBalancer, $methodName ], $args );
230 [ $methodName, $args ]
235 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
237 * @param string $fname Caller name
240 public function flushReplicaSnapshots( $fname = __METHOD__
) {
241 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
245 * Commit on all connections. Done for two reasons:
246 * 1. To commit changes to the masters.
247 * 2. To release the snapshot on all connections, master and replica DB.
248 * @param string $fname Caller name
249 * @param array $options Options map:
250 * - maxWriteDuration: abort if more than this much time was spent in write queries
252 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
253 $this->commitMasterChanges( $fname, $options );
254 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
258 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
260 * The DBO_TRX setting will be reverted to the default in each of these methods:
261 * - commitMasterChanges()
262 * - rollbackMasterChanges()
265 * This allows for custom transaction rounds from any outer transaction scope.
267 * @param string $fname
268 * @throws DBTransactionError
271 public function beginMasterChanges( $fname = __METHOD__
) {
272 if ( $this->trxRoundId
!== false ) {
273 throw new DBTransactionError(
275 "$fname: transaction round '{$this->trxRoundId}' already started."
278 $this->trxRoundId
= $fname;
279 // Set DBO_TRX flags on all appropriate DBs
280 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
284 * Commit changes on all master connections
285 * @param string $fname Caller name
286 * @param array $options Options map:
287 * - maxWriteDuration: abort if more than this much time was spent in write queries
290 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
291 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
292 throw new DBTransactionError(
294 "$fname: transaction round '{$this->trxRoundId}' still running."
297 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
298 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
299 $this->trxRoundId
= false;
300 // Perform pre-commit checks, aborting on failure
301 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
302 // Log the DBs and methods involved in multi-DB transactions
303 $this->logIfMultiDbTransaction();
304 // Actually perform the commit on all master DB connections and revert DBO_TRX
305 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
306 // Run all post-commit callbacks
307 /** @var Exception $e */
308 $e = null; // first callback exception
309 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$e ) {
310 $ex = $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_COMMIT
);
313 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
314 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
315 // Throw any last post-commit callback error
316 if ( $e instanceof Exception
) {
322 * Rollback changes on all master connections
323 * @param string $fname Caller name
326 public function rollbackMasterChanges( $fname = __METHOD__
) {
327 $this->trxRoundId
= false;
328 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
329 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
330 // Run all post-rollback callbacks
331 $this->forEachLB( function ( LoadBalancer
$lb ) {
332 $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_ROLLBACK
);
337 * Log query info if multi DB transactions are going to be committed now
339 private function logIfMultiDbTransaction() {
341 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$callersByDB ) {
342 $masterName = $lb->getServerName( $lb->getWriterIndex() );
343 $callers = $lb->pendingMasterChangeCallers();
345 $callersByDB[$masterName] = $callers;
349 if ( count( $callersByDB ) >= 2 ) {
350 $dbs = implode( ', ', array_keys( $callersByDB ) );
351 $msg = "Multi-DB transaction [{$dbs}]:\n";
352 foreach ( $callersByDB as $db => $callers ) {
353 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
355 $this->trxLogger
->info( $msg );
360 * Determine if any master connection has pending changes
364 public function hasMasterChanges() {
366 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
367 $ret = $ret ||
$lb->hasMasterChanges();
374 * Detemine if any lagged replica DB connection was used
378 public function laggedReplicaUsed() {
380 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
381 $ret = $ret ||
$lb->laggedReplicaUsed();
390 * @deprecated Since 1.28; use laggedReplicaUsed()
392 public function laggedSlaveUsed() {
393 return $this->laggedReplicaUsed();
397 * Determine if any master connection has pending/written changes from this request
398 * @param float $age How many seconds ago is "recent" [defaults to LB lag wait timeout]
402 public function hasOrMadeRecentMasterChanges( $age = null ) {
404 $this->forEachLB( function ( LoadBalancer
$lb ) use ( $age, &$ret ) {
405 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
411 * Waits for the replica DBs to catch up to the current master position
413 * Use this when updating very large numbers of rows, as in maintenance scripts,
414 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
416 * By default this waits on all DB clusters actually used in this request.
417 * This makes sense when lag being waiting on is caused by the code that does this check.
418 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
419 * that were not changed since the last wait check. To forcefully wait on a specific cluster
420 * for a given wiki, use the 'wiki' parameter. To forcefully wait on an "external" cluster,
421 * use the "cluster" parameter.
423 * Never call this function after a large DB write that is *still* in a transaction.
424 * It only makes sense to call this after the possible lag inducing changes were committed.
426 * @param array $opts Optional fields that include:
427 * - wiki : wait on the load balancer DBs that handles the given wiki
428 * - cluster : wait on the given external load balancer DBs
429 * - timeout : Max wait time. Default: ~60 seconds
430 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
431 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
434 public function waitForReplication( array $opts = [] ) {
439 'ifWritesSince' => null
442 foreach ( $this->replicationWaitCallbacks
as $callback ) {
446 // Figure out which clusters need to be checked
447 /** @var LoadBalancer[] $lbs */
449 if ( $opts['cluster'] !== false ) {
450 $lbs[] = $this->getExternalLB( $opts['cluster'] );
451 } elseif ( $opts['wiki'] !== false ) {
452 $lbs[] = $this->getMainLB( $opts['wiki'] );
454 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$lbs ) {
458 return; // nothing actually used
462 // Get all the master positions of applicable DBs right now.
463 // This can be faster since waiting on one cluster reduces the
464 // time needed to wait on the next clusters.
465 $masterPositions = array_fill( 0, count( $lbs ), false );
466 foreach ( $lbs as $i => $lb ) {
467 if ( $lb->getServerCount() <= 1 ) {
468 // Bug 27975 - Don't try to wait for replica DBs if there are none
469 // Prevents permission error when getting master position
471 } elseif ( $opts['ifWritesSince']
472 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
474 continue; // no writes since the last wait
476 $masterPositions[$i] = $lb->getMasterPos();
480 foreach ( $lbs as $i => $lb ) {
481 if ( $masterPositions[$i] ) {
482 // The DBMS may not support getMasterPos() or the whole
483 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
484 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
485 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
491 throw new DBReplicationWaitError(
492 "Could not wait for replica DBs to catch up to " .
493 implode( ', ', $failed )
499 * Add a callback to be run in every call to waitForReplication() before waiting
501 * Callbacks must clear any transactions that they start
503 * @param string $name Callback name
504 * @param callable|null $callback Use null to unset a callback
507 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
509 $this->replicationWaitCallbacks
[$name] = $callback;
511 unset( $this->replicationWaitCallbacks
[$name] );
516 * Get a token asserting that no transaction writes are active
518 * @param string $fname Caller name (e.g. __METHOD__)
519 * @return mixed A value to pass to commitAndWaitForReplication()
522 public function getEmptyTransactionTicket( $fname ) {
523 if ( $this->hasMasterChanges() ) {
524 $this->trxLogger
->error( __METHOD__
. ": $fname does not have outer scope." );
528 return $this->ticket
;
532 * Convenience method for safely running commitMasterChanges()/waitForReplication()
534 * This will commit and wait unless $ticket indicates it is unsafe to do so
536 * @param string $fname Caller name (e.g. __METHOD__)
537 * @param mixed $ticket Result of getEmptyTransactionTicket()
538 * @param array $opts Options to waitForReplication()
539 * @throws DBReplicationWaitError
542 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
543 if ( $ticket !== $this->ticket
) {
544 $logger = LoggerFactory
::getInstance( 'DBPerformance' );
545 $logger->error( __METHOD__
. ": cannot commit; $fname does not have outer scope." );
549 // The transaction owner and any caller with the empty transaction ticket can commit
550 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
551 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
552 $this->trxLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
553 $fnameEffective = $this->trxRoundId
;
555 $fnameEffective = $fname;
558 $this->commitMasterChanges( $fnameEffective );
559 $this->waitForReplication( $opts );
560 // If a nested caller committed on behalf of $fname, start another empty $fname
561 // transaction, leaving the caller with the same empty transaction state as before.
562 if ( $fnameEffective !== $fname ) {
563 $this->beginMasterChanges( $fnameEffective );
568 * @param string $dbName DB master name (e.g. "db1052")
569 * @return float|bool UNIX timestamp when client last touched the DB or false if not recent
572 public function getChronologyProtectorTouched( $dbName ) {
573 return $this->chronProt
->getTouched( $dbName );
577 * Disable the ChronologyProtector for all load balancers
579 * This can be called at the start of special API entry points
583 public function disableChronologyProtection() {
584 $this->chronProt
->setEnabled( false );
588 * @return ChronologyProtector
590 protected function newChronologyProtector() {
591 $request = RequestContext
::getMain()->getRequest();
592 $chronProt = new ChronologyProtector(
593 ObjectCache
::getMainStashInstance(),
595 'ip' => $request->getIP(),
596 'agent' => $request->getHeader( 'User-Agent' ),
598 $request->getFloat( 'cpPosTime', null )
600 if ( PHP_SAPI
=== 'cli' ) {
601 $chronProt->setEnabled( false );
602 } elseif ( $request->getHeader( 'ChronologyProtection' ) === 'false' ) {
603 // Request opted out of using position wait logic. This is useful for requests
604 // done by the job queue or background ETL that do not have a meaningful session.
605 $chronProt->setWaitEnabled( false );
612 * Get and record all of the staged DB positions into persistent memory storage
614 * @param ChronologyProtector $cp
615 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
616 * @param string $mode One of (sync, async); whether to wait on remote datacenters
618 protected function shutdownChronologyProtector(
619 ChronologyProtector
$cp, $workCallback, $mode
621 // Record all the master positions needed
622 $this->forEachLB( function ( LoadBalancer
$lb ) use ( $cp ) {
623 $cp->shutdownLB( $lb );
625 // Write them to the persistent stash. Try to do something useful by running $work
626 // while ChronologyProtector waits for the stash write to replicate to all DCs.
627 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
628 if ( $unsavedPositions && $workCallback ) {
629 // Invoke callback in case it did not cache the result yet
630 $workCallback(); // work now to block for less time in waitForAll()
632 // If the positions failed to write to the stash, at least wait on local datacenter
633 // replica DBs to catch up before responding. Even if there are several DCs, this increases
634 // the chance that the user will see their own changes immediately afterwards. As long
635 // as the sticky DC cookie applies (same domain), this is not even an issue.
636 $this->forEachLB( function ( LoadBalancer
$lb ) use ( $unsavedPositions ) {
637 $masterName = $lb->getServerName( $lb->getWriterIndex() );
638 if ( isset( $unsavedPositions[$masterName] ) ) {
639 $lb->waitForAll( $unsavedPositions[$masterName] );
645 * @param LoadBalancer $lb
647 protected function initLoadBalancer( LoadBalancer
$lb ) {
648 if ( $this->trxRoundId
!== false ) {
649 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
654 * Append ?cpPosTime parameter to a URL for ChronologyProtector purposes if needed
656 * Note that unlike cookies, this works accross domains
659 * @param float $time UNIX timestamp just before shutdown() was called
663 public function appendPreShutdownTimeAsQuery( $url, $time ) {
665 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$usedCluster ) {
666 $usedCluster |
= ( $lb->getServerCount() > 1 );
669 if ( !$usedCluster ) {
670 return $url; // no master/replica clusters touched
673 return wfAppendQuery( $url, [ 'cpPosTime' => $time ] );
677 * Close all open database connections on all open load balancers.
680 public function closeAll() {
681 $this->forEachLBCallMethod( 'closeAll', [] );