MediaWiki REL1_27
LBFactory.php
Go to the documentation of this file.
1<?php
24use Psr\Log\LoggerInterface;
26
31abstract class LBFactory {
33 protected $chronProt;
34
36 protected $trxProfiler;
37
39 protected $logger;
40
42 private static $instance;
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
67 public static function disableBackend() {
69 self::$instance = new LBFactoryFake( $wgLBFactoryConf );
70 }
71
77 public static function singleton() {
79
80 if ( is_null( self::$instance ) ) {
82 $config = $wgLBFactoryConf;
83 if ( !isset( $config['readOnlyReason'] ) ) {
84 $config['readOnlyReason'] = wfConfiguredReadOnlyReason();
85 }
86 self::$instance = new $class( $config );
87 }
88
89 return self::$instance;
90 }
91
98 public static function getLBFactoryClass( array $config ) {
99 // For configuration backward compatibility after removing
100 // underscores from class names in MediaWiki 1.23.
101 $bcClasses = [
102 'LBFactory_Simple' => 'LBFactorySimple',
103 'LBFactory_Single' => 'LBFactorySingle',
104 'LBFactory_Multi' => 'LBFactoryMulti',
105 'LBFactory_Fake' => 'LBFactoryFake',
106 ];
107
108 $class = $config['class'];
109
110 if ( isset( $bcClasses[$class] ) ) {
111 $class = $bcClasses[$class];
113 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
114 '1.23'
115 );
116 }
117
118 return $class;
119 }
120
124 public static function destroyInstance() {
125 if ( self::$instance ) {
126 self::$instance->shutdown();
127 self::$instance->forEachLBCallMethod( 'closeAll' );
128 self::$instance = null;
129 }
130 }
131
137 public static function setInstance( $instance ) {
139 self::$instance = $instance;
140 }
141
149 abstract public function newMainLB( $wiki = false );
150
157 abstract public function getMainLB( $wiki = false );
158
168 abstract protected function newExternalLB( $cluster, $wiki = false );
169
177 abstract public function &getExternalLB( $cluster, $wiki = false );
178
187 abstract public function forEachLB( $callback, array $params = [] );
188
194 public function shutdown( $flags = 0 ) {
195 }
196
203 private function forEachLBCallMethod( $methodName, array $args = [] ) {
204 $this->forEachLB(
205 function ( LoadBalancer $loadBalancer, $methodName, array $args ) {
206 call_user_func_array( [ $loadBalancer, $methodName ], $args );
207 },
208 [ $methodName, $args ]
209 );
210 }
211
218 public function commitAll( $fname = __METHOD__ ) {
219 $this->logMultiDbTransaction();
220
221 $start = microtime( true );
222 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
223 $timeMs = 1000 * ( microtime( true ) - $start );
224
225 RequestContext::getMain()->getStats()->timing( "db.commit-all", $timeMs );
226 }
227
234 public function commitMasterChanges( $fname = __METHOD__, array $options = [] ) {
235 $limit = isset( $options['maxWriteDuration'] ) ? $options['maxWriteDuration'] : 0;
236
237 $this->logMultiDbTransaction();
238 $this->forEachLB( function ( LoadBalancer $lb ) use ( $limit ) {
239 $lb->forEachOpenConnection( function ( IDatabase $db ) use ( $limit ) {
241 if ( $limit > 0 && $time > $limit ) {
242 throw new DBTransactionError(
243 $db,
244 wfMessage( 'transaction-duration-limit-exceeded', $time, $limit )->text()
245 );
246 }
247 } );
248 } );
249
250 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
251 }
252
258 public function rollbackMasterChanges( $fname = __METHOD__ ) {
259 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
260 }
261
265 private function logMultiDbTransaction() {
266 $callersByDB = [];
267 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$callersByDB ) {
268 $masterName = $lb->getServerName( $lb->getWriterIndex() );
269 $callers = $lb->pendingMasterChangeCallers();
270 if ( $callers ) {
271 $callersByDB[$masterName] = $callers;
272 }
273 } );
274
275 if ( count( $callersByDB ) >= 2 ) {
276 $dbs = implode( ', ', array_keys( $callersByDB ) );
277 $msg = "Multi-DB transaction [{$dbs}]:\n";
278 foreach ( $callersByDB as $db => $callers ) {
279 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
280 }
281 $this->logger->info( $msg );
282 }
283 }
284
290 public function hasMasterChanges() {
291 $ret = false;
292 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
293 $ret = $ret || $lb->hasMasterChanges();
294 } );
295
296 return $ret;
297 }
298
304 public function laggedSlaveUsed() {
305 $ret = false;
306 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
307 $ret = $ret || $lb->laggedSlaveUsed();
308 } );
309
310 return $ret;
311 }
312
319 $ret = false;
320 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
322 } );
323 return $ret;
324 }
325
350 public function waitForReplication( array $opts = [] ) {
351 $opts += [
352 'wiki' => false,
353 'cluster' => false,
354 'timeout' => 60,
355 'ifWritesSince' => null
356 ];
357
358 // Figure out which clusters need to be checked
360 $lbs = [];
361 if ( $opts['cluster'] !== false ) {
362 $lbs[] = $this->getExternalLB( $opts['cluster'] );
363 } elseif ( $opts['wiki'] !== false ) {
364 $lbs[] = $this->getMainLB( $opts['wiki'] );
365 } else {
366 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$lbs ) {
367 $lbs[] = $lb;
368 } );
369 if ( !$lbs ) {
370 return; // nothing actually used
371 }
372 }
373
374 // Get all the master positions of applicable DBs right now.
375 // This can be faster since waiting on one cluster reduces the
376 // time needed to wait on the next clusters.
377 $masterPositions = array_fill( 0, count( $lbs ), false );
378 foreach ( $lbs as $i => $lb ) {
379 if ( $lb->getServerCount() <= 1 ) {
380 // Bug 27975 - Don't try to wait for slaves if there are none
381 // Prevents permission error when getting master position
382 continue;
383 } elseif ( $opts['ifWritesSince']
384 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
385 ) {
386 continue; // no writes since the last wait
387 }
388 $masterPositions[$i] = $lb->getMasterPos();
389 }
390
391 $failed = [];
392 foreach ( $lbs as $i => $lb ) {
393 if ( $masterPositions[$i] ) {
394 // The DBMS may not support getMasterPos() or the whole
395 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
396 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
397 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
398 }
399 }
400 }
401
402 if ( $failed ) {
403 throw new DBReplicationWaitError(
404 "Could not wait for slaves to catch up to " .
405 implode( ', ', $failed )
406 );
407 }
408 }
409
417 public function disableChronologyProtection() {
418 $this->chronProt->setEnabled( false );
419 }
420
424 protected function newChronologyProtector() {
428 [
429 'ip' => $request->getIP(),
430 'agent' => $request->getHeader( 'User-Agent' )
431 ]
432 );
433 if ( PHP_SAPI === 'cli' ) {
434 $chronProt->setEnabled( false );
435 } elseif ( $request->getHeader( 'ChronologyProtection' ) === 'false' ) {
436 // Request opted out of using position wait logic. This is useful for requests
437 // done by the job queue or background ETL that do not have a meaningful session.
438 $chronProt->setWaitEnabled( false );
439 }
440
441 return $chronProt;
442 }
443
448 // Get all the master positions needed
449 $this->forEachLB( function ( LoadBalancer $lb ) use ( $cp ) {
450 $cp->shutdownLB( $lb );
451 } );
452 // Write them to the stash
453 $unsavedPositions = $cp->shutdown();
454 // If the positions failed to write to the stash, at least wait on local datacenter
455 // slaves to catch up before responding. Even if there are several DCs, this increases
456 // the chance that the user will see their own changes immediately afterwards. As long
457 // as the sticky DC cookie applies (same domain), this is not even an issue.
458 $this->forEachLB( function ( LoadBalancer $lb ) use ( $unsavedPositions ) {
459 $masterName = $lb->getServerName( $lb->getWriterIndex() );
460 if ( isset( $unsavedPositions[$masterName] ) ) {
461 $lb->waitForAll( $unsavedPositions[$masterName] );
462 }
463 } );
464 }
465}
466
471 public function __construct() {
472 parent::__construct( "Mediawiki tried to access the database via wfGetDB(). " .
473 "This is not allowed." );
474 }
475}
476
480class DBReplicationWaitError extends Exception {
481}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgLBFactoryConf
Load balancer factory configuration To set up a multi-master wiki farm, set the class here to somethi...
wfConfiguredReadOnlyReason()
Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
$i
Definition Parser.php:1694
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
Definition Setup.php:35
if( $line===false) $args
Definition cdb.php:64
Class for ensuring a consistent ordering of events as seen by the user, despite replication.
shutdownLB(LoadBalancer $lb)
Notify the ChronologyProtector that the LoadBalancer is about to shut down.
shutdown()
Notify the ChronologyProtector that the LBFactory is done calling shutdownLB() for now.
getRequest()
Get the WebRequest object.
Exception class for attempted DB access.
Exception class for replica DB wait timeouts.
LBFactory class that throws an error on any attempt to use it.
An interface for generating database load balancers.
Definition LBFactory.php:31
forEachLBCallMethod( $methodName, array $args=[])
Call a method of each tracked load balancer.
const SHUTDOWN_NO_CHRONPROT
Definition LBFactory.php:47
logMultiDbTransaction()
Log query info if multi DB transactions are going to be committed now.
laggedSlaveUsed()
Detemine if any lagged slave connection was used.
static setInstance( $instance)
Set the instance to be the given object.
static getLBFactoryClass(array $config)
Returns the LBFactory class to use and the load balancer configuration.
Definition LBFactory.php:98
static singleton()
Get an LBFactory instance.
Definition LBFactory.php:77
newExternalLB( $cluster, $wiki=false)
Create a new load balancer for external storage.
& getExternalLB( $cluster, $wiki=false)
Get a cached (tracked) load balancer for external storage.
LoggerInterface $logger
Definition LBFactory.php:39
static LBFactory $instance
Definition LBFactory.php:42
__construct(array $conf)
Construct a factory based on a configuration array (typically from $wgLBFactoryConf)
Definition LBFactory.php:53
disableChronologyProtection()
Disable the ChronologyProtector for all load balancers.
rollbackMasterChanges( $fname=__METHOD__)
Rollback changes on all master connections.
ChronologyProtector $chronProt
Definition LBFactory.php:33
getMainLB( $wiki=false)
Get a cached (tracked) load balancer object.
hasMasterChanges()
Determine if any master connection has pending changes.
commitAll( $fname=__METHOD__)
Commit on all connections.
commitMasterChanges( $fname=__METHOD__, array $options=[])
Commit changes on all master connections.
shutdownChronologyProtector(ChronologyProtector $cp)
newChronologyProtector()
newMainLB( $wiki=false)
Create a new load balancer object.
static destroyInstance()
Shut down, close connections and destroy the cached instance.
static disableBackend()
Disables all access to the load balancer, will cause all database access to throw a DBAccessError.
Definition LBFactory.php:67
hasOrMadeRecentMasterChanges()
Determine if any master connection has pending/written changes from this request.
string bool $readOnlyReason
Reason all LBs are read-only or false if not.
Definition LBFactory.php:45
forEachLB( $callback, array $params=[])
Execute a function for each tracked load balancer The callback is called with the load balancer as th...
waitForReplication(array $opts=[])
Waits for the slave DBs to catch up to the current master position.
shutdown( $flags=0)
Prepare all tracked load balancers for shutdown.
TransactionProfiler $trxProfiler
Definition LBFactory.php:36
Database load balancing object.
pendingMasterChangeCallers()
Get the list of callers that have pending master changes.
forEachOpenConnection( $callback, array $params=[])
Call a function with each open connection object.
hasMasterChanges()
Determine if there are pending changes in a transaction by this thread.
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.
hasOrMadeRecentMasterChanges( $age=null)
Check if this load balancer object had any recent or still pending writes issued against it by this P...
MediaWiki exception.
PSR-3 logger instance factory.
static getMainStashInstance()
Get the cache object for the main stash.
static instance()
Singleton.
Definition Profiler.php:60
static getMain()
Static methods.
Helper class that detects high-contention DB queries via profiling calls.
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition design.txt:18
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
the array() calling protocol came about after MediaWiki 1.4rc1.
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 just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
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:1042
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:1810
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition hooks.txt:2555
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition hooks.txt:2530
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 the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive $limit
Definition hooks.txt:1081
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition hooks.txt:1615
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:37
Basic database interface for live and lazy-loaded DB handles.
Definition IDatabase.php:35
pendingWriteQueryDuration()
Get the time spend running write queries for this transaction.
$params