PHPSessionHandler: Implement SessionHandlerInterface
[mediawiki.git] / includes / db / loadbalancer / LBFactory.php
blob606f4f4b78f3cc3d61c38e40a3cd23f2996459af
1 <?php
2 /**
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
20 * @file
21 * @ingroup Database
24 use Psr\Log\LoggerInterface;
25 use MediaWiki\Logger\LoggerFactory;
27 /**
28 * An interface for generating database load balancers
29 * @ingroup Database
31 abstract class LBFactory {
32 /** @var ChronologyProtector */
33 protected $chronProt;
35 /** @var TransactionProfiler */
36 protected $trxProfiler;
38 /** @var LoggerInterface */
39 protected $logger;
41 /** @var LBFactory */
42 private static $instance;
44 /** @var string|bool Reason all LBs are read-only or false if not */
45 protected $readOnlyReason = false;
47 const SHUTDOWN_NO_CHRONPROT = 1; // don't save ChronologyProtector positions (for async code)
49 /**
50 * Construct a factory based on a configuration array (typically from $wgLBFactoryConf)
51 * @param array $conf
53 public function __construct( array $conf ) {
54 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
55 $this->readOnlyReason = $conf['readOnlyReason'];
58 $this->chronProt = $this->newChronologyProtector();
59 $this->trxProfiler = Profiler::instance()->getTransactionProfiler();
60 $this->logger = LoggerFactory::getInstance( 'DBTransaction' );
63 /**
64 * Disables all access to the load balancer, will cause all database access
65 * to throw a DBAccessError
67 public static function disableBackend() {
68 global $wgLBFactoryConf;
69 self::$instance = new LBFactoryFake( $wgLBFactoryConf );
72 /**
73 * Get an LBFactory instance
75 * @return LBFactory
77 public static function singleton() {
78 global $wgLBFactoryConf;
80 if ( is_null( self::$instance ) ) {
81 $class = self::getLBFactoryClass( $wgLBFactoryConf );
82 $config = $wgLBFactoryConf;
83 if ( !isset( $config['readOnlyReason'] ) ) {
84 $config['readOnlyReason'] = wfConfiguredReadOnlyReason();
86 self::$instance = new $class( $config );
89 return self::$instance;
92 /**
93 * Returns the LBFactory class to use and the load balancer configuration.
95 * @param array $config (e.g. $wgLBFactoryConf)
96 * @return string Class name
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 = array(
102 'LBFactory_Simple' => 'LBFactorySimple',
103 'LBFactory_Single' => 'LBFactorySingle',
104 'LBFactory_Multi' => 'LBFactoryMulti',
105 'LBFactory_Fake' => 'LBFactoryFake',
108 $class = $config['class'];
110 if ( isset( $bcClasses[$class] ) ) {
111 $class = $bcClasses[$class];
112 wfDeprecated(
113 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
114 '1.23'
118 return $class;
122 * Shut down, close connections and destroy the cached instance.
124 public static function destroyInstance() {
125 if ( self::$instance ) {
126 self::$instance->shutdown();
127 self::$instance->forEachLBCallMethod( 'closeAll' );
128 self::$instance = null;
133 * Set the instance to be the given object
135 * @param LBFactory $instance
137 public static function setInstance( $instance ) {
138 self::destroyInstance();
139 self::$instance = $instance;
143 * Create a new load balancer object. The resulting object will be untracked,
144 * not chronology-protected, and the caller is responsible for cleaning it up.
146 * @param bool|string $wiki Wiki ID, or false for the current wiki
147 * @return LoadBalancer
149 abstract public function newMainLB( $wiki = false );
152 * Get a cached (tracked) load balancer object.
154 * @param bool|string $wiki Wiki ID, or false for the current wiki
155 * @return LoadBalancer
157 abstract public function getMainLB( $wiki = false );
160 * Create a new load balancer for external storage. The resulting object will be
161 * untracked, not chronology-protected, and the caller is responsible for
162 * cleaning it up.
164 * @param string $cluster External storage cluster, or false for core
165 * @param bool|string $wiki Wiki ID, or false for the current wiki
166 * @return LoadBalancer
168 abstract protected function newExternalLB( $cluster, $wiki = false );
171 * Get a cached (tracked) load balancer for external storage
173 * @param string $cluster External storage cluster, or false for core
174 * @param bool|string $wiki Wiki ID, or false for the current wiki
175 * @return LoadBalancer
177 abstract public function &getExternalLB( $cluster, $wiki = false );
180 * Execute a function for each tracked load balancer
181 * The callback is called with the load balancer as the first parameter,
182 * and $params passed as the subsequent parameters.
184 * @param callable $callback
185 * @param array $params
187 abstract public function forEachLB( $callback, array $params = array() );
190 * Prepare all tracked load balancers for shutdown
191 * @param integer $flags Supports SHUTDOWN_* flags
192 * STUB
194 public function shutdown( $flags = 0 ) {
198 * Call a method of each tracked load balancer
200 * @param string $methodName
201 * @param array $args
203 private function forEachLBCallMethod( $methodName, array $args = array() ) {
204 $this->forEachLB(
205 function ( LoadBalancer $loadBalancer, $methodName, array $args ) {
206 call_user_func_array( array( $loadBalancer, $methodName ), $args );
208 array( $methodName, $args )
213 * Commit on all connections. Done for two reasons:
214 * 1. To commit changes to the masters.
215 * 2. To release the snapshot on all connections, master and slave.
216 * @param string $fname Caller name
218 public function commitAll( $fname = __METHOD__ ) {
219 $this->logMultiDbTransaction();
221 $start = microtime( true );
222 $this->forEachLBCallMethod( 'commitAll', array( $fname ) );
223 $timeMs = 1000 * ( microtime( true ) - $start );
225 RequestContext::getMain()->getStats()->timing( "db.commit-all", $timeMs );
229 * Commit changes on all master connections
230 * @param string $fname Caller name
231 * @param array $options Options map:
232 * - maxWriteDuration: abort if more than this much time was spent in write queries
234 public function commitMasterChanges( $fname = __METHOD__, array $options = array() ) {
235 $limit = isset( $options['maxWriteDuration'] ) ? $options['maxWriteDuration'] : 0;
237 $this->logMultiDbTransaction();
238 $this->forEachLB( function ( LoadBalancer $lb ) use ( $limit ) {
239 $lb->forEachOpenConnection( function ( IDatabase $db ) use ( $limit ) {
240 $time = $db->pendingWriteQueryDuration();
241 if ( $limit > 0 && $time > $limit ) {
242 throw new DBTransactionError(
243 $db,
244 wfMessage( 'transaction-duration-limit-exceeded', $time, $limit )->text()
247 } );
248 } );
250 $start = microtime( true );
251 $this->forEachLBCallMethod( 'commitMasterChanges', array( $fname ) );
252 $timeMs = 1000 * ( microtime( true ) - $start );
254 RequestContext::getMain()->getStats()->timing( "db.commit-masters", $timeMs );
258 * Rollback changes on all master connections
259 * @param string $fname Caller name
260 * @since 1.23
262 public function rollbackMasterChanges( $fname = __METHOD__ ) {
263 $this->forEachLBCallMethod( 'rollbackMasterChanges', array( $fname ) );
267 * Log query info if multi DB transactions are going to be committed now
269 private function logMultiDbTransaction() {
270 $callersByDB = array();
271 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$callersByDB ) {
272 $masterName = $lb->getServerName( $lb->getWriterIndex() );
273 $callers = $lb->pendingMasterChangeCallers();
274 if ( $callers ) {
275 $callersByDB[$masterName] = $callers;
277 } );
279 if ( count( $callersByDB ) >= 2 ) {
280 $dbs = implode( ', ', array_keys( $callersByDB ) );
281 $msg = "Multi-DB transaction [{$dbs}]:\n";
282 foreach ( $callersByDB as $db => $callers ) {
283 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
285 $this->logger->info( $msg );
290 * Determine if any master connection has pending changes
291 * @return bool
292 * @since 1.23
294 public function hasMasterChanges() {
295 $ret = false;
296 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
297 $ret = $ret || $lb->hasMasterChanges();
298 } );
300 return $ret;
304 * Detemine if any lagged slave connection was used
305 * @since 1.27
306 * @return bool
308 public function laggedSlaveUsed() {
309 $ret = false;
310 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
311 $ret = $ret || $lb->laggedSlaveUsed();
312 } );
314 return $ret;
318 * Determine if any master connection has pending/written changes from this request
319 * @return bool
320 * @since 1.27
322 public function hasOrMadeRecentMasterChanges() {
323 $ret = false;
324 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
325 $ret = $ret || $lb->hasOrMadeRecentMasterChanges();
326 } );
327 return $ret;
331 * Waits for the slave DBs to catch up to the current master position
333 * Use this when updating very large numbers of rows, as in maintenance scripts,
334 * to avoid causing too much lag. Of course, this is a no-op if there are no slaves.
336 * By default this waits on all DB clusters actually used in this request.
337 * This makes sense when lag being waiting on is caused by the code that does this check.
338 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
339 * that were not changed since the last wait check. To forcefully wait on a specific cluster
340 * for a given wiki, use the 'wiki' parameter. To forcefully wait on an "external" cluster,
341 * use the "cluster" parameter.
343 * Never call this function after a large DB write that is *still* in a transaction.
344 * It only makes sense to call this after the possible lag inducing changes were committed.
346 * @param array $opts Optional fields that include:
347 * - wiki : wait on the load balancer DBs that handles the given wiki
348 * - cluster : wait on the given external load balancer DBs
349 * - timeout : Max wait time. Default: ~60 seconds
350 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
351 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
352 * @since 1.27
354 public function waitForReplication( array $opts = array() ) {
355 $opts += array(
356 'wiki' => false,
357 'cluster' => false,
358 'timeout' => 60,
359 'ifWritesSince' => null
362 // Figure out which clusters need to be checked
363 /** @var LoadBalancer[] $lbs */
364 $lbs = array();
365 if ( $opts['cluster'] !== false ) {
366 $lbs[] = $this->getExternalLB( $opts['cluster'] );
367 } elseif ( $opts['wiki'] !== false ) {
368 $lbs[] = $this->getMainLB( $opts['wiki'] );
369 } else {
370 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$lbs ) {
371 $lbs[] = $lb;
372 } );
373 if ( !$lbs ) {
374 return; // nothing actually used
378 // Get all the master positions of applicable DBs right now.
379 // This can be faster since waiting on one cluster reduces the
380 // time needed to wait on the next clusters.
381 $masterPositions = array_fill( 0, count( $lbs ), false );
382 foreach ( $lbs as $i => $lb ) {
383 if ( $lb->getServerCount() <= 1 ) {
384 // Bug 27975 - Don't try to wait for slaves if there are none
385 // Prevents permission error when getting master position
386 continue;
387 } elseif ( $opts['ifWritesSince']
388 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
390 continue; // no writes since the last wait
392 $masterPositions[$i] = $lb->getMasterPos();
395 $failed = array();
396 foreach ( $lbs as $i => $lb ) {
397 if ( $masterPositions[$i] ) {
398 // The DBMS may not support getMasterPos() or the whole
399 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
400 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
401 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
406 if ( $failed ) {
407 throw new DBReplicationWaitError(
408 "Could not wait for slaves to catch up to " .
409 implode( ', ', $failed )
415 * Disable the ChronologyProtector for all load balancers
417 * This can be called at the start of special API entry points
419 * @since 1.27
421 public function disableChronologyProtection() {
422 $this->chronProt->setEnabled( false );
426 * @return ChronologyProtector
428 protected function newChronologyProtector() {
429 $request = RequestContext::getMain()->getRequest();
430 $chronProt = new ChronologyProtector(
431 ObjectCache::getMainStashInstance(),
432 array(
433 'ip' => $request->getIP(),
434 'agent' => $request->getHeader( 'User-Agent' )
437 if ( PHP_SAPI === 'cli' ) {
438 $chronProt->setEnabled( false );
439 } elseif ( $request->getHeader( 'ChronologyProtection' ) === 'false' ) {
440 // Request opted out of using position wait logic. This is useful for requests
441 // done by the job queue or background ETL that do not have a meaningful session.
442 $chronProt->setWaitEnabled( false );
445 return $chronProt;
449 * @param ChronologyProtector $cp
451 protected function shutdownChronologyProtector( ChronologyProtector $cp ) {
452 // Get all the master positions needed
453 $this->forEachLB( function ( LoadBalancer $lb ) use ( $cp ) {
454 $cp->shutdownLB( $lb );
455 } );
456 // Write them to the stash
457 $unsavedPositions = $cp->shutdown();
458 // If the positions failed to write to the stash, at least wait on local datacenter
459 // slaves to catch up before responding. Even if there are several DCs, this increases
460 // the chance that the user will see their own changes immediately afterwards. As long
461 // as the sticky DC cookie applies (same domain), this is not even an issue.
462 $this->forEachLB( function ( LoadBalancer $lb ) use ( $unsavedPositions ) {
463 $masterName = $lb->getServerName( $lb->getWriterIndex() );
464 if ( isset( $unsavedPositions[$masterName] ) ) {
465 $lb->waitForAll( $unsavedPositions[$masterName] );
467 } );
472 * Exception class for attempted DB access
474 class DBAccessError extends MWException {
475 public function __construct() {
476 parent::__construct( "Mediawiki tried to access the database via wfGetDB(). " .
477 "This is not allowed." );
482 * Exception class for replica DB wait timeouts
484 class DBReplicationWaitError extends Exception {