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