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 String if a requested DBO_TRX transaction round is active */
48 protected $trxRoundId = false;
49 /** @var string|bool Reason all LBs are read-only or false if not */
50 protected $readOnlyReason = false;
51 /** @var callable[] */
52 protected $replicationWaitCallbacks = [];
54 const SHUTDOWN_NO_CHRONPROT
= 1; // don't save ChronologyProtector positions (for async code)
57 * Construct a factory based on a configuration array (typically from $wgLBFactoryConf)
59 * @TODO: inject objects via dependency framework
61 public function __construct( array $conf ) {
62 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
63 $this->readOnlyReason
= $conf['readOnlyReason'];
65 $this->chronProt
= $this->newChronologyProtector();
66 $this->trxProfiler
= Profiler
::instance()->getTransactionProfiler();
67 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
68 $cache = ObjectCache
::getLocalServerInstance();
69 if ( $cache->getQoS( $cache::ATTR_EMULATION
) > $cache::QOS_EMULATION_SQL
) {
70 $this->srvCache
= $cache;
72 $this->srvCache
= new EmptyBagOStuff();
74 $wCache = ObjectCache
::getMainWANInstance();
75 if ( $wCache->getQoS( $wCache::ATTR_EMULATION
) > $wCache::QOS_EMULATION_SQL
) {
76 $this->wanCache
= $wCache;
78 $this->wanCache
= WANObjectCache
::newEmpty();
80 $this->trxLogger
= LoggerFactory
::getInstance( 'DBTransaction' );
81 $this->ticket
= mt_rand();
85 * Disables all load balancers. All connections are closed, and any attempt to
86 * open a new connection will result in a DBAccessError.
87 * @see LoadBalancer::disable()
89 public function destroy() {
91 $this->forEachLBCallMethod( 'disable' );
95 * Disables all access to the load balancer, will cause all database access
96 * to throw a DBAccessError
98 public static function disableBackend() {
99 MediaWikiServices
::disableStorageBackend();
103 * Get an LBFactory instance
105 * @deprecated since 1.27, use MediaWikiServices::getDBLoadBalancerFactory() instead.
109 public static function singleton() {
110 return MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
114 * Returns the LBFactory class to use and the load balancer configuration.
116 * @todo instead of this, use a ServiceContainer for managing the different implementations.
118 * @param array $config (e.g. $wgLBFactoryConf)
119 * @return string Class name
121 public static function getLBFactoryClass( array $config ) {
122 // For configuration backward compatibility after removing
123 // underscores from class names in MediaWiki 1.23.
125 'LBFactory_Simple' => 'LBFactorySimple',
126 'LBFactory_Single' => 'LBFactorySingle',
127 'LBFactory_Multi' => 'LBFactoryMulti',
128 'LBFactory_Fake' => 'LBFactoryFake',
131 $class = $config['class'];
133 if ( isset( $bcClasses[$class] ) ) {
134 $class = $bcClasses[$class];
136 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
145 * Shut down, close connections and destroy the cached instance.
147 * @deprecated since 1.27, use LBFactory::destroy()
149 public static function destroyInstance() {
150 self
::singleton()->destroy();
154 * Create a new load balancer object. The resulting object will be untracked,
155 * not chronology-protected, and the caller is responsible for cleaning it up.
157 * @param bool|string $wiki Wiki ID, or false for the current wiki
158 * @return LoadBalancer
160 abstract public function newMainLB( $wiki = false );
163 * Get a cached (tracked) load balancer object.
165 * @param bool|string $wiki Wiki ID, or false for the current wiki
166 * @return LoadBalancer
168 abstract public function getMainLB( $wiki = false );
171 * Create a new load balancer for external storage. The resulting object will be
172 * untracked, not chronology-protected, and the caller is responsible for
175 * @param string $cluster External storage cluster, or false for core
176 * @param bool|string $wiki Wiki ID, or false for the current wiki
177 * @return LoadBalancer
179 abstract protected function newExternalLB( $cluster, $wiki = false );
182 * Get a cached (tracked) load balancer for external storage
184 * @param string $cluster External storage cluster, or false for core
185 * @param bool|string $wiki Wiki ID, or false for the current wiki
186 * @return LoadBalancer
188 abstract public function &getExternalLB( $cluster, $wiki = false );
191 * Execute a function for each tracked load balancer
192 * The callback is called with the load balancer as the first parameter,
193 * and $params passed as the subsequent parameters.
195 * @param callable $callback
196 * @param array $params
198 abstract public function forEachLB( $callback, array $params = [] );
201 * Prepare all tracked load balancers for shutdown
202 * @param integer $flags Supports SHUTDOWN_* flags
204 public function shutdown( $flags = 0 ) {
205 if ( !( $flags & self
::SHUTDOWN_NO_CHRONPROT
) ) {
206 $this->shutdownChronologyProtector( $this->chronProt
);
208 $this->commitMasterChanges( __METHOD__
); // sanity
212 * Call a method of each tracked load balancer
214 * @param string $methodName
217 private function forEachLBCallMethod( $methodName, array $args = [] ) {
219 function ( LoadBalancer
$loadBalancer, $methodName, array $args ) {
220 call_user_func_array( [ $loadBalancer, $methodName ], $args );
222 [ $methodName, $args ]
227 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
229 * The DBO_TRX setting will be reverted to the default in each of these methods:
230 * - commitMasterChanges()
231 * - rollbackMasterChanges()
233 * This allows for custom transaction rounds from any outer transaction scope.
235 * @param string $fname
236 * @throws DBTransactionError
239 public function beginMasterChanges( $fname = __METHOD__
) {
240 if ( $this->trxRoundId
!== false ) {
241 throw new DBTransactionError(
243 "Transaction round '{$this->trxRoundId}' already started."
246 $this->trxRoundId
= $fname;
247 // Set DBO_TRX flags on all appropriate DBs
248 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
252 * Commit on all connections. Done for two reasons:
253 * 1. To commit changes to the masters.
254 * 2. To release the snapshot on all connections, master and slave.
255 * @param string $fname Caller name
256 * @param array $options Options map:
257 * - maxWriteDuration: abort if more than this much time was spent in write queries
259 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
260 $this->commitMasterChanges( $fname, $options );
261 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
265 * Commit changes on all master connections
266 * @param string $fname Caller name
267 * @param array $options Options map:
268 * - maxWriteDuration: abort if more than this much time was spent in write queries
271 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
272 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
273 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
274 $this->trxRoundId
= false;
275 // Perform pre-commit checks, aborting on failure
276 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
277 // Log the DBs and methods involved in multi-DB transactions
278 $this->logIfMultiDbTransaction();
279 // Actually perform the commit on all master DB connections and revert DBO_TRX
280 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
281 // Run all post-commit callbacks
282 /** @var Exception $e */
283 $e = null; // first callback exception
284 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$e ) {
285 $ex = $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_COMMIT
);
288 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
289 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
290 // Throw any last post-commit callback error
291 if ( $e instanceof Exception
) {
297 * Rollback changes on all master connections
298 * @param string $fname Caller name
301 public function rollbackMasterChanges( $fname = __METHOD__
) {
302 $this->trxRoundId
= false;
303 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
304 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
305 // Run all post-rollback callbacks
306 $this->forEachLB( function ( LoadBalancer
$lb ) {
307 $lb->runMasterPostTrxCallbacks( IDatabase
::TRIGGER_ROLLBACK
);
312 * Log query info if multi DB transactions are going to be committed now
314 private function logIfMultiDbTransaction() {
316 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$callersByDB ) {
317 $masterName = $lb->getServerName( $lb->getWriterIndex() );
318 $callers = $lb->pendingMasterChangeCallers();
320 $callersByDB[$masterName] = $callers;
324 if ( count( $callersByDB ) >= 2 ) {
325 $dbs = implode( ', ', array_keys( $callersByDB ) );
326 $msg = "Multi-DB transaction [{$dbs}]:\n";
327 foreach ( $callersByDB as $db => $callers ) {
328 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
330 $this->trxLogger
->info( $msg );
335 * Determine if any master connection has pending changes
339 public function hasMasterChanges() {
341 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
342 $ret = $ret ||
$lb->hasMasterChanges();
349 * Detemine if any lagged slave connection was used
353 public function laggedSlaveUsed() {
355 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
356 $ret = $ret ||
$lb->laggedSlaveUsed();
363 * Determine if any master connection has pending/written changes from this request
367 public function hasOrMadeRecentMasterChanges() {
369 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
370 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges();
376 * Waits for the slave DBs to catch up to the current master position
378 * Use this when updating very large numbers of rows, as in maintenance scripts,
379 * to avoid causing too much lag. Of course, this is a no-op if there are no slaves.
381 * By default this waits on all DB clusters actually used in this request.
382 * This makes sense when lag being waiting on is caused by the code that does this check.
383 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
384 * that were not changed since the last wait check. To forcefully wait on a specific cluster
385 * for a given wiki, use the 'wiki' parameter. To forcefully wait on an "external" cluster,
386 * use the "cluster" parameter.
388 * Never call this function after a large DB write that is *still* in a transaction.
389 * It only makes sense to call this after the possible lag inducing changes were committed.
391 * @param array $opts Optional fields that include:
392 * - wiki : wait on the load balancer DBs that handles the given wiki
393 * - cluster : wait on the given external load balancer DBs
394 * - timeout : Max wait time. Default: ~60 seconds
395 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
396 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
399 public function waitForReplication( array $opts = [] ) {
404 'ifWritesSince' => null
407 foreach ( $this->replicationWaitCallbacks
as $callback ) {
411 // Figure out which clusters need to be checked
412 /** @var LoadBalancer[] $lbs */
414 if ( $opts['cluster'] !== false ) {
415 $lbs[] = $this->getExternalLB( $opts['cluster'] );
416 } elseif ( $opts['wiki'] !== false ) {
417 $lbs[] = $this->getMainLB( $opts['wiki'] );
419 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$lbs ) {
423 return; // nothing actually used
427 // Get all the master positions of applicable DBs right now.
428 // This can be faster since waiting on one cluster reduces the
429 // time needed to wait on the next clusters.
430 $masterPositions = array_fill( 0, count( $lbs ), false );
431 foreach ( $lbs as $i => $lb ) {
432 if ( $lb->getServerCount() <= 1 ) {
433 // Bug 27975 - Don't try to wait for slaves if there are none
434 // Prevents permission error when getting master position
436 } elseif ( $opts['ifWritesSince']
437 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
439 continue; // no writes since the last wait
441 $masterPositions[$i] = $lb->getMasterPos();
445 foreach ( $lbs as $i => $lb ) {
446 if ( $masterPositions[$i] ) {
447 // The DBMS may not support getMasterPos() or the whole
448 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
449 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
450 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
456 throw new DBReplicationWaitError(
457 "Could not wait for slaves to catch up to " .
458 implode( ', ', $failed )
464 * Add a callback to be run in every call to waitForReplication() before waiting
466 * Callbacks must clear any transactions that they start
468 * @param string $name Callback name
469 * @param callable|null $callback Use null to unset a callback
472 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
474 $this->replicationWaitCallbacks
[$name] = $callback;
476 unset( $this->replicationWaitCallbacks
[$name] );
481 * Get a token asserting that no transaction writes are active
483 * @param string $fname Caller name (e.g. __METHOD__)
484 * @return mixed A value to pass to commitAndWaitForReplication()
487 public function getEmptyTransactionTicket( $fname ) {
488 if ( $this->hasMasterChanges() ) {
489 $this->trxLogger
->error( __METHOD__
. ": $fname does not have outer scope." );
493 return $this->ticket
;
497 * Convenience method for safely running commitMasterChanges()/waitForReplication()
499 * This will commit and wait unless $ticket indicates it is unsafe to do so
501 * @param string $fname Caller name (e.g. __METHOD__)
502 * @param mixed $ticket Result of getOuterTransactionScopeTicket()
503 * @param array $opts Options to waitForReplication()
504 * @throws DBReplicationWaitError
507 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
508 if ( $ticket !== $this->ticket
) {
509 $logger = LoggerFactory
::getInstance( 'DBPerformance' );
510 $logger->error( __METHOD__
. ": cannot commit; $fname does not have outer scope." );
514 $this->commitMasterChanges( $fname );
515 $this->waitForReplication( $opts );
519 * Disable the ChronologyProtector for all load balancers
521 * This can be called at the start of special API entry points
525 public function disableChronologyProtection() {
526 $this->chronProt
->setEnabled( false );
530 * @return ChronologyProtector
532 protected function newChronologyProtector() {
533 $request = RequestContext
::getMain()->getRequest();
534 $chronProt = new ChronologyProtector(
535 ObjectCache
::getMainStashInstance(),
537 'ip' => $request->getIP(),
538 'agent' => $request->getHeader( 'User-Agent' )
541 if ( PHP_SAPI
=== 'cli' ) {
542 $chronProt->setEnabled( false );
543 } elseif ( $request->getHeader( 'ChronologyProtection' ) === 'false' ) {
544 // Request opted out of using position wait logic. This is useful for requests
545 // done by the job queue or background ETL that do not have a meaningful session.
546 $chronProt->setWaitEnabled( false );
553 * @param ChronologyProtector $cp
555 protected function shutdownChronologyProtector( ChronologyProtector
$cp ) {
556 // Get all the master positions needed
557 $this->forEachLB( function ( LoadBalancer
$lb ) use ( $cp ) {
558 $cp->shutdownLB( $lb );
560 // Write them to the stash
561 $unsavedPositions = $cp->shutdown();
562 // If the positions failed to write to the stash, at least wait on local datacenter
563 // slaves to catch up before responding. Even if there are several DCs, this increases
564 // the chance that the user will see their own changes immediately afterwards. As long
565 // as the sticky DC cookie applies (same domain), this is not even an issue.
566 $this->forEachLB( function ( LoadBalancer
$lb ) use ( $unsavedPositions ) {
567 $masterName = $lb->getServerName( $lb->getWriterIndex() );
568 if ( isset( $unsavedPositions[$masterName] ) ) {
569 $lb->waitForAll( $unsavedPositions[$masterName] );
575 * @param LoadBalancer $lb
577 protected function initLoadBalancer( LoadBalancer
$lb ) {
578 if ( $this->trxRoundId
!== false ) {
579 $lb->beginMasterChanges( $this->trxRoundId
); // set DBO_TRX
584 * Close all open database connections on all open load balancers.
587 public function closeAll() {
588 $this->forEachLBCallMethod( 'closeAll', [] );