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 */
45 /** @var string|bool Reason all LBs are read-only or false if not */
46 protected $readOnlyReason = false;
48 const SHUTDOWN_NO_CHRONPROT
= 1; // don't save ChronologyProtector positions (for async code)
51 * Construct a factory based on a configuration array (typically from $wgLBFactoryConf)
53 * @TODO: inject objects via dependency framework
55 public function __construct( array $conf ) {
56 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
57 $this->readOnlyReason
= $conf['readOnlyReason'];
59 $this->chronProt
= $this->newChronologyProtector();
60 $this->trxProfiler
= Profiler
::instance()->getTransactionProfiler();
61 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
62 $cache = ObjectCache
::getLocalServerInstance();
63 if ( $cache->getQoS( $cache::ATTR_EMULATION
) > $cache::QOS_EMULATION_SQL
) {
64 $this->srvCache
= $cache;
66 $this->srvCache
= new EmptyBagOStuff();
68 $wCache = ObjectCache
::getMainWANInstance();
69 if ( $wCache->getQoS( $wCache::ATTR_EMULATION
) > $wCache::QOS_EMULATION_SQL
) {
70 $this->wanCache
= $wCache;
72 $this->wanCache
= WANObjectCache
::newEmpty();
74 $this->trxLogger
= LoggerFactory
::getInstance( 'DBTransaction' );
78 * Disables all load balancers. All connections are closed, and any attempt to
79 * open a new connection will result in a DBAccessError.
80 * @see LoadBalancer::disable()
82 public function destroy() {
84 $this->forEachLBCallMethod( 'disable' );
88 * Disables all access to the load balancer, will cause all database access
89 * to throw a DBAccessError
91 public static function disableBackend() {
92 MediaWikiServices
::disableStorageBackend();
96 * Get an LBFactory instance
98 * @deprecated since 1.27, use MediaWikiServices::getDBLoadBalancerFactory() instead.
102 public static function singleton() {
103 return MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
107 * Returns the LBFactory class to use and the load balancer configuration.
109 * @todo instead of this, use a ServiceContainer for managing the different implementations.
111 * @param array $config (e.g. $wgLBFactoryConf)
112 * @return string Class name
114 public static function getLBFactoryClass( array $config ) {
115 // For configuration backward compatibility after removing
116 // underscores from class names in MediaWiki 1.23.
118 'LBFactory_Simple' => 'LBFactorySimple',
119 'LBFactory_Single' => 'LBFactorySingle',
120 'LBFactory_Multi' => 'LBFactoryMulti',
121 'LBFactory_Fake' => 'LBFactoryFake',
124 $class = $config['class'];
126 if ( isset( $bcClasses[$class] ) ) {
127 $class = $bcClasses[$class];
129 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
138 * Shut down, close connections and destroy the cached instance.
140 * @deprecated since 1.27, use LBFactory::destroy()
142 public static function destroyInstance() {
143 self
::singleton()->destroy();
147 * Create a new load balancer object. The resulting object will be untracked,
148 * not chronology-protected, and the caller is responsible for cleaning it up.
150 * @param bool|string $wiki Wiki ID, or false for the current wiki
151 * @return LoadBalancer
153 abstract public function newMainLB( $wiki = false );
156 * Get a cached (tracked) load balancer object.
158 * @param bool|string $wiki Wiki ID, or false for the current wiki
159 * @return LoadBalancer
161 abstract public function getMainLB( $wiki = false );
164 * Create a new load balancer for external storage. The resulting object will be
165 * untracked, not chronology-protected, and the caller is responsible for
168 * @param string $cluster External storage cluster, or false for core
169 * @param bool|string $wiki Wiki ID, or false for the current wiki
170 * @return LoadBalancer
172 abstract protected function newExternalLB( $cluster, $wiki = false );
175 * Get a cached (tracked) load balancer for external storage
177 * @param string $cluster External storage cluster, or false for core
178 * @param bool|string $wiki Wiki ID, or false for the current wiki
179 * @return LoadBalancer
181 abstract public function &getExternalLB( $cluster, $wiki = false );
184 * Execute a function for each tracked load balancer
185 * The callback is called with the load balancer as the first parameter,
186 * and $params passed as the subsequent parameters.
188 * @param callable $callback
189 * @param array $params
191 abstract public function forEachLB( $callback, array $params = [] );
194 * Prepare all tracked load balancers for shutdown
195 * @param integer $flags Supports SHUTDOWN_* flags
198 public function shutdown( $flags = 0 ) {
202 * Call a method of each tracked load balancer
204 * @param string $methodName
207 private function forEachLBCallMethod( $methodName, array $args = [] ) {
209 function ( LoadBalancer
$loadBalancer, $methodName, array $args ) {
210 call_user_func_array( [ $loadBalancer, $methodName ], $args );
212 [ $methodName, $args ]
217 * Commit on all connections. Done for two reasons:
218 * 1. To commit changes to the masters.
219 * 2. To release the snapshot on all connections, master and slave.
220 * @param string $fname Caller name
221 * @param array $options Options map:
222 * - maxWriteDuration: abort if more than this much time was spent in write queries
224 public function commitAll( $fname = __METHOD__
, array $options = [] ) {
225 $this->commitMasterChanges( $fname, $options );
226 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
230 * Commit changes on all master connections
231 * @param string $fname Caller name
232 * @param array $options Options map:
233 * - maxWriteDuration: abort if more than this much time was spent in write queries
235 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
236 // Perform all pre-commit callbacks, aborting on failure
237 $this->forEachLBCallMethod( 'runMasterPreCommitCallbacks' );
238 // Perform all pre-commit checks, aborting on failure
239 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
240 // Log the DBs and methods involved in multi-DB transactions
241 $this->logIfMultiDbTransaction();
242 // Actually perform the commit on all master DB connections
243 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
244 // Run all post-commit callbacks
245 $this->forEachLBCallMethod( 'runMasterPostCommitCallbacks' );
246 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
247 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
251 * Rollback changes on all master connections
252 * @param string $fname Caller name
255 public function rollbackMasterChanges( $fname = __METHOD__
) {
256 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
260 * Log query info if multi DB transactions are going to be committed now
262 private function logIfMultiDbTransaction() {
264 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$callersByDB ) {
265 $masterName = $lb->getServerName( $lb->getWriterIndex() );
266 $callers = $lb->pendingMasterChangeCallers();
268 $callersByDB[$masterName] = $callers;
272 if ( count( $callersByDB ) >= 2 ) {
273 $dbs = implode( ', ', array_keys( $callersByDB ) );
274 $msg = "Multi-DB transaction [{$dbs}]:\n";
275 foreach ( $callersByDB as $db => $callers ) {
276 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
278 $this->trxLogger
->info( $msg );
283 * Determine if any master connection has pending changes
287 public function hasMasterChanges() {
289 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
290 $ret = $ret ||
$lb->hasMasterChanges();
297 * Detemine if any lagged slave connection was used
301 public function laggedSlaveUsed() {
303 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
304 $ret = $ret ||
$lb->laggedSlaveUsed();
311 * Determine if any master connection has pending/written changes from this request
315 public function hasOrMadeRecentMasterChanges() {
317 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$ret ) {
318 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges();
324 * Waits for the slave DBs to catch up to the current master position
326 * Use this when updating very large numbers of rows, as in maintenance scripts,
327 * to avoid causing too much lag. Of course, this is a no-op if there are no slaves.
329 * By default this waits on all DB clusters actually used in this request.
330 * This makes sense when lag being waiting on is caused by the code that does this check.
331 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
332 * that were not changed since the last wait check. To forcefully wait on a specific cluster
333 * for a given wiki, use the 'wiki' parameter. To forcefully wait on an "external" cluster,
334 * use the "cluster" parameter.
336 * Never call this function after a large DB write that is *still* in a transaction.
337 * It only makes sense to call this after the possible lag inducing changes were committed.
339 * @param array $opts Optional fields that include:
340 * - wiki : wait on the load balancer DBs that handles the given wiki
341 * - cluster : wait on the given external load balancer DBs
342 * - timeout : Max wait time. Default: ~60 seconds
343 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
344 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
347 public function waitForReplication( array $opts = [] ) {
352 'ifWritesSince' => null
355 // Figure out which clusters need to be checked
356 /** @var LoadBalancer[] $lbs */
358 if ( $opts['cluster'] !== false ) {
359 $lbs[] = $this->getExternalLB( $opts['cluster'] );
360 } elseif ( $opts['wiki'] !== false ) {
361 $lbs[] = $this->getMainLB( $opts['wiki'] );
363 $this->forEachLB( function ( LoadBalancer
$lb ) use ( &$lbs ) {
367 return; // nothing actually used
371 // Get all the master positions of applicable DBs right now.
372 // This can be faster since waiting on one cluster reduces the
373 // time needed to wait on the next clusters.
374 $masterPositions = array_fill( 0, count( $lbs ), false );
375 foreach ( $lbs as $i => $lb ) {
376 if ( $lb->getServerCount() <= 1 ) {
377 // Bug 27975 - Don't try to wait for slaves if there are none
378 // Prevents permission error when getting master position
380 } elseif ( $opts['ifWritesSince']
381 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
383 continue; // no writes since the last wait
385 $masterPositions[$i] = $lb->getMasterPos();
389 foreach ( $lbs as $i => $lb ) {
390 if ( $masterPositions[$i] ) {
391 // The DBMS may not support getMasterPos() or the whole
392 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
393 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
394 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
400 throw new DBReplicationWaitError(
401 "Could not wait for slaves to catch up to " .
402 implode( ', ', $failed )
408 * Disable the ChronologyProtector for all load balancers
410 * This can be called at the start of special API entry points
414 public function disableChronologyProtection() {
415 $this->chronProt
->setEnabled( false );
419 * @return ChronologyProtector
421 protected function newChronologyProtector() {
422 $request = RequestContext
::getMain()->getRequest();
423 $chronProt = new ChronologyProtector(
424 ObjectCache
::getMainStashInstance(),
426 'ip' => $request->getIP(),
427 'agent' => $request->getHeader( 'User-Agent' )
430 if ( PHP_SAPI
=== 'cli' ) {
431 $chronProt->setEnabled( false );
432 } elseif ( $request->getHeader( 'ChronologyProtection' ) === 'false' ) {
433 // Request opted out of using position wait logic. This is useful for requests
434 // done by the job queue or background ETL that do not have a meaningful session.
435 $chronProt->setWaitEnabled( false );
442 * @param ChronologyProtector $cp
444 protected function shutdownChronologyProtector( ChronologyProtector
$cp ) {
445 // Get all the master positions needed
446 $this->forEachLB( function ( LoadBalancer
$lb ) use ( $cp ) {
447 $cp->shutdownLB( $lb );
449 // Write them to the stash
450 $unsavedPositions = $cp->shutdown();
451 // If the positions failed to write to the stash, at least wait on local datacenter
452 // slaves to catch up before responding. Even if there are several DCs, this increases
453 // the chance that the user will see their own changes immediately afterwards. As long
454 // as the sticky DC cookie applies (same domain), this is not even an issue.
455 $this->forEachLB( function ( LoadBalancer
$lb ) use ( $unsavedPositions ) {
456 $masterName = $lb->getServerName( $lb->getWriterIndex() );
457 if ( isset( $unsavedPositions[$masterName] ) ) {
458 $lb->waitForAll( $unsavedPositions[$masterName] );
464 * Close all open database connections on all open load balancers.
467 public function closeAll() {
468 $this->forEachLBCallMethod( 'closeAll', [] );
474 * Exception class for attempted DB access
476 class DBAccessError
extends MWException
{
477 public function __construct() {
478 parent
::__construct( "Mediawiki tried to access the database via wfGetDB(). " .
479 "This is not allowed, because database access has been disabled." );
484 * Exception class for replica DB wait timeouts
486 class DBReplicationWaitError
extends Exception
{