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