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