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 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
72 $sCache = ObjectCache
::getLocalServerInstance();
73 if ( $sCache->getQoS( $sCache::ATTR_EMULATION
) > $sCache::QOS_EMULATION_SQL
) {
74 $this->srvCache
= $sCache;
76 $this->srvCache
= new EmptyBagOStuff();
78 $cCache = ObjectCache
::getLocalClusterInstance();
79 if ( $cCache->getQoS( $cCache::ATTR_EMULATION
) > $cCache::QOS_EMULATION_SQL
) {
80 $this->memCache
= $cCache;
82 $this->memCache
= new EmptyBagOStuff();
84 $wCache = ObjectCache
::getMainWANInstance();
85 if ( $wCache->getQoS( $wCache::ATTR_EMULATION
) > $wCache::QOS_EMULATION_SQL
) {
86 $this->wanCache
= $wCache;
88 $this->wanCache
= WANObjectCache
::newEmpty();
90 $this->trxProfiler
= Profiler
::instance()->getTransactionProfiler();
91 $this->trxLogger
= LoggerFactory
::getInstance( 'DBTransaction' );
92 $this->replLogger
= LoggerFactory
::getInstance( 'DBReplication' );
93 $this->chronProt
= $this->newChronologyProtector();
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',
143 $class = $config['class'];
145 if ( isset( $bcClasses[$class] ) ) {
146 $class = $bcClasses[$class];
148 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
157 * Shut down, close connections and destroy the cached instance.
159 * @deprecated since 1.27, use LBFactory::destroy()
161 public static function destroyInstance() {
162 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
166 * Create a new load balancer object. The resulting object will be untracked,
167 * not chronology-protected, and the caller is responsible for cleaning it up.
169 * @param bool|string $wiki Wiki ID, or false for the current wiki
170 * @return LoadBalancer
172 abstract public function newMainLB( $wiki = false );
175 * Get a cached (tracked) load balancer object.
177 * @param bool|string $wiki Wiki ID, or false for the current wiki
178 * @return LoadBalancer
180 abstract public function getMainLB( $wiki = false );
183 * Create a new load balancer for external storage. The resulting object will be
184 * untracked, not chronology-protected, and the caller is responsible for
187 * @param string $cluster External storage cluster, or false for core
188 * @param bool|string $wiki Wiki ID, or false for the current wiki
189 * @return LoadBalancer
191 abstract protected function newExternalLB( $cluster, $wiki = false );
194 * Get a cached (tracked) load balancer for external storage
196 * @param string $cluster External storage cluster, or false for core
197 * @param bool|string $wiki Wiki ID, or false for the current wiki
198 * @return LoadBalancer
200 abstract public function getExternalLB( $cluster, $wiki = false );
203 * Execute a function for each tracked load balancer
204 * The callback is called with the load balancer as the first parameter,
205 * and $params passed as the subsequent parameters.
207 * @param callable $callback
208 * @param array $params
210 abstract public function forEachLB( $callback, array $params = [] );
213 * Prepare all tracked load balancers for shutdown
214 * @param integer $mode One of the class SHUTDOWN_* constants
215 * @param callable|null $workCallback Work to mask ChronologyProtector writes
217 public function shutdown(
218 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null
220 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
221 $this->shutdownChronologyProtector( $this->chronProt
, $workCallback, 'sync' );
222 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
223 $this->shutdownChronologyProtector( $this->chronProt
, null, 'async' );
226 $this->commitMasterChanges( __METHOD__
); // sanity
230 * Call a method of each tracked load balancer
232 * @param string $methodName
235 private function forEachLBCallMethod( $methodName, array $args = [] ) {
237 function ( LoadBalancer
$loadBalancer, $methodName, array $args ) {
238 call_user_func_array( [ $loadBalancer, $methodName ], $args );
240 [ $methodName, $args ]
245 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
247 * @param string $fname Caller name
250 public function flushReplicaSnapshots( $fname = __METHOD__
) {
251 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
255 * Commit on all connections. Done for two reasons:
256 * 1. To commit changes to the masters.
257 * 2. To release the snapshot on all connections, master and replica DB.
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
262 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
263 $this->commitMasterChanges( $fname, $options );
264 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
268 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
270 * The DBO_TRX setting will be reverted to the default in each of these methods:
271 * - commitMasterChanges()
272 * - rollbackMasterChanges()
275 * This allows for custom transaction rounds from any outer transaction scope.
277 * @param string $fname
278 * @throws DBTransactionError
281 public function beginMasterChanges( $fname = __METHOD__
) {
282 if ( $this->trxRoundId
!== false ) {
283 throw new DBTransactionError(
285 "$fname: transaction round '{$this->trxRoundId}' already started."
288 $this->trxRoundId
= $fname;
289 // Set DBO_TRX flags on all appropriate DBs
290 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
294 * Commit changes on all master connections
295 * @param string $fname Caller name
296 * @param array $options Options map:
297 * - maxWriteDuration: abort if more than this much time was spent in write queries
300 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
301 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
302 throw new DBTransactionError(
304 "$fname: transaction round '{$this->trxRoundId}' still running."
307 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
308 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
309 $this->trxRoundId
= false;
310 // Perform pre-commit checks, aborting on failure
311 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
312 // Log the DBs and methods involved in multi-DB transactions
313 $this->logIfMultiDbTransaction();
314 // Actually perform the commit on all master DB connections and revert DBO_TRX
315 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
316 // Run all post-commit callbacks
317 /** @var Exception $e */
318 $e = null; // first callback exception
319 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$e ) {
320 $ex = $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_COMMIT
);
323 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
324 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
325 // Throw any last post-commit callback error
326 if ( $e instanceof Exception
) {
332 * Rollback changes on all master connections
333 * @param string $fname Caller name
336 public function rollbackMasterChanges( $fname = __METHOD__
) {
337 $this->trxRoundId
= false;
338 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
339 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
340 // Run all post-rollback callbacks
341 $this->forEachLB( function ( LoadBalancer
$lb ) {
342 $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_ROLLBACK
);
347 * Log query info if multi DB transactions are going to be committed now
349 private function logIfMultiDbTransaction() {
351 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$callersByDB ) {
352 $masterName = $lb->getServerName( $lb->getWriterIndex() );
353 $callers = $lb->pendingMasterChangeCallers();
355 $callersByDB[$masterName] = $callers;
359 if ( count( $callersByDB ) >= 2 ) {
360 $dbs = implode( ', ', array_keys( $callersByDB ) );
361 $msg = "Multi-DB transaction [{$dbs}]:\n";
362 foreach ( $callersByDB as $db => $callers ) {
363 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
365 $this->trxLogger
->info( $msg );
370 * Determine if any master connection has pending changes
374 public function hasMasterChanges() {
376 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
377 $ret = $ret ||
$lb->hasMasterChanges();
384 * Detemine if any lagged replica DB connection was used
388 public function laggedReplicaUsed() {
390 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
391 $ret = $ret ||
$lb->laggedReplicaUsed();
400 * @deprecated Since 1.28; use laggedReplicaUsed()
402 public function laggedSlaveUsed() {
403 return $this->laggedReplicaUsed();
407 * Determine if any master connection has pending/written changes from this request
408 * @param float $age How many seconds ago is "recent" [defaults to LB lag wait timeout]
412 public function hasOrMadeRecentMasterChanges( $age = null ) {
414 $this->forEachLB( function ( LoadBalancer
$lb ) use ( $age, &$ret ) {
415 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
421 * Waits for the replica DBs to catch up to the current master position
423 * Use this when updating very large numbers of rows, as in maintenance scripts,
424 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
426 * By default this waits on all DB clusters actually used in this request.
427 * This makes sense when lag being waiting on is caused by the code that does this check.
428 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
429 * that were not changed since the last wait check. To forcefully wait on a specific cluster
430 * for a given wiki, use the 'wiki' parameter. To forcefully wait on an "external" cluster,
431 * use the "cluster" parameter.
433 * Never call this function after a large DB write that is *still* in a transaction.
434 * It only makes sense to call this after the possible lag inducing changes were committed.
436 * @param array $opts Optional fields that include:
437 * - wiki : wait on the load balancer DBs that handles the given wiki
438 * - cluster : wait on the given external load balancer DBs
439 * - timeout : Max wait time. Default: ~60 seconds
440 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
441 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
444 public function waitForReplication( array $opts = [] ) {
449 'ifWritesSince' => null
452 // Figure out which clusters need to be checked
453 /** @var LoadBalancer[] $lbs */
455 if ( $opts['cluster'] !== false ) {
456 $lbs[] = $this->getExternalLB( $opts['cluster'] );
457 } elseif ( $opts['wiki'] !== false ) {
458 $lbs[] = $this->getMainLB( $opts['wiki'] );
460 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$lbs ) {
464 return; // nothing actually used
468 // Get all the master positions of applicable DBs right now.
469 // This can be faster since waiting on one cluster reduces the
470 // time needed to wait on the next clusters.
471 $masterPositions = array_fill( 0, count( $lbs ), false );
472 foreach ( $lbs as $i => $lb ) {
473 if ( $lb->getServerCount() <= 1 ) {
474 // Bug 27975 - Don't try to wait for replica DBs if there are none
475 // Prevents permission error when getting master position
477 } elseif ( $opts['ifWritesSince']
478 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
480 continue; // no writes since the last wait
482 $masterPositions[$i] = $lb->getMasterPos();
485 // Run any listener callbacks *after* getting the DB positions. The more
486 // time spent in the callbacks, the less time is spent in waitForAll().
487 foreach ( $this->replicationWaitCallbacks
as $callback ) {
492 foreach ( $lbs as $i => $lb ) {
493 if ( $masterPositions[$i] ) {
494 // The DBMS may not support getMasterPos() or the whole
495 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
496 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
497 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
503 throw new DBReplicationWaitError(
504 "Could not wait for replica DBs to catch up to " .
505 implode( ', ', $failed )
511 * Add a callback to be run in every call to waitForReplication() before waiting
513 * Callbacks must clear any transactions that they start
515 * @param string $name Callback name
516 * @param callable|null $callback Use null to unset a callback
519 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
521 $this->replicationWaitCallbacks
[$name] = $callback;
523 unset( $this->replicationWaitCallbacks
[$name] );
528 * Get a token asserting that no transaction writes are active
530 * @param string $fname Caller name (e.g. __METHOD__)
531 * @return mixed A value to pass to commitAndWaitForReplication()
534 public function getEmptyTransactionTicket( $fname ) {
535 if ( $this->hasMasterChanges() ) {
536 $this->trxLogger
->error( __METHOD__
. ": $fname does not have outer scope." );
540 return $this->ticket
;
544 * Convenience method for safely running commitMasterChanges()/waitForReplication()
546 * This will commit and wait unless $ticket indicates it is unsafe to do so
548 * @param string $fname Caller name (e.g. __METHOD__)
549 * @param mixed $ticket Result of getEmptyTransactionTicket()
550 * @param array $opts Options to waitForReplication()
551 * @throws DBReplicationWaitError
554 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
555 if ( $ticket !== $this->ticket
) {
556 $logger = LoggerFactory
::getInstance( 'DBPerformance' );
557 $logger->error( __METHOD__
. ": cannot commit; $fname does not have outer scope." );
561 // The transaction owner and any caller with the empty transaction ticket can commit
562 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
563 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
564 $this->trxLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}." );
565 $fnameEffective = $this->trxRoundId
;
567 $fnameEffective = $fname;
570 $this->commitMasterChanges( $fnameEffective );
571 $this->waitForReplication( $opts );
572 // If a nested caller committed on behalf of $fname, start another empty $fname
573 // transaction, leaving the caller with the same empty transaction state as before.
574 if ( $fnameEffective !== $fname ) {
575 $this->beginMasterChanges( $fnameEffective );
580 * @param string $dbName DB master name (e.g. "db1052")
581 * @return float|bool UNIX timestamp when client last touched the DB or false if not recent
584 public function getChronologyProtectorTouched( $dbName ) {
585 return $this->chronProt
->getTouched( $dbName );
589 * Disable the ChronologyProtector for all load balancers
591 * This can be called at the start of special API entry points
595 public function disableChronologyProtection() {
596 $this->chronProt
->setEnabled( false );
600 * @return ChronologyProtector
602 protected function newChronologyProtector() {
603 $request = RequestContext
::getMain()->getRequest();
604 $chronProt = new ChronologyProtector(
605 ObjectCache
::getMainStashInstance(),
607 'ip' => $request->getIP(),
608 'agent' => $request->getHeader( 'User-Agent' ),
610 $request->getFloat( 'cpPosTime', $request->getCookie( 'cpPosTime', '' ) )
612 $chronProt->setLogger( $this->replLogger
);
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' ],
673 'hostname' => wfHostname()
678 * @param LoadBalancer $lb
680 protected function initLoadBalancer( LoadBalancer
$lb ) {
681 if ( $this->trxRoundId
!== false ) {
682 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
687 * Append ?cpPosTime parameter to a URL for ChronologyProtector purposes if needed
689 * Note that unlike cookies, this works accross domains
692 * @param float $time UNIX timestamp just before shutdown() was called
696 public function appendPreShutdownTimeAsQuery( $url, $time ) {
698 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$usedCluster ) {
699 $usedCluster |
= ( $lb->getServerCount() > 1 );
702 if ( !$usedCluster ) {
703 return $url; // no master/replica clusters touched
706 return wfAppendQuery( $url, [ 'cpPosTime' => $time ] );
710 * Close all open database connections on all open load balancers.
713 public function closeAll() {
714 $this->forEachLBCallMethod( 'closeAll', [] );