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