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