MediaWiki  master
LBFactory.php
Go to the documentation of this file.
1 <?php
26 use Psr\Log\LoggerInterface;
28 
33 abstract class LBFactory implements DestructibleService {
34 
36  protected $chronProt;
37 
39  protected $trxProfiler;
40 
42  protected $logger;
43 
45  protected $readOnlyReason = false;
46 
47  const SHUTDOWN_NO_CHRONPROT = 1; // don't save ChronologyProtector positions (for async code)
48 
53  public function __construct( array $conf ) {
54  if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
55  $this->readOnlyReason = $conf['readOnlyReason'];
56  }
57 
58  $this->chronProt = $this->newChronologyProtector();
59  $this->trxProfiler = Profiler::instance()->getTransactionProfiler();
60  $this->logger = LoggerFactory::getInstance( 'DBTransaction' );
61  }
62 
68  public function destroy() {
69  $this->shutdown();
70  $this->forEachLBCallMethod( 'disable' );
71  }
72 
77  public static function disableBackend() {
78  MediaWikiServices::disableStorageBackend();
79  }
80 
88  public static function singleton() {
89  return MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
90  }
91 
100  public static function getLBFactoryClass( array $config ) {
101  // For configuration backward compatibility after removing
102  // underscores from class names in MediaWiki 1.23.
103  $bcClasses = [
104  'LBFactory_Simple' => 'LBFactorySimple',
105  'LBFactory_Single' => 'LBFactorySingle',
106  'LBFactory_Multi' => 'LBFactoryMulti',
107  'LBFactory_Fake' => 'LBFactoryFake',
108  ];
109 
110  $class = $config['class'];
111 
112  if ( isset( $bcClasses[$class] ) ) {
113  $class = $bcClasses[$class];
114  wfDeprecated(
115  '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
116  '1.23'
117  );
118  }
119 
120  return $class;
121  }
122 
128  public static function destroyInstance() {
129  self::singleton()->destroy();
130  }
131 
139  abstract public function newMainLB( $wiki = false );
140 
147  abstract public function getMainLB( $wiki = false );
148 
158  abstract protected function newExternalLB( $cluster, $wiki = false );
159 
167  abstract public function &getExternalLB( $cluster, $wiki = false );
168 
177  abstract public function forEachLB( $callback, array $params = [] );
178 
184  public function shutdown( $flags = 0 ) {
185  }
186 
193  private function forEachLBCallMethod( $methodName, array $args = [] ) {
194  $this->forEachLB(
195  function ( LoadBalancer $loadBalancer, $methodName, array $args ) {
196  call_user_func_array( [ $loadBalancer, $methodName ], $args );
197  },
198  [ $methodName, $args ]
199  );
200  }
201 
210  public function commitAll( $fname = __METHOD__, array $options = [] ) {
212  $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
213  }
214 
221  public function commitMasterChanges( $fname = __METHOD__, array $options = [] ) {
222  // Perform all pre-commit callbacks, aborting on failure
223  $this->forEachLBCallMethod( 'runMasterPreCommitCallbacks' );
224  // Perform all pre-commit checks, aborting on failure
225  $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
226  // Log the DBs and methods involved in multi-DB transactions
227  $this->logIfMultiDbTransaction();
228  // Actually perform the commit on all master DB connections
229  $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
230  // Run all post-commit callbacks
231  $this->forEachLBCallMethod( 'runMasterPostCommitCallbacks' );
232  // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
233  $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
234  }
235 
241  public function rollbackMasterChanges( $fname = __METHOD__ ) {
242  $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
243  }
244 
248  private function logIfMultiDbTransaction() {
249  $callersByDB = [];
250  $this->forEachLB( function ( LoadBalancer $lb ) use ( &$callersByDB ) {
251  $masterName = $lb->getServerName( $lb->getWriterIndex() );
252  $callers = $lb->pendingMasterChangeCallers();
253  if ( $callers ) {
254  $callersByDB[$masterName] = $callers;
255  }
256  } );
257 
258  if ( count( $callersByDB ) >= 2 ) {
259  $dbs = implode( ', ', array_keys( $callersByDB ) );
260  $msg = "Multi-DB transaction [{$dbs}]:\n";
261  foreach ( $callersByDB as $db => $callers ) {
262  $msg .= "$db: " . implode( '; ', $callers ) . "\n";
263  }
264  $this->logger->info( $msg );
265  }
266  }
267 
273  public function hasMasterChanges() {
274  $ret = false;
275  $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
276  $ret = $ret || $lb->hasMasterChanges();
277  } );
278 
279  return $ret;
280  }
281 
287  public function laggedSlaveUsed() {
288  $ret = false;
289  $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
290  $ret = $ret || $lb->laggedSlaveUsed();
291  } );
292 
293  return $ret;
294  }
295 
301  public function hasOrMadeRecentMasterChanges() {
302  $ret = false;
303  $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
305  } );
306  return $ret;
307  }
308 
333  public function waitForReplication( array $opts = [] ) {
334  $opts += [
335  'wiki' => false,
336  'cluster' => false,
337  'timeout' => 60,
338  'ifWritesSince' => null
339  ];
340 
341  // Figure out which clusters need to be checked
343  $lbs = [];
344  if ( $opts['cluster'] !== false ) {
345  $lbs[] = $this->getExternalLB( $opts['cluster'] );
346  } elseif ( $opts['wiki'] !== false ) {
347  $lbs[] = $this->getMainLB( $opts['wiki'] );
348  } else {
349  $this->forEachLB( function ( LoadBalancer $lb ) use ( &$lbs ) {
350  $lbs[] = $lb;
351  } );
352  if ( !$lbs ) {
353  return; // nothing actually used
354  }
355  }
356 
357  // Get all the master positions of applicable DBs right now.
358  // This can be faster since waiting on one cluster reduces the
359  // time needed to wait on the next clusters.
360  $masterPositions = array_fill( 0, count( $lbs ), false );
361  foreach ( $lbs as $i => $lb ) {
362  if ( $lb->getServerCount() <= 1 ) {
363  // Bug 27975 - Don't try to wait for slaves if there are none
364  // Prevents permission error when getting master position
365  continue;
366  } elseif ( $opts['ifWritesSince']
367  && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
368  ) {
369  continue; // no writes since the last wait
370  }
371  $masterPositions[$i] = $lb->getMasterPos();
372  }
373 
374  $failed = [];
375  foreach ( $lbs as $i => $lb ) {
376  if ( $masterPositions[$i] ) {
377  // The DBMS may not support getMasterPos() or the whole
378  // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
379  if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
380  $failed[] = $lb->getServerName( $lb->getWriterIndex() );
381  }
382  }
383  }
384 
385  if ( $failed ) {
386  throw new DBReplicationWaitError(
387  "Could not wait for slaves to catch up to " .
388  implode( ', ', $failed )
389  );
390  }
391  }
392 
400  public function disableChronologyProtection() {
401  $this->chronProt->setEnabled( false );
402  }
403 
407  protected function newChronologyProtector() {
408  $request = RequestContext::getMain()->getRequest();
411  [
412  'ip' => $request->getIP(),
413  'agent' => $request->getHeader( 'User-Agent' )
414  ]
415  );
416  if ( PHP_SAPI === 'cli' ) {
417  $chronProt->setEnabled( false );
418  } elseif ( $request->getHeader( 'ChronologyProtection' ) === 'false' ) {
419  // Request opted out of using position wait logic. This is useful for requests
420  // done by the job queue or background ETL that do not have a meaningful session.
421  $chronProt->setWaitEnabled( false );
422  }
423 
424  return $chronProt;
425  }
426 
431  // Get all the master positions needed
432  $this->forEachLB( function ( LoadBalancer $lb ) use ( $cp ) {
433  $cp->shutdownLB( $lb );
434  } );
435  // Write them to the stash
436  $unsavedPositions = $cp->shutdown();
437  // If the positions failed to write to the stash, at least wait on local datacenter
438  // slaves to catch up before responding. Even if there are several DCs, this increases
439  // the chance that the user will see their own changes immediately afterwards. As long
440  // as the sticky DC cookie applies (same domain), this is not even an issue.
441  $this->forEachLB( function ( LoadBalancer $lb ) use ( $unsavedPositions ) {
442  $masterName = $lb->getServerName( $lb->getWriterIndex() );
443  if ( isset( $unsavedPositions[$masterName] ) ) {
444  $lb->waitForAll( $unsavedPositions[$masterName] );
445  }
446  } );
447  }
448 
453  public function closeAll() {
454  $this->forEachLBCallMethod( 'closeAll', [] );
455  }
456 
457 }
458 
462 class DBAccessError extends MWException {
463  public function __construct() {
464  parent::__construct( "Mediawiki tried to access the database via wfGetDB(). " .
465  "This is not allowed, because database access has been disabled." );
466  }
467 }
468 
472 class DBReplicationWaitError extends Exception {
473 }
newMainLB($wiki=false)
Create a new load balancer object.
LoggerInterface $logger
Definition: LBFactory.php:42
the array() calling protocol came about after MediaWiki 1.4rc1.
shutdownChronologyProtector(ChronologyProtector $cp)
Definition: LBFactory.php:430
newChronologyProtector()
Definition: LBFactory.php:407
shutdown($flags=0)
Prepare all tracked load balancers for shutdown.
Definition: LBFactory.php:184
& getExternalLB($cluster, $wiki=false)
Get a cached (tracked) load balancer for external storage.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
__construct(array $conf)
Construct a factory based on a configuration array (typically from $wgLBFactoryConf) ...
Definition: LBFactory.php:53
static instance()
Singleton.
Definition: Profiler.php:60
forEachLB($callback, array $params=[])
Execute a function for each tracked load balancer The callback is called with the load balancer as th...
commitAll($fname=__METHOD__, array $options=[])
Commit on all connections.
Definition: LBFactory.php:210
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2588
newExternalLB($cluster, $wiki=false)
Create a new load balancer for external storage.
static getMainStashInstance()
Get the cache object for the main stash.
static disableBackend()
Disables all access to the load balancer, will cause all database access to throw a DBAccessError...
Definition: LBFactory.php:77
commitMasterChanges($fname=__METHOD__, array $options=[])
Commit changes on all master connections.
Definition: LBFactory.php:221
if($line===false) $args
Definition: cdb.php:64
shutdownLB(LoadBalancer $lb)
Notify the ChronologyProtector that the LoadBalancer is about to shut down.
Database load balancing object.
const SHUTDOWN_NO_CHRONPROT
Definition: LBFactory.php:47
rollbackMasterChanges($fname=__METHOD__)
Rollback changes on all master connections.
Definition: LBFactory.php:241
Exception class for replica DB wait timeouts.
Definition: LBFactory.php:472
static singleton()
Get an LBFactory instance.
Definition: LBFactory.php:88
static getMain()
Static methods.
An interface for generating database load balancers.
Definition: LBFactory.php:33
waitForReplication(array $opts=[])
Waits for the slave DBs to catch up to the current master position.
Definition: LBFactory.php:333
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1020
MediaWiki exception.
Definition: MWException.php:26
hasMasterChanges()
Determine if there are pending changes in a transaction by this thread.
Exception class for attempted DB access.
Definition: LBFactory.php:462
hasMasterChanges()
Determine if any master connection has pending changes.
Definition: LBFactory.php:273
$params
string bool $readOnlyReason
Reason all LBs are read-only or false if not.
Definition: LBFactory.php:45
wfDeprecated($function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
static destroyInstance()
Shut down, close connections and destroy the cached instance.
Definition: LBFactory.php:128
closeAll()
Close all open database connections on all open load balancers.
Definition: LBFactory.php:453
getMainLB($wiki=false)
Get a cached (tracked) load balancer object.
disableChronologyProtection()
Disable the ChronologyProtector for all load balancers.
Definition: LBFactory.php:400
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1816
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
hasOrMadeRecentMasterChanges($age=null)
Check if this load balancer object had any recent or still pending writes issued against it by this P...
forEachLBCallMethod($methodName, array $args=[])
Call a method of each tracked load balancer.
Definition: LBFactory.php:193
static getLBFactoryClass(array $config)
Returns the LBFactory class to use and the load balancer configuration.
Definition: LBFactory.php:100
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
Class for ensuring a consistent ordering of events as seen by the user, despite replication.
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2458
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined...
Definition: Setup.php:36
shutdown()
Notify the ChronologyProtector that the LBFactory is done calling shutdownLB() for now...
destroy()
Disables all load balancers.
Definition: LBFactory.php:68
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method.MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances.The"Spi"in MediaWiki\Logger\Spi stands for"service provider interface".An SPI is an API intended to be implemented or extended by a third party.This software design pattern is intended to enable framework extension and replaceable components.It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki.The service provider interface allows the backend logging library to be implemented in multiple ways.The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime.This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance.Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
laggedSlaveUsed()
Detemine if any lagged slave connection was used.
Definition: LBFactory.php:287
pendingMasterChangeCallers()
Get the list of callers that have pending master changes.
TransactionProfiler $trxProfiler
Definition: LBFactory.php:39
getServerName($i)
Get the host name or IP address of the server with the specified index Prefer a readable name if avai...
waitForAll($pos, $timeout=null)
Set the master wait position and wait for ALL slaves to catch up to it.
DestructibleService defines a standard interface for shutting down a service instance.
logIfMultiDbTransaction()
Log query info if multi DB transactions are going to be committed now.
Definition: LBFactory.php:248
hasOrMadeRecentMasterChanges()
Determine if any master connection has pending/written changes from this request. ...
Definition: LBFactory.php:301
ChronologyProtector $chronProt
Definition: LBFactory.php:36