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;
46 /** @var WANObjectCache */
51 /** @var string|bool String if a requested DBO_TRX transaction round is active */
52 protected $trxRoundId = false;
53 /** @var string|bool Reason all LBs are read-only or false if not */
54 protected $readOnlyReason = false;
55 /** @var callable[] */
56 protected $replicationWaitCallbacks = [];
58 const SHUTDOWN_NO_CHRONPROT
= 0; // don't save DB positions at all
59 const SHUTDOWN_CHRONPROT_ASYNC
= 1; // save DB positions, but don't wait on remote DCs
60 const SHUTDOWN_CHRONPROT_SYNC
= 2; // save DB positions, waiting on all DCs
63 * Construct a factory based on a configuration array (typically from $wgLBFactoryConf)
65 * @TODO: inject objects via dependency framework
67 public function __construct( array $conf ) {
68 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
69 $this->readOnlyReason
= $conf['readOnlyReason'];
71 $this->chronProt
= $this->newChronologyProtector();
72 $this->trxProfiler
= Profiler
::instance()->getTransactionProfiler();
73 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
74 $sCache = ObjectCache
::getLocalServerInstance();
75 if ( $sCache->getQoS( $sCache::ATTR_EMULATION
) > $sCache::QOS_EMULATION_SQL
) {
76 $this->srvCache
= $sCache;
78 $this->srvCache
= new EmptyBagOStuff();
80 $cCache = ObjectCache
::getLocalClusterInstance();
81 if ( $cCache->getQoS( $cCache::ATTR_EMULATION
) > $cCache::QOS_EMULATION_SQL
) {
82 $this->memCache
= $cCache;
84 $this->memCache
= new EmptyBagOStuff();
86 $wCache = ObjectCache
::getMainWANInstance();
87 if ( $wCache->getQoS( $wCache::ATTR_EMULATION
) > $wCache::QOS_EMULATION_SQL
) {
88 $this->wanCache
= $wCache;
90 $this->wanCache
= WANObjectCache
::newEmpty();
92 $this->trxLogger
= LoggerFactory
::getInstance( 'DBTransaction' );
93 $this->replLogger
= LoggerFactory
::getInstance( 'DBReplication' );
94 $this->ticket
= mt_rand();
98 * Disables all load balancers. All connections are closed, and any attempt to
99 * open a new connection will result in a DBAccessError.
100 * @see LoadBalancer::disable()
102 public function destroy() {
103 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
104 $this->forEachLBCallMethod( 'disable' );
108 * Disables all access to the load balancer, will cause all database access
109 * to throw a DBAccessError
111 public static function disableBackend() {
112 MediaWikiServices
::disableStorageBackend();
116 * Get an LBFactory instance
118 * @deprecated since 1.27, use MediaWikiServices::getDBLoadBalancerFactory() instead.
122 public static function singleton() {
123 return MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
127 * Returns the LBFactory class to use and the load balancer configuration.
129 * @todo instead of this, use a ServiceContainer for managing the different implementations.
131 * @param array $config (e.g. $wgLBFactoryConf)
132 * @return string Class name
134 public static function getLBFactoryClass( array $config ) {
135 // For configuration backward compatibility after removing
136 // underscores from class names in MediaWiki 1.23.
138 'LBFactory_Simple' => 'LBFactorySimple',
139 'LBFactory_Single' => 'LBFactorySingle',
140 'LBFactory_Multi' => 'LBFactoryMulti',
141 'LBFactory_Fake' => 'LBFactoryFake',
144 $class = $config['class'];
146 if ( isset( $bcClasses[$class] ) ) {
147 $class = $bcClasses[$class];
149 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
158 * Shut down, close connections and destroy the cached instance.
160 * @deprecated since 1.27, use LBFactory::destroy()
162 public static function destroyInstance() {
163 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
167 * Create a new load balancer object. The resulting object will be untracked,
168 * not chronology-protected, and the caller is responsible for cleaning it up.
170 * @param bool|string $wiki Wiki ID, or false for the current wiki
171 * @return LoadBalancer
173 abstract public function newMainLB( $wiki = false );
176 * Get a cached (tracked) load balancer object.
178 * @param bool|string $wiki Wiki ID, or false for the current wiki
179 * @return LoadBalancer
181 abstract public function getMainLB( $wiki = false );
184 * Create a new load balancer for external storage. The resulting object will be
185 * untracked, not chronology-protected, and the caller is responsible for
188 * @param string $cluster External storage cluster, or false for core
189 * @param bool|string $wiki Wiki ID, or false for the current wiki
190 * @return LoadBalancer
192 abstract protected function newExternalLB( $cluster, $wiki = false );
195 * Get a cached (tracked) load balancer for external storage
197 * @param string $cluster External storage cluster, or false for core
198 * @param bool|string $wiki Wiki ID, or false for the current wiki
199 * @return LoadBalancer
201 abstract public function getExternalLB( $cluster, $wiki = false );
204 * Execute a function for each tracked load balancer
205 * The callback is called with the load balancer as the first parameter,
206 * and $params passed as the subsequent parameters.
208 * @param callable $callback
209 * @param array $params
211 abstract public function forEachLB( $callback, array $params = [] );
214 * Prepare all tracked load balancers for shutdown
215 * @param integer $mode One of the class SHUTDOWN_* constants
216 * @param callable|null $workCallback Work to mask ChronologyProtector writes
218 public function shutdown(
219 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null
221 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
222 $this->shutdownChronologyProtector( $this->chronProt
, $workCallback, 'sync' );
223 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
224 $this->shutdownChronologyProtector( $this->chronProt
, null, 'async' );
227 $this->commitMasterChanges( __METHOD__
); // sanity
231 * Call a method of each tracked load balancer
233 * @param string $methodName
236 private function forEachLBCallMethod( $methodName, array $args = [] ) {
238 function ( LoadBalancer
$loadBalancer, $methodName, array $args ) {
239 call_user_func_array( [ $loadBalancer, $methodName ], $args );
241 [ $methodName, $args ]
246 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
248 * @param string $fname Caller name
251 public function flushReplicaSnapshots( $fname = __METHOD__
) {
252 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
256 * Commit on all connections. Done for two reasons:
257 * 1. To commit changes to the masters.
258 * 2. To release the snapshot on all connections, master and replica DB.
259 * @param string $fname Caller name
260 * @param array $options Options map:
261 * - maxWriteDuration: abort if more than this much time was spent in write queries
263 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
264 $this->commitMasterChanges( $fname, $options );
265 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
269 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
271 * The DBO_TRX setting will be reverted to the default in each of these methods:
272 * - commitMasterChanges()
273 * - rollbackMasterChanges()
276 * This allows for custom transaction rounds from any outer transaction scope.
278 * @param string $fname
279 * @throws DBTransactionError
282 public function beginMasterChanges( $fname = __METHOD__
) {
283 if ( $this->trxRoundId
!== false ) {
284 throw new DBTransactionError(
286 "$fname: transaction round '{$this->trxRoundId}' already started."
289 $this->trxRoundId
= $fname;
290 // Set DBO_TRX flags on all appropriate DBs
291 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
295 * Commit changes on all master connections
296 * @param string $fname Caller name
297 * @param array $options Options map:
298 * - maxWriteDuration: abort if more than this much time was spent in write queries
301 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
302 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
303 throw new DBTransactionError(
305 "$fname: transaction round '{$this->trxRoundId}' still running."
308 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
309 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
310 $this->trxRoundId
= false;
311 // Perform pre-commit checks, aborting on failure
312 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
313 // Log the DBs and methods involved in multi-DB transactions
314 $this->logIfMultiDbTransaction();
315 // Actually perform the commit on all master DB connections and revert DBO_TRX
316 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
317 // Run all post-commit callbacks
318 /** @var Exception $e */
319 $e = null; // first callback exception
320 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$e ) {
321 $ex = $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_COMMIT
);
324 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
325 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
326 // Throw any last post-commit callback error
327 if ( $e instanceof Exception
) {
333 * Rollback changes on all master connections
334 * @param string $fname Caller name
337 public function rollbackMasterChanges( $fname = __METHOD__
) {
338 $this->trxRoundId
= false;
339 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
340 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
341 // Run all post-rollback callbacks
342 $this->forEachLB( function ( LoadBalancer
$lb ) {
343 $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_ROLLBACK
);
348 * Log query info if multi DB transactions are going to be committed now
350 private function logIfMultiDbTransaction() {
352 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$callersByDB ) {
353 $masterName = $lb->getServerName( $lb->getWriterIndex() );
354 $callers = $lb->pendingMasterChangeCallers();
356 $callersByDB[$masterName] = $callers;
360 if ( count( $callersByDB ) >= 2 ) {
361 $dbs = implode( ', ', array_keys( $callersByDB ) );
362 $msg = "Multi-DB transaction [{$dbs}]:\n";
363 foreach ( $callersByDB as $db => $callers ) {
364 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
366 $this->trxLogger
->info( $msg );
371 * Determine if any master connection has pending changes
375 public function hasMasterChanges() {
377 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
378 $ret = $ret ||
$lb->hasMasterChanges();
385 * Detemine if any lagged replica DB connection was used
389 public function laggedReplicaUsed() {
391 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
392 $ret = $ret ||
$lb->laggedReplicaUsed();
401 * @deprecated Since 1.28; use laggedReplicaUsed()
403 public function laggedSlaveUsed() {
404 return $this->laggedReplicaUsed();
408 * Determine if any master connection has pending/written changes from this request
409 * @param float $age How many seconds ago is "recent" [defaults to LB lag wait timeout]
413 public function hasOrMadeRecentMasterChanges( $age = null ) {
415 $this->forEachLB( function ( LoadBalancer
$lb ) use ( $age, &$ret ) {
416 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
422 * Waits for the replica DBs to catch up to the current master position
424 * Use this when updating very large numbers of rows, as in maintenance scripts,
425 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
427 * By default this waits on all DB clusters actually used in this request.
428 * This makes sense when lag being waiting on is caused by the code that does this check.
429 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
430 * that were not changed since the last wait check. To forcefully wait on a specific cluster
431 * for a given wiki, use the 'wiki' parameter. To forcefully wait on an "external" cluster,
432 * use the "cluster" parameter.
434 * Never call this function after a large DB write that is *still* in a transaction.
435 * It only makes sense to call this after the possible lag inducing changes were committed.
437 * @param array $opts Optional fields that include:
438 * - wiki : wait on the load balancer DBs that handles the given wiki
439 * - cluster : wait on the given external load balancer DBs
440 * - timeout : Max wait time. Default: ~60 seconds
441 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
442 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
445 public function waitForReplication( array $opts = [] ) {
450 'ifWritesSince' => null
453 // Figure out which clusters need to be checked
454 /** @var LoadBalancer[] $lbs */
456 if ( $opts['cluster'] !== false ) {
457 $lbs[] = $this->getExternalLB( $opts['cluster'] );
458 } elseif ( $opts['wiki'] !== false ) {
459 $lbs[] = $this->getMainLB( $opts['wiki'] );
461 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$lbs ) {
465 return; // nothing actually used
469 // Get all the master positions of applicable DBs right now.
470 // This can be faster since waiting on one cluster reduces the
471 // time needed to wait on the next clusters.
472 $masterPositions = array_fill( 0, count( $lbs ), false );
473 foreach ( $lbs as $i => $lb ) {
474 if ( $lb->getServerCount() <= 1 ) {
475 // Bug 27975 - Don't try to wait for replica DBs if there are none
476 // Prevents permission error when getting master position
478 } elseif ( $opts['ifWritesSince']
479 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
481 continue; // no writes since the last wait
483 $masterPositions[$i] = $lb->getMasterPos();
486 // Run any listener callbacks *after* getting the DB positions. The more
487 // time spent in the callbacks, the less time is spent in waitForAll().
488 foreach ( $this->replicationWaitCallbacks
as $callback ) {
493 foreach ( $lbs as $i => $lb ) {
494 if ( $masterPositions[$i] ) {
495 // The DBMS may not support getMasterPos() or the whole
496 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
497 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
498 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
504 throw new DBReplicationWaitError(
505 "Could not wait for replica DBs to catch up to " .
506 implode( ', ', $failed )
512 * Add a callback to be run in every call to waitForReplication() before waiting
514 * Callbacks must clear any transactions that they start
516 * @param string $name Callback name
517 * @param callable|null $callback Use null to unset a callback
520 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
522 $this->replicationWaitCallbacks
[$name] = $callback;
524 unset( $this->replicationWaitCallbacks
[$name] );
529 * Get a token asserting that no transaction writes are active
531 * @param string $fname Caller name (e.g. __METHOD__)
532 * @return mixed A value to pass to commitAndWaitForReplication()
535 public function getEmptyTransactionTicket( $fname ) {
536 if ( $this->hasMasterChanges() ) {
537 $this->trxLogger
->error( __METHOD__
. ": $fname does not have outer scope." );
541 return $this->ticket
;
545 * Convenience method for safely running commitMasterChanges()/waitForReplication()
547 * This will commit and wait unless $ticket indicates it is unsafe to do so
549 * @param string $fname Caller name (e.g. __METHOD__)
550 * @param mixed $ticket Result of getEmptyTransactionTicket()
551 * @param array $opts Options to waitForReplication()
552 * @throws DBReplicationWaitError
555 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
556 if ( $ticket !== $this->ticket
) {
557 $logger = LoggerFactory
::getInstance( 'DBPerformance' );
558 $logger->error( __METHOD__
. ": cannot commit; $fname does not have outer scope." );
562 // The transaction owner and any caller with the empty transaction ticket can commit
563 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
564 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
565 $this->trxLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
566 $fnameEffective = $this->trxRoundId
;
568 $fnameEffective = $fname;
571 $this->commitMasterChanges( $fnameEffective );
572 $this->waitForReplication( $opts );
573 // If a nested caller committed on behalf of $fname, start another empty $fname
574 // transaction, leaving the caller with the same empty transaction state as before.
575 if ( $fnameEffective !== $fname ) {
576 $this->beginMasterChanges( $fnameEffective );
581 * @param string $dbName DB master name (e.g. "db1052")
582 * @return float|bool UNIX timestamp when client last touched the DB or false if not recent
585 public function getChronologyProtectorTouched( $dbName ) {
586 return $this->chronProt
->getTouched( $dbName );
590 * Disable the ChronologyProtector for all load balancers
592 * This can be called at the start of special API entry points
596 public function disableChronologyProtection() {
597 $this->chronProt
->setEnabled( false );
601 * @return ChronologyProtector
603 protected function newChronologyProtector() {
604 $request = RequestContext
::getMain()->getRequest();
605 $chronProt = new ChronologyProtector(
606 ObjectCache
::getMainStashInstance(),
608 'ip' => $request->getIP(),
609 'agent' => $request->getHeader( 'User-Agent' ),
611 $request->getFloat( 'cpPosTime', $request->getCookie( 'cpPosTime', '' ) )
613 if ( PHP_SAPI
=== 'cli' ) {
614 $chronProt->setEnabled( false );
615 } elseif ( $request->getHeader( 'ChronologyProtection' ) === 'false' ) {
616 // Request opted out of using position wait logic. This is useful for requests
617 // done by the job queue or background ETL that do not have a meaningful session.
618 $chronProt->setWaitEnabled( false );
625 * Get and record all of the staged DB positions into persistent memory storage
627 * @param ChronologyProtector $cp
628 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
629 * @param string $mode One of (sync, async); whether to wait on remote datacenters
631 protected function shutdownChronologyProtector(
632 ChronologyProtector
$cp, $workCallback, $mode
634 // Record all the master positions needed
635 $this->forEachLB( function ( LoadBalancer
$lb ) use ( $cp ) {
636 $cp->shutdownLB( $lb );
638 // Write them to the persistent stash. Try to do something useful by running $work
639 // while ChronologyProtector waits for the stash write to replicate to all DCs.
640 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
641 if ( $unsavedPositions && $workCallback ) {
642 // Invoke callback in case it did not cache the result yet
643 $workCallback(); // work now to block for less time in waitForAll()
645 // If the positions failed to write to the stash, at least wait on local datacenter
646 // replica DBs to catch up before responding. Even if there are several DCs, this increases
647 // the chance that the user will see their own changes immediately afterwards. As long
648 // as the sticky DC cookie applies (same domain), this is not even an issue.
649 $this->forEachLB( function ( LoadBalancer
$lb ) use ( $unsavedPositions ) {
650 $masterName = $lb->getServerName( $lb->getWriterIndex() );
651 if ( isset( $unsavedPositions[$masterName] ) ) {
652 $lb->waitForAll( $unsavedPositions[$masterName] );
658 * Base parameters to LoadBalancer::__construct()
661 final protected function baseLoadBalancerParams() {
663 'localDomain' => wfWikiID(),
664 'readOnlyReason' => $this->readOnlyReason
,
665 'srvCache' => $this->srvCache
,
666 'memCache' => $this->memCache
,
667 'wanCache' => $this->wanCache
,
668 'trxProfiler' => $this->trxProfiler
,
669 'queryLogger' => LoggerFactory
::getInstance( 'DBQuery' ),
670 'connLogger' => LoggerFactory
::getInstance( 'DBConnection' ),
671 'replLogger' => LoggerFactory
::getInstance( 'DBReplication' ),
672 'errorLogger' => [ MWExceptionHandler
::class, 'logException' ]
677 * @param LoadBalancer $lb
679 protected function initLoadBalancer( LoadBalancer
$lb ) {
680 if ( $this->trxRoundId
!== false ) {
681 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
686 * Append ?cpPosTime parameter to a URL for ChronologyProtector purposes if needed
688 * Note that unlike cookies, this works accross domains
691 * @param float $time UNIX timestamp just before shutdown() was called
695 public function appendPreShutdownTimeAsQuery( $url, $time ) {
697 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$usedCluster ) {
698 $usedCluster |
= ( $lb->getServerCount() > 1 );
701 if ( !$usedCluster ) {
702 return $url; // no master/replica clusters touched
705 return wfAppendQuery( $url, [ 'cpPosTime' => $time ] );
709 * Close all open database connections on all open load balancers.
712 public function closeAll() {
713 $this->forEachLBCallMethod( 'closeAll', [] );