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 Reason all LBs are read-only or false if not */
48 protected $readOnlyReason = false;
50 const SHUTDOWN_NO_CHRONPROT
= 1; // don't save ChronologyProtector positions (for async code)
53 * Construct a factory based on a configuration array (typically from $wgLBFactoryConf)
55 * @TODO: inject objects via dependency framework
57 public function __construct( array $conf ) {
58 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
59 $this->readOnlyReason
= $conf['readOnlyReason'];
61 $this->chronProt
= $this->newChronologyProtector();
62 $this->trxProfiler
= Profiler
::instance()->getTransactionProfiler();
63 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
64 $cache = ObjectCache
::getLocalServerInstance();
65 if ( $cache->getQoS( $cache::ATTR_EMULATION
) > $cache::QOS_EMULATION_SQL
) {
66 $this->srvCache
= $cache;
68 $this->srvCache
= new EmptyBagOStuff();
70 $wCache = ObjectCache
::getMainWANInstance();
71 if ( $wCache->getQoS( $wCache::ATTR_EMULATION
) > $wCache::QOS_EMULATION_SQL
) {
72 $this->wanCache
= $wCache;
74 $this->wanCache
= WANObjectCache
::newEmpty();
76 $this->trxLogger
= LoggerFactory
::getInstance( 'DBTransaction' );
77 $this->ticket
= mt_rand();
81 * Disables all load balancers. All connections are closed, and any attempt to
82 * open a new connection will result in a DBAccessError.
83 * @see LoadBalancer::disable()
85 public function destroy() {
87 $this->forEachLBCallMethod( 'disable' );
91 * Disables all access to the load balancer, will cause all database access
92 * to throw a DBAccessError
94 public static function disableBackend() {
95 MediaWikiServices
::disableStorageBackend();
99 * Get an LBFactory instance
101 * @deprecated since 1.27, use MediaWikiServices::getDBLoadBalancerFactory() instead.
105 public static function singleton() {
106 return MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
110 * Returns the LBFactory class to use and the load balancer configuration.
112 * @todo instead of this, use a ServiceContainer for managing the different implementations.
114 * @param array $config (e.g. $wgLBFactoryConf)
115 * @return string Class name
117 public static function getLBFactoryClass( array $config ) {
118 // For configuration backward compatibility after removing
119 // underscores from class names in MediaWiki 1.23.
121 'LBFactory_Simple' => 'LBFactorySimple',
122 'LBFactory_Single' => 'LBFactorySingle',
123 'LBFactory_Multi' => 'LBFactoryMulti',
124 'LBFactory_Fake' => 'LBFactoryFake',
127 $class = $config['class'];
129 if ( isset( $bcClasses[$class] ) ) {
130 $class = $bcClasses[$class];
132 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
141 * Shut down, close connections and destroy the cached instance.
143 * @deprecated since 1.27, use LBFactory::destroy()
145 public static function destroyInstance() {
146 self
::singleton()->destroy();
150 * Create a new load balancer object. The resulting object will be untracked,
151 * not chronology-protected, and the caller is responsible for cleaning it up.
153 * @param bool|string $wiki Wiki ID, or false for the current wiki
154 * @return LoadBalancer
156 abstract public function newMainLB( $wiki = false );
159 * Get a cached (tracked) load balancer object.
161 * @param bool|string $wiki Wiki ID, or false for the current wiki
162 * @return LoadBalancer
164 abstract public function getMainLB( $wiki = false );
167 * Create a new load balancer for external storage. The resulting object will be
168 * untracked, not chronology-protected, and the caller is responsible for
171 * @param string $cluster External storage cluster, or false for core
172 * @param bool|string $wiki Wiki ID, or false for the current wiki
173 * @return LoadBalancer
175 abstract protected function newExternalLB( $cluster, $wiki = false );
178 * Get a cached (tracked) load balancer for external storage
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 public function &getExternalLB( $cluster, $wiki = false );
187 * Execute a function for each tracked load balancer
188 * The callback is called with the load balancer as the first parameter,
189 * and $params passed as the subsequent parameters.
191 * @param callable $callback
192 * @param array $params
194 abstract public function forEachLB( $callback, array $params = [] );
197 * Prepare all tracked load balancers for shutdown
198 * @param integer $flags Supports SHUTDOWN_* flags
201 public function shutdown( $flags = 0 ) {
205 * Call a method of each tracked load balancer
207 * @param string $methodName
210 private function forEachLBCallMethod( $methodName, array $args = [] ) {
212 function ( LoadBalancer
$loadBalancer, $methodName, array $args ) {
213 call_user_func_array( [ $loadBalancer, $methodName ], $args );
215 [ $methodName, $args ]
220 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
222 * The DBO_TRX setting will be reverted to the default in each of these methods:
223 * - commitMasterChanges()
224 * - rollbackMasterChanges()
226 * This allows for custom transaction rounds from any outer transaction scope.
228 * @param string $fname
231 public function beginMasterChanges( $fname = __METHOD__
) {
232 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
236 * Commit on all connections. Done for two reasons:
237 * 1. To commit changes to the masters.
238 * 2. To release the snapshot on all connections, master and slave.
239 * @param string $fname Caller name
240 * @param array $options Options map:
241 * - maxWriteDuration: abort if more than this much time was spent in write queries
243 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
244 $this->commitMasterChanges( $fname, $options );
245 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
249 * Commit changes on all master connections
250 * @param string $fname Caller name
251 * @param array $options Options map:
252 * - maxWriteDuration: abort if more than this much time was spent in write queries
255 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
256 // Perform all pre-commit callbacks, aborting on failure
257 $this->forEachLBCallMethod( 'runMasterPreCommitCallbacks' );
258 // Perform all pre-commit checks, aborting on failure
259 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
260 // Log the DBs and methods involved in multi-DB transactions
261 $this->logIfMultiDbTransaction();
262 // Actually perform the commit on all master DB connections
263 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
264 // Run all post-commit callbacks
265 /** @var Exception $e */
266 $e = null; // first callback exception
267 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$e ) {
268 $ex = $lb->runMasterPostCommitCallbacks();
271 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
272 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
273 // Throw any last post-commit callback error
274 if ( $e instanceof Exception
) {
280 * Rollback changes on all master connections
281 * @param string $fname Caller name
284 public function rollbackMasterChanges( $fname = __METHOD__
) {
285 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
289 * Log query info if multi DB transactions are going to be committed now
291 private function logIfMultiDbTransaction() {
293 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$callersByDB ) {
294 $masterName = $lb->getServerName( $lb->getWriterIndex() );
295 $callers = $lb->pendingMasterChangeCallers();
297 $callersByDB[$masterName] = $callers;
301 if ( count( $callersByDB ) >= 2 ) {
302 $dbs = implode( ', ', array_keys( $callersByDB ) );
303 $msg = "Multi-DB transaction [{$dbs}]:\n";
304 foreach ( $callersByDB as $db => $callers ) {
305 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
307 $this->trxLogger
->info( $msg );
312 * Determine if any master connection has pending changes
316 public function hasMasterChanges() {
318 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
319 $ret = $ret ||
$lb->hasMasterChanges();
326 * Detemine if any lagged slave connection was used
330 public function laggedSlaveUsed() {
332 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
333 $ret = $ret ||
$lb->laggedSlaveUsed();
340 * Determine if any master connection has pending/written changes from this request
344 public function hasOrMadeRecentMasterChanges() {
346 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
347 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges();
353 * Waits for the slave DBs to catch up to the current master position
355 * Use this when updating very large numbers of rows, as in maintenance scripts,
356 * to avoid causing too much lag. Of course, this is a no-op if there are no slaves.
358 * By default this waits on all DB clusters actually used in this request.
359 * This makes sense when lag being waiting on is caused by the code that does this check.
360 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
361 * that were not changed since the last wait check. To forcefully wait on a specific cluster
362 * for a given wiki, use the 'wiki' parameter. To forcefully wait on an "external" cluster,
363 * use the "cluster" parameter.
365 * Never call this function after a large DB write that is *still* in a transaction.
366 * It only makes sense to call this after the possible lag inducing changes were committed.
368 * @param array $opts Optional fields that include:
369 * - wiki : wait on the load balancer DBs that handles the given wiki
370 * - cluster : wait on the given external load balancer DBs
371 * - timeout : Max wait time. Default: ~60 seconds
372 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
373 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
376 public function waitForReplication( array $opts = [] ) {
381 'ifWritesSince' => null
384 // Figure out which clusters need to be checked
385 /** @var LoadBalancer[] $lbs */
387 if ( $opts['cluster'] !== false ) {
388 $lbs[] = $this->getExternalLB( $opts['cluster'] );
389 } elseif ( $opts['wiki'] !== false ) {
390 $lbs[] = $this->getMainLB( $opts['wiki'] );
392 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$lbs ) {
396 return; // nothing actually used
400 // Get all the master positions of applicable DBs right now.
401 // This can be faster since waiting on one cluster reduces the
402 // time needed to wait on the next clusters.
403 $masterPositions = array_fill( 0, count( $lbs ), false );
404 foreach ( $lbs as $i => $lb ) {
405 if ( $lb->getServerCount() <= 1 ) {
406 // Bug 27975 - Don't try to wait for slaves if there are none
407 // Prevents permission error when getting master position
409 } elseif ( $opts['ifWritesSince']
410 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
412 continue; // no writes since the last wait
414 $masterPositions[$i] = $lb->getMasterPos();
418 foreach ( $lbs as $i => $lb ) {
419 if ( $masterPositions[$i] ) {
420 // The DBMS may not support getMasterPos() or the whole
421 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
422 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
423 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
429 throw new DBReplicationWaitError(
430 "Could not wait for slaves to catch up to " .
431 implode( ', ', $failed )
437 * Get a token asserting that no transaction writes are active
439 * @param string $fname Caller name (e.g. __METHOD__)
440 * @return mixed A value to pass to commitAndWaitForReplication()
443 public function getEmptyTransactionTicket( $fname ) {
444 if ( $this->hasMasterChanges() ) {
445 $this->trxLogger
->error( __METHOD__
. ": $fname does not have outer scope." );
449 return $this->ticket
;
453 * Convenience method for safely running commitMasterChanges()/waitForReplication()
455 * This will commit and wait unless $ticket indicates it is unsafe to do so
457 * @param string $fname Caller name (e.g. __METHOD__)
458 * @param mixed $ticket Result of getOuterTransactionScopeTicket()
459 * @param array $opts Options to waitForReplication()
460 * @throws DBReplicationWaitError
463 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
464 if ( $ticket !== $this->ticket
) {
465 $logger = LoggerFactory
::getInstance( 'DBPerformance' );
466 $logger->error( __METHOD__
. ": cannot commit; $fname does not have outer scope." );
470 $this->commitMasterChanges( $fname );
471 $this->waitForReplication( $opts );
475 * Disable the ChronologyProtector for all load balancers
477 * This can be called at the start of special API entry points
481 public function disableChronologyProtection() {
482 $this->chronProt
->setEnabled( false );
486 * @return ChronologyProtector
488 protected function newChronologyProtector() {
489 $request = RequestContext
::getMain()->getRequest();
490 $chronProt = new ChronologyProtector(
491 ObjectCache
::getMainStashInstance(),
493 'ip' => $request->getIP(),
494 'agent' => $request->getHeader( 'User-Agent' )
497 if ( PHP_SAPI
=== 'cli' ) {
498 $chronProt->setEnabled( false );
499 } elseif ( $request->getHeader( 'ChronologyProtection' ) === 'false' ) {
500 // Request opted out of using position wait logic. This is useful for requests
501 // done by the job queue or background ETL that do not have a meaningful session.
502 $chronProt->setWaitEnabled( false );
509 * @param ChronologyProtector $cp
511 protected function shutdownChronologyProtector( ChronologyProtector
$cp ) {
512 // Get all the master positions needed
513 $this->forEachLB( function ( LoadBalancer
$lb ) use ( $cp ) {
514 $cp->shutdownLB( $lb );
516 // Write them to the stash
517 $unsavedPositions = $cp->shutdown();
518 // If the positions failed to write to the stash, at least wait on local datacenter
519 // slaves to catch up before responding. Even if there are several DCs, this increases
520 // the chance that the user will see their own changes immediately afterwards. As long
521 // as the sticky DC cookie applies (same domain), this is not even an issue.
522 $this->forEachLB( function ( LoadBalancer
$lb ) use ( $unsavedPositions ) {
523 $masterName = $lb->getServerName( $lb->getWriterIndex() );
524 if ( isset( $unsavedPositions[$masterName] ) ) {
525 $lb->waitForAll( $unsavedPositions[$masterName] );
531 * Close all open database connections on all open load balancers.
534 public function closeAll() {
535 $this->forEachLBCallMethod( 'closeAll', [] );
541 * Exception class for attempted DB access
543 class DBAccessError
extends MWException
{
544 public function __construct() {
545 parent
::__construct( "Mediawiki tried to access the database via wfGetDB(). " .
546 "This is not allowed, because database access has been disabled." );
551 * Exception class for replica DB wait timeouts
553 class DBReplicationWaitError
extends Exception
{