Merge "benchmarkParse: Add option to clear link cache"
[lhc/web/wiklou.git] / includes / libs / rdbms / lbfactory / LBFactory.php
1 <?php
2 /**
3 * Generator and manager 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
26 /**
27 * An interface for generating database load balancers
28 * @ingroup Database
29 */
30 abstract class LBFactory {
31 /** @var ChronologyProtector */
32 protected $chronProt;
33 /** @var TransactionProfiler */
34 protected $trxProfiler;
35 /** @var LoggerInterface */
36 protected $replLogger;
37 /** @var LoggerInterface */
38 protected $connLogger;
39 /** @var LoggerInterface */
40 protected $queryLogger;
41 /** @var LoggerInterface */
42 protected $perfLogger;
43 /** @var callable Error logger */
44 protected $errorLogger;
45 /** @var BagOStuff */
46 protected $srvCache;
47 /** @var BagOStuff */
48 protected $memCache;
49 /** @var WANObjectCache */
50 protected $wanCache;
51
52 /** @var string Local domain */
53 protected $domain;
54 /** @var string Local hostname of the app server */
55 protected $hostname;
56 /** @var mixed */
57 protected $ticket;
58 /** @var string|bool String if a requested DBO_TRX transaction round is active */
59 protected $trxRoundId = false;
60 /** @var string|bool Reason all LBs are read-only or false if not */
61 protected $readOnlyReason = false;
62 /** @var callable[] */
63 protected $replicationWaitCallbacks = [];
64
65 const SHUTDOWN_NO_CHRONPROT = 0; // don't save DB positions at all
66 const SHUTDOWN_CHRONPROT_ASYNC = 1; // save DB positions, but don't wait on remote DCs
67 const SHUTDOWN_CHRONPROT_SYNC = 2; // save DB positions, waiting on all DCs
68
69 private static $loggerFields =
70 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
71
72 /**
73 * @TODO: document base params here
74 * @param array $conf
75 */
76 public function __construct( array $conf ) {
77 $this->domain = isset( $conf['domain'] ) ? $conf['domain'] : '';
78 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
79 $this->readOnlyReason = $conf['readOnlyReason'];
80 }
81
82 $this->srvCache = isset( $conf['srvCache'] ) ? $conf['srvCache'] : new EmptyBagOStuff();
83 $this->memCache = isset( $conf['memCache'] ) ? $conf['memCache'] : new EmptyBagOStuff();
84 $this->wanCache = isset( $conf['wanCache'] )
85 ? $conf['wanCache']
86 : WANObjectCache::newEmpty();
87
88 foreach ( self::$loggerFields as $key ) {
89 $this->$key = isset( $conf[$key] ) ? $conf[$key] : new \Psr\Log\NullLogger();
90 }
91 $this->errorLogger = isset( $conf['errorLogger'] )
92 ? $conf['errorLogger']
93 : function ( Exception $e ) {
94 trigger_error( E_WARNING, $e->getMessage() );
95 };
96 $this->hostname = isset( $conf['hostname'] )
97 ? $conf['hostname']
98 : gethostname();
99
100 $this->chronProt = isset( $conf['chronProt'] )
101 ? $conf['chronProt']
102 : $this->newChronologyProtector();
103 $this->trxProfiler = isset( $conf['trxProfiler'] )
104 ? $conf['trxProfiler']
105 : new TransactionProfiler();
106
107 $this->ticket = mt_rand();
108 }
109
110 /**
111 * Disables all load balancers. All connections are closed, and any attempt to
112 * open a new connection will result in a DBAccessError.
113 * @see LoadBalancer::disable()
114 */
115 public function destroy() {
116 $this->shutdown( self::SHUTDOWN_NO_CHRONPROT );
117 $this->forEachLBCallMethod( 'disable' );
118 }
119
120 /**
121 * Create a new load balancer object. The resulting object will be untracked,
122 * not chronology-protected, and the caller is responsible for cleaning it up.
123 *
124 * @param bool|string $domain Wiki ID, or false for the current wiki
125 * @return ILoadBalancer
126 */
127 abstract public function newMainLB( $domain = false );
128
129 /**
130 * Get a cached (tracked) load balancer object.
131 *
132 * @param bool|string $domain Wiki ID, or false for the current wiki
133 * @return ILoadBalancer
134 */
135 abstract public function getMainLB( $domain = false );
136
137 /**
138 * Create a new load balancer for external storage. The resulting object will be
139 * untracked, not chronology-protected, and the caller is responsible for
140 * cleaning it up.
141 *
142 * @param string $cluster External storage cluster, or false for core
143 * @param bool|string $domain Wiki ID, or false for the current wiki
144 * @return ILoadBalancer
145 */
146 abstract protected function newExternalLB( $cluster, $domain = false );
147
148 /**
149 * Get a cached (tracked) load balancer for external storage
150 *
151 * @param string $cluster External storage cluster, or false for core
152 * @param bool|string $domain Wiki ID, or false for the current wiki
153 * @return ILoadBalancer
154 */
155 abstract public function getExternalLB( $cluster, $domain = false );
156
157 /**
158 * Execute a function for each tracked load balancer
159 * The callback is called with the load balancer as the first parameter,
160 * and $params passed as the subsequent parameters.
161 *
162 * @param callable $callback
163 * @param array $params
164 */
165 abstract public function forEachLB( $callback, array $params = [] );
166
167 /**
168 * Prepare all tracked load balancers for shutdown
169 * @param integer $mode One of the class SHUTDOWN_* constants
170 * @param callable|null $workCallback Work to mask ChronologyProtector writes
171 */
172 public function shutdown(
173 $mode = self::SHUTDOWN_CHRONPROT_SYNC, callable $workCallback = null
174 ) {
175 if ( $mode === self::SHUTDOWN_CHRONPROT_SYNC ) {
176 $this->shutdownChronologyProtector( $this->chronProt, $workCallback, 'sync' );
177 } elseif ( $mode === self::SHUTDOWN_CHRONPROT_ASYNC ) {
178 $this->shutdownChronologyProtector( $this->chronProt, null, 'async' );
179 }
180
181 $this->commitMasterChanges( __METHOD__ ); // sanity
182 }
183
184 /**
185 * Call a method of each tracked load balancer
186 *
187 * @param string $methodName
188 * @param array $args
189 */
190 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
191 $this->forEachLB(
192 function ( ILoadBalancer $loadBalancer, $methodName, array $args ) {
193 call_user_func_array( [ $loadBalancer, $methodName ], $args );
194 },
195 [ $methodName, $args ]
196 );
197 }
198
199 /**
200 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
201 *
202 * @param string $fname Caller name
203 * @since 1.28
204 */
205 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
206 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
207 }
208
209 /**
210 * Commit on all connections. Done for two reasons:
211 * 1. To commit changes to the masters.
212 * 2. To release the snapshot on all connections, master and replica DB.
213 * @param string $fname Caller name
214 * @param array $options Options map:
215 * - maxWriteDuration: abort if more than this much time was spent in write queries
216 */
217 public function commitAll( $fname = __METHOD__, array $options = [] ) {
218 $this->commitMasterChanges( $fname, $options );
219 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
220 }
221
222 /**
223 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
224 *
225 * The DBO_TRX setting will be reverted to the default in each of these methods:
226 * - commitMasterChanges()
227 * - rollbackMasterChanges()
228 * - commitAll()
229 *
230 * This allows for custom transaction rounds from any outer transaction scope.
231 *
232 * @param string $fname
233 * @throws DBTransactionError
234 * @since 1.28
235 */
236 public function beginMasterChanges( $fname = __METHOD__ ) {
237 if ( $this->trxRoundId !== false ) {
238 throw new DBTransactionError(
239 null,
240 "$fname: transaction round '{$this->trxRoundId}' already started."
241 );
242 }
243 $this->trxRoundId = $fname;
244 // Set DBO_TRX flags on all appropriate DBs
245 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
246 }
247
248 /**
249 * Commit changes on all master connections
250 * @param string $fname Caller name
251 * @param array $options Options map:
252 * - maxWriteDuration: abort if more than this much time was spent in write queries
253 * @throws Exception
254 */
255 public function commitMasterChanges( $fname = __METHOD__, array $options = [] ) {
256 if ( $this->trxRoundId !== false && $this->trxRoundId !== $fname ) {
257 throw new DBTransactionError(
258 null,
259 "$fname: transaction round '{$this->trxRoundId}' still running."
260 );
261 }
262 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
263 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
264 $this->trxRoundId = false;
265 // Perform pre-commit checks, aborting on failure
266 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
267 // Log the DBs and methods involved in multi-DB transactions
268 $this->logIfMultiDbTransaction();
269 // Actually perform the commit on all master DB connections and revert DBO_TRX
270 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
271 // Run all post-commit callbacks
272 /** @var Exception $e */
273 $e = null; // first callback exception
274 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$e ) {
275 $ex = $lb->runMasterPostTrxCallbacks( IDatabase::TRIGGER_COMMIT );
276 $e = $e ?: $ex;
277 } );
278 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
279 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
280 // Throw any last post-commit callback error
281 if ( $e instanceof Exception ) {
282 throw $e;
283 }
284 }
285
286 /**
287 * Rollback changes on all master connections
288 * @param string $fname Caller name
289 * @since 1.23
290 */
291 public function rollbackMasterChanges( $fname = __METHOD__ ) {
292 $this->trxRoundId = false;
293 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
294 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
295 // Run all post-rollback callbacks
296 $this->forEachLB( function ( ILoadBalancer $lb ) {
297 $lb->runMasterPostTrxCallbacks( IDatabase::TRIGGER_ROLLBACK );
298 } );
299 }
300
301 /**
302 * Log query info if multi DB transactions are going to be committed now
303 */
304 private function logIfMultiDbTransaction() {
305 $callersByDB = [];
306 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$callersByDB ) {
307 $masterName = $lb->getServerName( $lb->getWriterIndex() );
308 $callers = $lb->pendingMasterChangeCallers();
309 if ( $callers ) {
310 $callersByDB[$masterName] = $callers;
311 }
312 } );
313
314 if ( count( $callersByDB ) >= 2 ) {
315 $dbs = implode( ', ', array_keys( $callersByDB ) );
316 $msg = "Multi-DB transaction [{$dbs}]:\n";
317 foreach ( $callersByDB as $db => $callers ) {
318 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
319 }
320 $this->queryLogger->info( $msg );
321 }
322 }
323
324 /**
325 * Determine if any master connection has pending changes
326 * @return bool
327 * @since 1.23
328 */
329 public function hasMasterChanges() {
330 $ret = false;
331 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) {
332 $ret = $ret || $lb->hasMasterChanges();
333 } );
334
335 return $ret;
336 }
337
338 /**
339 * Detemine if any lagged replica DB connection was used
340 * @return bool
341 * @since 1.28
342 */
343 public function laggedReplicaUsed() {
344 $ret = false;
345 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) {
346 $ret = $ret || $lb->laggedReplicaUsed();
347 } );
348
349 return $ret;
350 }
351
352 /**
353 * Determine if any master connection has pending/written changes from this request
354 * @param float $age How many seconds ago is "recent" [defaults to LB lag wait timeout]
355 * @return bool
356 * @since 1.27
357 */
358 public function hasOrMadeRecentMasterChanges( $age = null ) {
359 $ret = false;
360 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $age, &$ret ) {
361 $ret = $ret || $lb->hasOrMadeRecentMasterChanges( $age );
362 } );
363 return $ret;
364 }
365
366 /**
367 * Waits for the replica DBs to catch up to the current master position
368 *
369 * Use this when updating very large numbers of rows, as in maintenance scripts,
370 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
371 *
372 * By default this waits on all DB clusters actually used in this request.
373 * This makes sense when lag being waiting on is caused by the code that does this check.
374 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
375 * that were not changed since the last wait check. To forcefully wait on a specific cluster
376 * for a given wiki, use the 'wiki' parameter. To forcefully wait on an "external" cluster,
377 * use the "cluster" parameter.
378 *
379 * Never call this function after a large DB write that is *still* in a transaction.
380 * It only makes sense to call this after the possible lag inducing changes were committed.
381 *
382 * @param array $opts Optional fields that include:
383 * - wiki : wait on the load balancer DBs that handles the given wiki
384 * - cluster : wait on the given external load balancer DBs
385 * - timeout : Max wait time. Default: ~60 seconds
386 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
387 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
388 * @since 1.27
389 */
390 public function waitForReplication( array $opts = [] ) {
391 $opts += [
392 'wiki' => false,
393 'cluster' => false,
394 'timeout' => 60,
395 'ifWritesSince' => null
396 ];
397
398 // Figure out which clusters need to be checked
399 /** @var ILoadBalancer[] $lbs */
400 $lbs = [];
401 if ( $opts['cluster'] !== false ) {
402 $lbs[] = $this->getExternalLB( $opts['cluster'] );
403 } elseif ( $opts['wiki'] !== false ) {
404 $lbs[] = $this->getMainLB( $opts['wiki'] );
405 } else {
406 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$lbs ) {
407 $lbs[] = $lb;
408 } );
409 if ( !$lbs ) {
410 return; // nothing actually used
411 }
412 }
413
414 // Get all the master positions of applicable DBs right now.
415 // This can be faster since waiting on one cluster reduces the
416 // time needed to wait on the next clusters.
417 $masterPositions = array_fill( 0, count( $lbs ), false );
418 foreach ( $lbs as $i => $lb ) {
419 if ( $lb->getServerCount() <= 1 ) {
420 // Bug 27975 - Don't try to wait for replica DBs if there are none
421 // Prevents permission error when getting master position
422 continue;
423 } elseif ( $opts['ifWritesSince']
424 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
425 ) {
426 continue; // no writes since the last wait
427 }
428 $masterPositions[$i] = $lb->getMasterPos();
429 }
430
431 // Run any listener callbacks *after* getting the DB positions. The more
432 // time spent in the callbacks, the less time is spent in waitForAll().
433 foreach ( $this->replicationWaitCallbacks as $callback ) {
434 $callback();
435 }
436
437 $failed = [];
438 foreach ( $lbs as $i => $lb ) {
439 if ( $masterPositions[$i] ) {
440 // The DBMS may not support getMasterPos() or the whole
441 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
442 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
443 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
444 }
445 }
446 }
447
448 if ( $failed ) {
449 throw new DBReplicationWaitError(
450 "Could not wait for replica DBs to catch up to " .
451 implode( ', ', $failed )
452 );
453 }
454 }
455
456 /**
457 * Add a callback to be run in every call to waitForReplication() before waiting
458 *
459 * Callbacks must clear any transactions that they start
460 *
461 * @param string $name Callback name
462 * @param callable|null $callback Use null to unset a callback
463 * @since 1.28
464 */
465 public function setWaitForReplicationListener( $name, callable $callback = null ) {
466 if ( $callback ) {
467 $this->replicationWaitCallbacks[$name] = $callback;
468 } else {
469 unset( $this->replicationWaitCallbacks[$name] );
470 }
471 }
472
473 /**
474 * Get a token asserting that no transaction writes are active
475 *
476 * @param string $fname Caller name (e.g. __METHOD__)
477 * @return mixed A value to pass to commitAndWaitForReplication()
478 * @since 1.28
479 */
480 public function getEmptyTransactionTicket( $fname ) {
481 if ( $this->hasMasterChanges() ) {
482 $this->queryLogger->error( __METHOD__ . ": $fname does not have outer scope." );
483 return null;
484 }
485
486 return $this->ticket;
487 }
488
489 /**
490 * Convenience method for safely running commitMasterChanges()/waitForReplication()
491 *
492 * This will commit and wait unless $ticket indicates it is unsafe to do so
493 *
494 * @param string $fname Caller name (e.g. __METHOD__)
495 * @param mixed $ticket Result of getEmptyTransactionTicket()
496 * @param array $opts Options to waitForReplication()
497 * @throws DBReplicationWaitError
498 * @since 1.28
499 */
500 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
501 if ( $ticket !== $this->ticket ) {
502 $this->perfLogger->error( __METHOD__ . ": $fname does not have outer scope." );
503 return;
504 }
505
506 // The transaction owner and any caller with the empty transaction ticket can commit
507 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
508 if ( $this->trxRoundId !== false && $fname !== $this->trxRoundId ) {
509 $this->queryLogger->info( "$fname: committing on behalf of {$this->trxRoundId}." );
510 $fnameEffective = $this->trxRoundId;
511 } else {
512 $fnameEffective = $fname;
513 }
514
515 $this->commitMasterChanges( $fnameEffective );
516 $this->waitForReplication( $opts );
517 // If a nested caller committed on behalf of $fname, start another empty $fname
518 // transaction, leaving the caller with the same empty transaction state as before.
519 if ( $fnameEffective !== $fname ) {
520 $this->beginMasterChanges( $fnameEffective );
521 }
522 }
523
524 /**
525 * @param string $dbName DB master name (e.g. "db1052")
526 * @return float|bool UNIX timestamp when client last touched the DB or false if not recent
527 * @since 1.28
528 */
529 public function getChronologyProtectorTouched( $dbName ) {
530 return $this->chronProt->getTouched( $dbName );
531 }
532
533 /**
534 * Disable the ChronologyProtector for all load balancers
535 *
536 * This can be called at the start of special API entry points
537 *
538 * @since 1.27
539 */
540 public function disableChronologyProtection() {
541 $this->chronProt->setEnabled( false );
542 }
543
544 /**
545 * @return ChronologyProtector
546 */
547 protected function newChronologyProtector() {
548 $chronProt = new ChronologyProtector(
549 $this->memCache,
550 [
551 'ip' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ? $_SERVER[ 'REMOTE_ADDR' ] : '',
552 'agent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : ''
553 ],
554 isset( $_GET['cpPosTime'] ) ? $_GET['cpPosTime'] : null
555 );
556 $chronProt->setLogger( $this->replLogger );
557 if ( PHP_SAPI === 'cli' ) {
558 $chronProt->setEnabled( false );
559 }
560
561 return $chronProt;
562 }
563
564 /**
565 * Get and record all of the staged DB positions into persistent memory storage
566 *
567 * @param ChronologyProtector $cp
568 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
569 * @param string $mode One of (sync, async); whether to wait on remote datacenters
570 */
571 protected function shutdownChronologyProtector(
572 ChronologyProtector $cp, $workCallback, $mode
573 ) {
574 // Record all the master positions needed
575 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $cp ) {
576 $cp->shutdownLB( $lb );
577 } );
578 // Write them to the persistent stash. Try to do something useful by running $work
579 // while ChronologyProtector waits for the stash write to replicate to all DCs.
580 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
581 if ( $unsavedPositions && $workCallback ) {
582 // Invoke callback in case it did not cache the result yet
583 $workCallback(); // work now to block for less time in waitForAll()
584 }
585 // If the positions failed to write to the stash, at least wait on local datacenter
586 // replica DBs to catch up before responding. Even if there are several DCs, this increases
587 // the chance that the user will see their own changes immediately afterwards. As long
588 // as the sticky DC cookie applies (same domain), this is not even an issue.
589 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $unsavedPositions ) {
590 $masterName = $lb->getServerName( $lb->getWriterIndex() );
591 if ( isset( $unsavedPositions[$masterName] ) ) {
592 $lb->waitForAll( $unsavedPositions[$masterName] );
593 }
594 } );
595 }
596
597 /**
598 * Base parameters to LoadBalancer::__construct()
599 * @return array
600 */
601 final protected function baseLoadBalancerParams() {
602 return [
603 'localDomain' => $this->domain,
604 'readOnlyReason' => $this->readOnlyReason,
605 'srvCache' => $this->srvCache,
606 'wanCache' => $this->wanCache,
607 'trxProfiler' => $this->trxProfiler,
608 'queryLogger' => $this->queryLogger,
609 'connLogger' => $this->connLogger,
610 'replLogger' => $this->replLogger,
611 'errorLogger' => $this->errorLogger,
612 'hostname' => $this->hostname
613 ];
614 }
615
616 /**
617 * @param ILoadBalancer $lb
618 */
619 protected function initLoadBalancer( ILoadBalancer $lb ) {
620 if ( $this->trxRoundId !== false ) {
621 $lb->beginMasterChanges( $this->trxRoundId ); // set DBO_TRX
622 }
623 }
624
625 /**
626 * Define a new local domain (for testing)
627 *
628 * Caller should make sure no local connection are open to the old local domain
629 *
630 * @param string $domain
631 * @since 1.28
632 */
633 public function setDomainPrefix( $domain ) {
634 $this->domain = $domain;
635 }
636
637 /**
638 * Close all open database connections on all open load balancers.
639 * @since 1.28
640 */
641 public function closeAll() {
642 $this->forEachLBCallMethod( 'closeAll', [] );
643 }
644 }