Merge "Floor slave lag before display"
[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 */
200 public function shutdown( $flags = 0 ) {
201 if ( !( $flags & self::SHUTDOWN_NO_CHRONPROT ) ) {
202 $this->shutdownChronologyProtector( $this->chronProt );
203 }
204 $this->commitMasterChanges( __METHOD__ ); // sanity
205 }
206
207 /**
208 * Call a method of each tracked load balancer
209 *
210 * @param string $methodName
211 * @param array $args
212 */
213 private function forEachLBCallMethod( $methodName, array $args = [] ) {
214 $this->forEachLB(
215 function ( LoadBalancer $loadBalancer, $methodName, array $args ) {
216 call_user_func_array( [ $loadBalancer, $methodName ], $args );
217 },
218 [ $methodName, $args ]
219 );
220 }
221
222 /**
223 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
224 *
225 * The DBO_TRX setting will be reverted to the default in each of these methods:
226 * - commitMasterChanges()
227 * - rollbackMasterChanges()
228 * - commitAll()
229 * This allows for custom transaction rounds from any outer transaction scope.
230 *
231 * @param string $fname
232 * @since 1.28
233 */
234 public function beginMasterChanges( $fname = __METHOD__ ) {
235 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
236 }
237
238 /**
239 * Commit on all connections. Done for two reasons:
240 * 1. To commit changes to the masters.
241 * 2. To release the snapshot on all connections, master and slave.
242 * @param string $fname Caller name
243 * @param array $options Options map:
244 * - maxWriteDuration: abort if more than this much time was spent in write queries
245 */
246 public function commitAll( $fname = __METHOD__, array $options = [] ) {
247 $this->commitMasterChanges( $fname, $options );
248 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
249 }
250
251 /**
252 * Commit changes on all master connections
253 * @param string $fname Caller name
254 * @param array $options Options map:
255 * - maxWriteDuration: abort if more than this much time was spent in write queries
256 * @throws Exception
257 */
258 public function commitMasterChanges( $fname = __METHOD__, array $options = [] ) {
259 // Perform all pre-commit callbacks, aborting on failure
260 $this->forEachLBCallMethod( 'runMasterPreCommitCallbacks' );
261 // Perform all pre-commit checks, aborting on failure
262 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
263 // Log the DBs and methods involved in multi-DB transactions
264 $this->logIfMultiDbTransaction();
265 // Actually perform the commit on all master DB connections
266 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
267 // Run all post-commit callbacks
268 /** @var Exception $e */
269 $e = null; // first callback exception
270 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$e ) {
271 $ex = $lb->runMasterPostCommitCallbacks();
272 $e = $e ?: $ex;
273 } );
274 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
275 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
276 // Throw any last post-commit callback error
277 if ( $e instanceof Exception ) {
278 throw $e;
279 }
280 }
281
282 /**
283 * Rollback changes on all master connections
284 * @param string $fname Caller name
285 * @since 1.23
286 */
287 public function rollbackMasterChanges( $fname = __METHOD__ ) {
288 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
289 }
290
291 /**
292 * Log query info if multi DB transactions are going to be committed now
293 */
294 private function logIfMultiDbTransaction() {
295 $callersByDB = [];
296 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$callersByDB ) {
297 $masterName = $lb->getServerName( $lb->getWriterIndex() );
298 $callers = $lb->pendingMasterChangeCallers();
299 if ( $callers ) {
300 $callersByDB[$masterName] = $callers;
301 }
302 } );
303
304 if ( count( $callersByDB ) >= 2 ) {
305 $dbs = implode( ', ', array_keys( $callersByDB ) );
306 $msg = "Multi-DB transaction [{$dbs}]:\n";
307 foreach ( $callersByDB as $db => $callers ) {
308 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
309 }
310 $this->trxLogger->info( $msg );
311 }
312 }
313
314 /**
315 * Determine if any master connection has pending changes
316 * @return bool
317 * @since 1.23
318 */
319 public function hasMasterChanges() {
320 $ret = false;
321 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
322 $ret = $ret || $lb->hasMasterChanges();
323 } );
324
325 return $ret;
326 }
327
328 /**
329 * Detemine if any lagged slave connection was used
330 * @since 1.27
331 * @return bool
332 */
333 public function laggedSlaveUsed() {
334 $ret = false;
335 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
336 $ret = $ret || $lb->laggedSlaveUsed();
337 } );
338
339 return $ret;
340 }
341
342 /**
343 * Determine if any master connection has pending/written changes from this request
344 * @return bool
345 * @since 1.27
346 */
347 public function hasOrMadeRecentMasterChanges() {
348 $ret = false;
349 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
350 $ret = $ret || $lb->hasOrMadeRecentMasterChanges();
351 } );
352 return $ret;
353 }
354
355 /**
356 * Waits for the slave DBs to catch up to the current master position
357 *
358 * Use this when updating very large numbers of rows, as in maintenance scripts,
359 * to avoid causing too much lag. Of course, this is a no-op if there are no slaves.
360 *
361 * By default this waits on all DB clusters actually used in this request.
362 * This makes sense when lag being waiting on is caused by the code that does this check.
363 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
364 * that were not changed since the last wait check. To forcefully wait on a specific cluster
365 * for a given wiki, use the 'wiki' parameter. To forcefully wait on an "external" cluster,
366 * use the "cluster" parameter.
367 *
368 * Never call this function after a large DB write that is *still* in a transaction.
369 * It only makes sense to call this after the possible lag inducing changes were committed.
370 *
371 * @param array $opts Optional fields that include:
372 * - wiki : wait on the load balancer DBs that handles the given wiki
373 * - cluster : wait on the given external load balancer DBs
374 * - timeout : Max wait time. Default: ~60 seconds
375 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
376 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
377 * @since 1.27
378 */
379 public function waitForReplication( array $opts = [] ) {
380 $opts += [
381 'wiki' => false,
382 'cluster' => false,
383 'timeout' => 60,
384 'ifWritesSince' => null
385 ];
386
387 // Figure out which clusters need to be checked
388 /** @var LoadBalancer[] $lbs */
389 $lbs = [];
390 if ( $opts['cluster'] !== false ) {
391 $lbs[] = $this->getExternalLB( $opts['cluster'] );
392 } elseif ( $opts['wiki'] !== false ) {
393 $lbs[] = $this->getMainLB( $opts['wiki'] );
394 } else {
395 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$lbs ) {
396 $lbs[] = $lb;
397 } );
398 if ( !$lbs ) {
399 return; // nothing actually used
400 }
401 }
402
403 // Get all the master positions of applicable DBs right now.
404 // This can be faster since waiting on one cluster reduces the
405 // time needed to wait on the next clusters.
406 $masterPositions = array_fill( 0, count( $lbs ), false );
407 foreach ( $lbs as $i => $lb ) {
408 if ( $lb->getServerCount() <= 1 ) {
409 // Bug 27975 - Don't try to wait for slaves if there are none
410 // Prevents permission error when getting master position
411 continue;
412 } elseif ( $opts['ifWritesSince']
413 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
414 ) {
415 continue; // no writes since the last wait
416 }
417 $masterPositions[$i] = $lb->getMasterPos();
418 }
419
420 $failed = [];
421 foreach ( $lbs as $i => $lb ) {
422 if ( $masterPositions[$i] ) {
423 // The DBMS may not support getMasterPos() or the whole
424 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
425 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
426 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
427 }
428 }
429 }
430
431 if ( $failed ) {
432 throw new DBReplicationWaitError(
433 "Could not wait for slaves to catch up to " .
434 implode( ', ', $failed )
435 );
436 }
437 }
438
439 /**
440 * Get a token asserting that no transaction writes are active
441 *
442 * @param string $fname Caller name (e.g. __METHOD__)
443 * @return mixed A value to pass to commitAndWaitForReplication()
444 * @since 1.28
445 */
446 public function getEmptyTransactionTicket( $fname ) {
447 if ( $this->hasMasterChanges() ) {
448 $this->trxLogger->error( __METHOD__ . ": $fname does not have outer scope." );
449 return null;
450 }
451
452 return $this->ticket;
453 }
454
455 /**
456 * Convenience method for safely running commitMasterChanges()/waitForReplication()
457 *
458 * This will commit and wait unless $ticket indicates it is unsafe to do so
459 *
460 * @param string $fname Caller name (e.g. __METHOD__)
461 * @param mixed $ticket Result of getOuterTransactionScopeTicket()
462 * @param array $opts Options to waitForReplication()
463 * @throws DBReplicationWaitError
464 * @since 1.28
465 */
466 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
467 if ( $ticket !== $this->ticket ) {
468 $logger = LoggerFactory::getInstance( 'DBPerformance' );
469 $logger->error( __METHOD__ . ": cannot commit; $fname does not have outer scope." );
470 return;
471 }
472
473 $this->commitMasterChanges( $fname );
474 $this->waitForReplication( $opts );
475 }
476
477 /**
478 * Disable the ChronologyProtector for all load balancers
479 *
480 * This can be called at the start of special API entry points
481 *
482 * @since 1.27
483 */
484 public function disableChronologyProtection() {
485 $this->chronProt->setEnabled( false );
486 }
487
488 /**
489 * @return ChronologyProtector
490 */
491 protected function newChronologyProtector() {
492 $request = RequestContext::getMain()->getRequest();
493 $chronProt = new ChronologyProtector(
494 ObjectCache::getMainStashInstance(),
495 [
496 'ip' => $request->getIP(),
497 'agent' => $request->getHeader( 'User-Agent' )
498 ]
499 );
500 if ( PHP_SAPI === 'cli' ) {
501 $chronProt->setEnabled( false );
502 } elseif ( $request->getHeader( 'ChronologyProtection' ) === 'false' ) {
503 // Request opted out of using position wait logic. This is useful for requests
504 // done by the job queue or background ETL that do not have a meaningful session.
505 $chronProt->setWaitEnabled( false );
506 }
507
508 return $chronProt;
509 }
510
511 /**
512 * @param ChronologyProtector $cp
513 */
514 protected function shutdownChronologyProtector( ChronologyProtector $cp ) {
515 // Get all the master positions needed
516 $this->forEachLB( function ( LoadBalancer $lb ) use ( $cp ) {
517 $cp->shutdownLB( $lb );
518 } );
519 // Write them to the stash
520 $unsavedPositions = $cp->shutdown();
521 // If the positions failed to write to the stash, at least wait on local datacenter
522 // slaves to catch up before responding. Even if there are several DCs, this increases
523 // the chance that the user will see their own changes immediately afterwards. As long
524 // as the sticky DC cookie applies (same domain), this is not even an issue.
525 $this->forEachLB( function ( LoadBalancer $lb ) use ( $unsavedPositions ) {
526 $masterName = $lb->getServerName( $lb->getWriterIndex() );
527 if ( isset( $unsavedPositions[$masterName] ) ) {
528 $lb->waitForAll( $unsavedPositions[$masterName] );
529 }
530 } );
531 }
532
533 /**
534 * Close all open database connections on all open load balancers.
535 * @since 1.28
536 */
537 public function closeAll() {
538 $this->forEachLBCallMethod( 'closeAll', [] );
539 }
540
541 }
542
543 /**
544 * Exception class for attempted DB access
545 */
546 class DBAccessError extends MWException {
547 public function __construct() {
548 parent::__construct( "Mediawiki tried to access the database via wfGetDB(). " .
549 "This is not allowed, because database access has been disabled." );
550 }
551 }
552
553 /**
554 * Exception class for replica DB wait timeouts
555 */
556 class DBReplicationWaitError extends Exception {
557 }