Improve beginMasterChanges and make methods for DeferredUpdates
[lhc/web/wiklou.git] / includes / db / loadbalancer / LBFactory.php
1 <?php
2 /**
3 * Generator of database load balancing objects.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Database
22 */
23
24 use MediaWiki\MediaWikiServices;
25 use MediaWiki\Services\DestructibleService;
26 use Psr\Log\LoggerInterface;
27 use MediaWiki\Logger\LoggerFactory;
28
29 /**
30 * An interface for generating database load balancers
31 * @ingroup Database
32 */
33 abstract class LBFactory implements DestructibleService {
34 /** @var ChronologyProtector */
35 protected $chronProt;
36 /** @var TransactionProfiler */
37 protected $trxProfiler;
38 /** @var LoggerInterface */
39 protected $trxLogger;
40 /** @var BagOStuff */
41 protected $srvCache;
42 /** @var WANObjectCache */
43 protected $wanCache;
44
45 /** @var mixed */
46 protected $ticket;
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 = [];
53
54 const SHUTDOWN_NO_CHRONPROT = 1; // don't save ChronologyProtector positions (for async code)
55
56 /**
57 * Construct a factory based on a configuration array (typically from $wgLBFactoryConf)
58 * @param array $conf
59 * @TODO: inject objects via dependency framework
60 */
61 public function __construct( array $conf ) {
62 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
63 $this->readOnlyReason = $conf['readOnlyReason'];
64 }
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;
71 } else {
72 $this->srvCache = new EmptyBagOStuff();
73 }
74 $wCache = ObjectCache::getMainWANInstance();
75 if ( $wCache->getQoS( $wCache::ATTR_EMULATION ) > $wCache::QOS_EMULATION_SQL ) {
76 $this->wanCache = $wCache;
77 } else {
78 $this->wanCache = WANObjectCache::newEmpty();
79 }
80 $this->trxLogger = LoggerFactory::getInstance( 'DBTransaction' );
81 $this->ticket = mt_rand();
82 }
83
84 /**
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()
88 */
89 public function destroy() {
90 $this->shutdown();
91 $this->forEachLBCallMethod( 'disable' );
92 }
93
94 /**
95 * Disables all access to the load balancer, will cause all database access
96 * to throw a DBAccessError
97 */
98 public static function disableBackend() {
99 MediaWikiServices::disableStorageBackend();
100 }
101
102 /**
103 * Get an LBFactory instance
104 *
105 * @deprecated since 1.27, use MediaWikiServices::getDBLoadBalancerFactory() instead.
106 *
107 * @return LBFactory
108 */
109 public static function singleton() {
110 return MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
111 }
112
113 /**
114 * Returns the LBFactory class to use and the load balancer configuration.
115 *
116 * @todo instead of this, use a ServiceContainer for managing the different implementations.
117 *
118 * @param array $config (e.g. $wgLBFactoryConf)
119 * @return string Class name
120 */
121 public static function getLBFactoryClass( array $config ) {
122 // For configuration backward compatibility after removing
123 // underscores from class names in MediaWiki 1.23.
124 $bcClasses = [
125 'LBFactory_Simple' => 'LBFactorySimple',
126 'LBFactory_Single' => 'LBFactorySingle',
127 'LBFactory_Multi' => 'LBFactoryMulti',
128 'LBFactory_Fake' => 'LBFactoryFake',
129 ];
130
131 $class = $config['class'];
132
133 if ( isset( $bcClasses[$class] ) ) {
134 $class = $bcClasses[$class];
135 wfDeprecated(
136 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
137 '1.23'
138 );
139 }
140
141 return $class;
142 }
143
144 /**
145 * Shut down, close connections and destroy the cached instance.
146 *
147 * @deprecated since 1.27, use LBFactory::destroy()
148 */
149 public static function destroyInstance() {
150 self::singleton()->destroy();
151 }
152
153 /**
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.
156 *
157 * @param bool|string $wiki Wiki ID, or false for the current wiki
158 * @return LoadBalancer
159 */
160 abstract public function newMainLB( $wiki = false );
161
162 /**
163 * Get a cached (tracked) load balancer object.
164 *
165 * @param bool|string $wiki Wiki ID, or false for the current wiki
166 * @return LoadBalancer
167 */
168 abstract public function getMainLB( $wiki = false );
169
170 /**
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
173 * cleaning it up.
174 *
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
178 */
179 abstract protected function newExternalLB( $cluster, $wiki = false );
180
181 /**
182 * Get a cached (tracked) load balancer for external storage
183 *
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
187 */
188 abstract public function &getExternalLB( $cluster, $wiki = false );
189
190 /**
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.
194 *
195 * @param callable $callback
196 * @param array $params
197 */
198 abstract public function forEachLB( $callback, array $params = [] );
199
200 /**
201 * Prepare all tracked load balancers for shutdown
202 * @param integer $flags Supports SHUTDOWN_* flags
203 * STUB
204 */
205 public function shutdown( $flags = 0 ) {
206 }
207
208 /**
209 * Call a method of each tracked load balancer
210 *
211 * @param string $methodName
212 * @param array $args
213 */
214 private function forEachLBCallMethod( $methodName, array $args = [] ) {
215 $this->forEachLB(
216 function ( LoadBalancer $loadBalancer, $methodName, array $args ) {
217 call_user_func_array( [ $loadBalancer, $methodName ], $args );
218 },
219 [ $methodName, $args ]
220 );
221 }
222
223 /**
224 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
225 *
226 * The DBO_TRX setting will be reverted to the default in each of these methods:
227 * - commitMasterChanges()
228 * - rollbackMasterChanges()
229 * - commitAll()
230 * This allows for custom transaction rounds from any outer transaction scope.
231 *
232 * @param string $fname
233 * @throws DBTransactionError
234 * @since 1.28
235 */
236 public function beginMasterChanges( $fname = __METHOD__ ) {
237 if ( $this->trxRoundId !== false ) {
238 throw new DBTransactionError(
239 null,
240 "Transaction round '{$this->trxRoundId}' already started."
241 );
242 }
243 $this->trxRoundId = $fname;
244 // Set DBO_TRX flags on all appropriate DBs
245 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
246 }
247
248 /**
249 * Commit on all connections. Done for two reasons:
250 * 1. To commit changes to the masters.
251 * 2. To release the snapshot on all connections, master and slave.
252 * @param string $fname Caller name
253 * @param array $options Options map:
254 * - maxWriteDuration: abort if more than this much time was spent in write queries
255 */
256 public function commitAll( $fname = __METHOD__, array $options = [] ) {
257 $this->commitMasterChanges( $fname, $options );
258 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
259 }
260
261 /**
262 * Commit changes on all master connections
263 * @param string $fname Caller name
264 * @param array $options Options map:
265 * - maxWriteDuration: abort if more than this much time was spent in write queries
266 * @throws Exception
267 */
268 public function commitMasterChanges( $fname = __METHOD__, array $options = [] ) {
269 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
270 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
271 $this->trxRoundId = false;
272 // Perform pre-commit checks, aborting on failure
273 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
274 // Log the DBs and methods involved in multi-DB transactions
275 $this->logIfMultiDbTransaction();
276 // Actually perform the commit on all master DB connections and revert DBO_TRX
277 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
278 // Run all post-commit callbacks
279 /** @var Exception $e */
280 $e = null; // first callback exception
281 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$e ) {
282 $ex = $lb->runMasterPostTrxCallbacks( IDatabase::TRIGGER_COMMIT );
283 $e = $e ?: $ex;
284 } );
285 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
286 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
287 // Throw any last post-commit callback error
288 if ( $e instanceof Exception ) {
289 throw $e;
290 }
291 }
292
293 /**
294 * Rollback changes on all master connections
295 * @param string $fname Caller name
296 * @since 1.23
297 */
298 public function rollbackMasterChanges( $fname = __METHOD__ ) {
299 $this->trxRoundId = false;
300 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
301 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
302 // Run all post-rollback callbacks
303 $this->forEachLB( function ( LoadBalancer $lb ) {
304 $lb->runMasterPostTrxCallbacks( IDatabase::TRIGGER_ROLLBACK );
305 } );
306 }
307
308 /**
309 * Log query info if multi DB transactions are going to be committed now
310 */
311 private function logIfMultiDbTransaction() {
312 $callersByDB = [];
313 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$callersByDB ) {
314 $masterName = $lb->getServerName( $lb->getWriterIndex() );
315 $callers = $lb->pendingMasterChangeCallers();
316 if ( $callers ) {
317 $callersByDB[$masterName] = $callers;
318 }
319 } );
320
321 if ( count( $callersByDB ) >= 2 ) {
322 $dbs = implode( ', ', array_keys( $callersByDB ) );
323 $msg = "Multi-DB transaction [{$dbs}]:\n";
324 foreach ( $callersByDB as $db => $callers ) {
325 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
326 }
327 $this->trxLogger->info( $msg );
328 }
329 }
330
331 /**
332 * Determine if any master connection has pending changes
333 * @return bool
334 * @since 1.23
335 */
336 public function hasMasterChanges() {
337 $ret = false;
338 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
339 $ret = $ret || $lb->hasMasterChanges();
340 } );
341
342 return $ret;
343 }
344
345 /**
346 * Detemine if any lagged slave connection was used
347 * @since 1.27
348 * @return bool
349 */
350 public function laggedSlaveUsed() {
351 $ret = false;
352 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
353 $ret = $ret || $lb->laggedSlaveUsed();
354 } );
355
356 return $ret;
357 }
358
359 /**
360 * Determine if any master connection has pending/written changes from this request
361 * @return bool
362 * @since 1.27
363 */
364 public function hasOrMadeRecentMasterChanges() {
365 $ret = false;
366 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
367 $ret = $ret || $lb->hasOrMadeRecentMasterChanges();
368 } );
369 return $ret;
370 }
371
372 /**
373 * Waits for the slave DBs to catch up to the current master position
374 *
375 * Use this when updating very large numbers of rows, as in maintenance scripts,
376 * to avoid causing too much lag. Of course, this is a no-op if there are no slaves.
377 *
378 * By default this waits on all DB clusters actually used in this request.
379 * This makes sense when lag being waiting on is caused by the code that does this check.
380 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
381 * that were not changed since the last wait check. To forcefully wait on a specific cluster
382 * for a given wiki, use the 'wiki' parameter. To forcefully wait on an "external" cluster,
383 * use the "cluster" parameter.
384 *
385 * Never call this function after a large DB write that is *still* in a transaction.
386 * It only makes sense to call this after the possible lag inducing changes were committed.
387 *
388 * @param array $opts Optional fields that include:
389 * - wiki : wait on the load balancer DBs that handles the given wiki
390 * - cluster : wait on the given external load balancer DBs
391 * - timeout : Max wait time. Default: ~60 seconds
392 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
393 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
394 * @since 1.27
395 */
396 public function waitForReplication( array $opts = [] ) {
397 $opts += [
398 'wiki' => false,
399 'cluster' => false,
400 'timeout' => 60,
401 'ifWritesSince' => null
402 ];
403
404 foreach ( $this->replicationWaitCallbacks as $callback ) {
405 $callback();
406 }
407
408 // Figure out which clusters need to be checked
409 /** @var LoadBalancer[] $lbs */
410 $lbs = [];
411 if ( $opts['cluster'] !== false ) {
412 $lbs[] = $this->getExternalLB( $opts['cluster'] );
413 } elseif ( $opts['wiki'] !== false ) {
414 $lbs[] = $this->getMainLB( $opts['wiki'] );
415 } else {
416 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$lbs ) {
417 $lbs[] = $lb;
418 } );
419 if ( !$lbs ) {
420 return; // nothing actually used
421 }
422 }
423
424 // Get all the master positions of applicable DBs right now.
425 // This can be faster since waiting on one cluster reduces the
426 // time needed to wait on the next clusters.
427 $masterPositions = array_fill( 0, count( $lbs ), false );
428 foreach ( $lbs as $i => $lb ) {
429 if ( $lb->getServerCount() <= 1 ) {
430 // Bug 27975 - Don't try to wait for slaves if there are none
431 // Prevents permission error when getting master position
432 continue;
433 } elseif ( $opts['ifWritesSince']
434 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
435 ) {
436 continue; // no writes since the last wait
437 }
438 $masterPositions[$i] = $lb->getMasterPos();
439 }
440
441 $failed = [];
442 foreach ( $lbs as $i => $lb ) {
443 if ( $masterPositions[$i] ) {
444 // The DBMS may not support getMasterPos() or the whole
445 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
446 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
447 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
448 }
449 }
450 }
451
452 if ( $failed ) {
453 throw new DBReplicationWaitError(
454 "Could not wait for slaves to catch up to " .
455 implode( ', ', $failed )
456 );
457 }
458 }
459
460 /**
461 * Add a callback to be run in every call to waitForReplication() before waiting
462 *
463 * Callbacks must clear any transactions that they start
464 *
465 * @param string $name Callback name
466 * @param callable|null $callback Use null to unset a callback
467 * @since 1.28
468 */
469 public function setWaitForReplicationListener( $name, callable $callback = null ) {
470 if ( $callback ) {
471 $this->replicationWaitCallbacks[$name] = $callback;
472 } else {
473 unset( $this->replicationWaitCallbacks[$name] );
474 }
475 }
476
477 /**
478 * Get a token asserting that no transaction writes are active
479 *
480 * @param string $fname Caller name (e.g. __METHOD__)
481 * @return mixed A value to pass to commitAndWaitForReplication()
482 * @since 1.28
483 */
484 public function getEmptyTransactionTicket( $fname ) {
485 if ( $this->hasMasterChanges() ) {
486 $this->trxLogger->error( __METHOD__ . ": $fname does not have outer scope." );
487 return null;
488 }
489
490 return $this->ticket;
491 }
492
493 /**
494 * Convenience method for safely running commitMasterChanges()/waitForReplication()
495 *
496 * This will commit and wait unless $ticket indicates it is unsafe to do so
497 *
498 * @param string $fname Caller name (e.g. __METHOD__)
499 * @param mixed $ticket Result of getOuterTransactionScopeTicket()
500 * @param array $opts Options to waitForReplication()
501 * @throws DBReplicationWaitError
502 * @since 1.28
503 */
504 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
505 if ( $ticket !== $this->ticket ) {
506 $logger = LoggerFactory::getInstance( 'DBPerformance' );
507 $logger->error( __METHOD__ . ": cannot commit; $fname does not have outer scope." );
508 return;
509 }
510
511 $this->commitMasterChanges( $fname );
512 $this->waitForReplication( $opts );
513 }
514
515 /**
516 * Disable the ChronologyProtector for all load balancers
517 *
518 * This can be called at the start of special API entry points
519 *
520 * @since 1.27
521 */
522 public function disableChronologyProtection() {
523 $this->chronProt->setEnabled( false );
524 }
525
526 /**
527 * @return ChronologyProtector
528 */
529 protected function newChronologyProtector() {
530 $request = RequestContext::getMain()->getRequest();
531 $chronProt = new ChronologyProtector(
532 ObjectCache::getMainStashInstance(),
533 [
534 'ip' => $request->getIP(),
535 'agent' => $request->getHeader( 'User-Agent' )
536 ]
537 );
538 if ( PHP_SAPI === 'cli' ) {
539 $chronProt->setEnabled( false );
540 } elseif ( $request->getHeader( 'ChronologyProtection' ) === 'false' ) {
541 // Request opted out of using position wait logic. This is useful for requests
542 // done by the job queue or background ETL that do not have a meaningful session.
543 $chronProt->setWaitEnabled( false );
544 }
545
546 return $chronProt;
547 }
548
549 /**
550 * @param ChronologyProtector $cp
551 */
552 protected function shutdownChronologyProtector( ChronologyProtector $cp ) {
553 // Get all the master positions needed
554 $this->forEachLB( function ( LoadBalancer $lb ) use ( $cp ) {
555 $cp->shutdownLB( $lb );
556 } );
557 // Write them to the stash
558 $unsavedPositions = $cp->shutdown();
559 // If the positions failed to write to the stash, at least wait on local datacenter
560 // slaves to catch up before responding. Even if there are several DCs, this increases
561 // the chance that the user will see their own changes immediately afterwards. As long
562 // as the sticky DC cookie applies (same domain), this is not even an issue.
563 $this->forEachLB( function ( LoadBalancer $lb ) use ( $unsavedPositions ) {
564 $masterName = $lb->getServerName( $lb->getWriterIndex() );
565 if ( isset( $unsavedPositions[$masterName] ) ) {
566 $lb->waitForAll( $unsavedPositions[$masterName] );
567 }
568 } );
569 }
570
571 /**
572 * @param LoadBalancer $lb
573 */
574 protected function initLoadBalancer( LoadBalancer $lb ) {
575 if ( $this->trxRoundId !== false ) {
576 $lb->beginMasterChanges( $this->trxRoundId ); // set DBO_TRX
577 }
578 }
579
580 /**
581 * Close all open database connections on all open load balancers.
582 * @since 1.28
583 */
584 public function closeAll() {
585 $this->forEachLBCallMethod( 'closeAll', [] );
586 }
587
588 }
589
590 /**
591 * Exception class for attempted DB access
592 */
593 class DBAccessError extends MWException {
594 public function __construct() {
595 parent::__construct( "Mediawiki tried to access the database via wfGetDB(). " .
596 "This is not allowed, because database access has been disabled." );
597 }
598 }
599
600 /**
601 * Exception class for replica DB wait timeouts
602 */
603 class DBReplicationWaitError extends Exception {
604 }