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