Merge "RCFilters: Style the Saved Links placeholder and add a title"
[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 namespace Wikimedia\Rdbms;
25
26 use Psr\Log\LoggerInterface;
27 use Wikimedia\ScopedCallback;
28 use BagOStuff;
29 use EmptyBagOStuff;
30 use WANObjectCache;
31 use Exception;
32 use RuntimeException;
33
34 /**
35 * An interface for generating database load balancers
36 * @ingroup Database
37 */
38 abstract class LBFactory implements ILBFactory {
39 /** @var ChronologyProtector */
40 protected $chronProt;
41 /** @var object|string Class name or object With profileIn/profileOut methods */
42 protected $profiler;
43 /** @var TransactionProfiler */
44 protected $trxProfiler;
45 /** @var LoggerInterface */
46 protected $replLogger;
47 /** @var LoggerInterface */
48 protected $connLogger;
49 /** @var LoggerInterface */
50 protected $queryLogger;
51 /** @var LoggerInterface */
52 protected $perfLogger;
53 /** @var callable Error logger */
54 protected $errorLogger;
55 /** @var BagOStuff */
56 protected $srvCache;
57 /** @var BagOStuff */
58 protected $memCache;
59 /** @var WANObjectCache */
60 protected $wanCache;
61
62 /** @var DatabaseDomain Local domain */
63 protected $localDomain;
64 /** @var string Local hostname of the app server */
65 protected $hostname;
66 /** @var array Web request information about the client */
67 protected $requestInfo;
68
69 /** @var mixed */
70 protected $ticket;
71 /** @var string|bool String if a requested DBO_TRX transaction round is active */
72 protected $trxRoundId = false;
73 /** @var string|bool Reason all LBs are read-only or false if not */
74 protected $readOnlyReason = false;
75 /** @var callable[] */
76 protected $replicationWaitCallbacks = [];
77
78 /** @var bool Whether this PHP instance is for a CLI script */
79 protected $cliMode;
80 /** @var string Agent name for query profiling */
81 protected $agent;
82
83 private static $loggerFields =
84 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
85
86 public function __construct( array $conf ) {
87 $this->localDomain = isset( $conf['localDomain'] )
88 ? DatabaseDomain::newFromId( $conf['localDomain'] )
89 : DatabaseDomain::newUnspecified();
90
91 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
92 $this->readOnlyReason = $conf['readOnlyReason'];
93 }
94
95 $this->srvCache = isset( $conf['srvCache'] ) ? $conf['srvCache'] : new EmptyBagOStuff();
96 $this->memCache = isset( $conf['memCache'] ) ? $conf['memCache'] : new EmptyBagOStuff();
97 $this->wanCache = isset( $conf['wanCache'] )
98 ? $conf['wanCache']
99 : WANObjectCache::newEmpty();
100
101 foreach ( self::$loggerFields as $key ) {
102 $this->$key = isset( $conf[$key] ) ? $conf[$key] : new \Psr\Log\NullLogger();
103 }
104 $this->errorLogger = isset( $conf['errorLogger'] )
105 ? $conf['errorLogger']
106 : function ( Exception $e ) {
107 trigger_error( E_USER_WARNING, get_class( $e ) . ': ' . $e->getMessage() );
108 };
109
110 $this->profiler = isset( $conf['profiler'] ) ? $conf['profiler'] : null;
111 $this->trxProfiler = isset( $conf['trxProfiler'] )
112 ? $conf['trxProfiler']
113 : new TransactionProfiler();
114
115 $this->requestInfo = [
116 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ? $_SERVER[ 'REMOTE_ADDR' ] : '',
117 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '',
118 'ChronologyProtection' => 'true'
119 ];
120
121 $this->cliMode = isset( $conf['cliMode'] ) ? $conf['cliMode'] : PHP_SAPI === 'cli';
122 $this->hostname = isset( $conf['hostname'] ) ? $conf['hostname'] : gethostname();
123 $this->agent = isset( $conf['agent'] ) ? $conf['agent'] : '';
124
125 $this->ticket = mt_rand();
126 }
127
128 public function destroy() {
129 $this->shutdown( self::SHUTDOWN_NO_CHRONPROT );
130 $this->forEachLBCallMethod( 'disable' );
131 }
132
133 public function shutdown(
134 $mode = self::SHUTDOWN_CHRONPROT_SYNC, callable $workCallback = null
135 ) {
136 $chronProt = $this->getChronologyProtector();
137 if ( $mode === self::SHUTDOWN_CHRONPROT_SYNC ) {
138 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync' );
139 } elseif ( $mode === self::SHUTDOWN_CHRONPROT_ASYNC ) {
140 $this->shutdownChronologyProtector( $chronProt, null, 'async' );
141 }
142
143 $this->commitMasterChanges( __METHOD__ ); // sanity
144 }
145
146 /**
147 * @see ILBFactory::newMainLB()
148 * @param bool $domain
149 * @return LoadBalancer
150 */
151 abstract public function newMainLB( $domain = false );
152
153 /**
154 * @see ILBFactory::getMainLB()
155 * @param bool $domain
156 * @return LoadBalancer
157 */
158 abstract public function getMainLB( $domain = false );
159
160 /**
161 * @see ILBFactory::newExternalLB()
162 * @param string $cluster
163 * @return LoadBalancer
164 */
165 abstract public function newExternalLB( $cluster );
166
167 /**
168 * @see ILBFactory::getExternalLB()
169 * @param string $cluster
170 * @return LoadBalancer
171 */
172 abstract public function getExternalLB( $cluster );
173
174 /**
175 * Call a method of each tracked load balancer
176 *
177 * @param string $methodName
178 * @param array $args
179 */
180 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
181 $this->forEachLB(
182 function ( ILoadBalancer $loadBalancer, $methodName, array $args ) {
183 call_user_func_array( [ $loadBalancer, $methodName ], $args );
184 },
185 [ $methodName, $args ]
186 );
187 }
188
189 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
190 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
191 }
192
193 public function commitAll( $fname = __METHOD__, array $options = [] ) {
194 $this->commitMasterChanges( $fname, $options );
195 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
196 }
197
198 public function beginMasterChanges( $fname = __METHOD__ ) {
199 if ( $this->trxRoundId !== false ) {
200 throw new DBTransactionError(
201 null,
202 "$fname: transaction round '{$this->trxRoundId}' already started."
203 );
204 }
205 $this->trxRoundId = $fname;
206 // Set DBO_TRX flags on all appropriate DBs
207 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
208 }
209
210 public function commitMasterChanges( $fname = __METHOD__, array $options = [] ) {
211 if ( $this->trxRoundId !== false && $this->trxRoundId !== $fname ) {
212 throw new DBTransactionError(
213 null,
214 "$fname: transaction round '{$this->trxRoundId}' still running."
215 );
216 }
217 /** @noinspection PhpUnusedLocalVariableInspection */
218 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
219 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
220 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
221 $this->trxRoundId = false;
222 // Perform pre-commit checks, aborting on failure
223 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
224 // Log the DBs and methods involved in multi-DB transactions
225 $this->logIfMultiDbTransaction();
226 // Actually perform the commit on all master DB connections and revert DBO_TRX
227 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
228 // Run all post-commit callbacks
229 /** @var Exception $e */
230 $e = null; // first callback exception
231 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$e ) {
232 $ex = $lb->runMasterPostTrxCallbacks( IDatabase::TRIGGER_COMMIT );
233 $e = $e ?: $ex;
234 } );
235 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
236 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
237 // Throw any last post-commit callback error
238 if ( $e instanceof Exception ) {
239 throw $e;
240 }
241 }
242
243 public function rollbackMasterChanges( $fname = __METHOD__ ) {
244 $this->trxRoundId = false;
245 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
246 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
247 // Run all post-rollback callbacks
248 $this->forEachLB( function ( ILoadBalancer $lb ) {
249 $lb->runMasterPostTrxCallbacks( IDatabase::TRIGGER_ROLLBACK );
250 } );
251 }
252
253 /**
254 * Log query info if multi DB transactions are going to be committed now
255 */
256 private function logIfMultiDbTransaction() {
257 $callersByDB = [];
258 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$callersByDB ) {
259 $masterName = $lb->getServerName( $lb->getWriterIndex() );
260 $callers = $lb->pendingMasterChangeCallers();
261 if ( $callers ) {
262 $callersByDB[$masterName] = $callers;
263 }
264 } );
265
266 if ( count( $callersByDB ) >= 2 ) {
267 $dbs = implode( ', ', array_keys( $callersByDB ) );
268 $msg = "Multi-DB transaction [{$dbs}]:\n";
269 foreach ( $callersByDB as $db => $callers ) {
270 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
271 }
272 $this->queryLogger->info( $msg );
273 }
274 }
275
276 public function hasMasterChanges() {
277 $ret = false;
278 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) {
279 $ret = $ret || $lb->hasMasterChanges();
280 } );
281
282 return $ret;
283 }
284
285 public function laggedReplicaUsed() {
286 $ret = false;
287 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) {
288 $ret = $ret || $lb->laggedReplicaUsed();
289 } );
290
291 return $ret;
292 }
293
294 public function hasOrMadeRecentMasterChanges( $age = null ) {
295 $ret = false;
296 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $age, &$ret ) {
297 $ret = $ret || $lb->hasOrMadeRecentMasterChanges( $age );
298 } );
299 return $ret;
300 }
301
302 public function waitForReplication( array $opts = [] ) {
303 $opts += [
304 'domain' => false,
305 'cluster' => false,
306 'timeout' => 60,
307 'ifWritesSince' => null
308 ];
309
310 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
311 $opts['domain'] = $opts['wiki']; // b/c
312 }
313
314 // Figure out which clusters need to be checked
315 /** @var ILoadBalancer[] $lbs */
316 $lbs = [];
317 if ( $opts['cluster'] !== false ) {
318 $lbs[] = $this->getExternalLB( $opts['cluster'] );
319 } elseif ( $opts['domain'] !== false ) {
320 $lbs[] = $this->getMainLB( $opts['domain'] );
321 } else {
322 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$lbs ) {
323 $lbs[] = $lb;
324 } );
325 if ( !$lbs ) {
326 return; // nothing actually used
327 }
328 }
329
330 // Get all the master positions of applicable DBs right now.
331 // This can be faster since waiting on one cluster reduces the
332 // time needed to wait on the next clusters.
333 $masterPositions = array_fill( 0, count( $lbs ), false );
334 foreach ( $lbs as $i => $lb ) {
335 if ( $lb->getServerCount() <= 1 ) {
336 // T29975 - Don't try to wait for replica DBs if there are none
337 // Prevents permission error when getting master position
338 continue;
339 } elseif ( $opts['ifWritesSince']
340 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
341 ) {
342 continue; // no writes since the last wait
343 }
344 $masterPositions[$i] = $lb->getMasterPos();
345 }
346
347 // Run any listener callbacks *after* getting the DB positions. The more
348 // time spent in the callbacks, the less time is spent in waitForAll().
349 foreach ( $this->replicationWaitCallbacks as $callback ) {
350 $callback();
351 }
352
353 $failed = [];
354 foreach ( $lbs as $i => $lb ) {
355 if ( $masterPositions[$i] ) {
356 // The DBMS may not support getMasterPos()
357 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
358 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
359 }
360 }
361 }
362
363 if ( $failed ) {
364 throw new DBReplicationWaitError(
365 null,
366 "Could not wait for replica DBs to catch up to " .
367 implode( ', ', $failed )
368 );
369 }
370 }
371
372 public function setWaitForReplicationListener( $name, callable $callback = null ) {
373 if ( $callback ) {
374 $this->replicationWaitCallbacks[$name] = $callback;
375 } else {
376 unset( $this->replicationWaitCallbacks[$name] );
377 }
378 }
379
380 public function getEmptyTransactionTicket( $fname ) {
381 if ( $this->hasMasterChanges() ) {
382 $this->queryLogger->error( __METHOD__ . ": $fname does not have outer scope.\n" .
383 ( new RuntimeException() )->getTraceAsString() );
384
385 return null;
386 }
387
388 return $this->ticket;
389 }
390
391 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
392 if ( $ticket !== $this->ticket ) {
393 $this->perfLogger->error( __METHOD__ . ": $fname does not have outer scope.\n" .
394 ( new RuntimeException() )->getTraceAsString() );
395
396 return;
397 }
398
399 // The transaction owner and any caller with the empty transaction ticket can commit
400 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
401 if ( $this->trxRoundId !== false && $fname !== $this->trxRoundId ) {
402 $this->queryLogger->info( "$fname: committing on behalf of {$this->trxRoundId}." );
403 $fnameEffective = $this->trxRoundId;
404 } else {
405 $fnameEffective = $fname;
406 }
407
408 $this->commitMasterChanges( $fnameEffective );
409 $this->waitForReplication( $opts );
410 // If a nested caller committed on behalf of $fname, start another empty $fname
411 // transaction, leaving the caller with the same empty transaction state as before.
412 if ( $fnameEffective !== $fname ) {
413 $this->beginMasterChanges( $fnameEffective );
414 }
415 }
416
417 public function getChronologyProtectorTouched( $dbName ) {
418 return $this->getChronologyProtector()->getTouched( $dbName );
419 }
420
421 public function disableChronologyProtection() {
422 $this->getChronologyProtector()->setEnabled( false );
423 }
424
425 /**
426 * @return ChronologyProtector
427 */
428 protected function getChronologyProtector() {
429 if ( $this->chronProt ) {
430 return $this->chronProt;
431 }
432
433 $this->chronProt = new ChronologyProtector(
434 $this->memCache,
435 [
436 'ip' => $this->requestInfo['IPAddress'],
437 'agent' => $this->requestInfo['UserAgent'],
438 ],
439 isset( $_GET['cpPosTime'] ) ? $_GET['cpPosTime'] : null
440 );
441 $this->chronProt->setLogger( $this->replLogger );
442
443 if ( $this->cliMode ) {
444 $this->chronProt->setEnabled( false );
445 } elseif ( $this->requestInfo['ChronologyProtection'] === 'false' ) {
446 // Request opted out of using position wait logic. This is useful for requests
447 // done by the job queue or background ETL that do not have a meaningful session.
448 $this->chronProt->setWaitEnabled( false );
449 }
450
451 $this->replLogger->debug( __METHOD__ . ': using request info ' .
452 json_encode( $this->requestInfo, JSON_PRETTY_PRINT ) );
453
454 return $this->chronProt;
455 }
456
457 /**
458 * Get and record all of the staged DB positions into persistent memory storage
459 *
460 * @param ChronologyProtector $cp
461 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
462 * @param string $mode One of (sync, async); whether to wait on remote datacenters
463 */
464 protected function shutdownChronologyProtector(
465 ChronologyProtector $cp, $workCallback, $mode
466 ) {
467 // Record all the master positions needed
468 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $cp ) {
469 $cp->shutdownLB( $lb );
470 } );
471 // Write them to the persistent stash. Try to do something useful by running $work
472 // while ChronologyProtector waits for the stash write to replicate to all DCs.
473 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
474 if ( $unsavedPositions && $workCallback ) {
475 // Invoke callback in case it did not cache the result yet
476 $workCallback(); // work now to block for less time in waitForAll()
477 }
478 // If the positions failed to write to the stash, at least wait on local datacenter
479 // replica DBs to catch up before responding. Even if there are several DCs, this increases
480 // the chance that the user will see their own changes immediately afterwards. As long
481 // as the sticky DC cookie applies (same domain), this is not even an issue.
482 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $unsavedPositions ) {
483 $masterName = $lb->getServerName( $lb->getWriterIndex() );
484 if ( isset( $unsavedPositions[$masterName] ) ) {
485 $lb->waitForAll( $unsavedPositions[$masterName] );
486 }
487 } );
488 }
489
490 /**
491 * Base parameters to LoadBalancer::__construct()
492 * @return array
493 */
494 final protected function baseLoadBalancerParams() {
495 return [
496 'localDomain' => $this->localDomain,
497 'readOnlyReason' => $this->readOnlyReason,
498 'srvCache' => $this->srvCache,
499 'wanCache' => $this->wanCache,
500 'profiler' => $this->profiler,
501 'trxProfiler' => $this->trxProfiler,
502 'queryLogger' => $this->queryLogger,
503 'connLogger' => $this->connLogger,
504 'replLogger' => $this->replLogger,
505 'errorLogger' => $this->errorLogger,
506 'hostname' => $this->hostname,
507 'cliMode' => $this->cliMode,
508 'agent' => $this->agent,
509 'chronologyProtector' => $this->getChronologyProtector()
510 ];
511 }
512
513 /**
514 * @param ILoadBalancer $lb
515 */
516 protected function initLoadBalancer( ILoadBalancer $lb ) {
517 if ( $this->trxRoundId !== false ) {
518 $lb->beginMasterChanges( $this->trxRoundId ); // set DBO_TRX
519 }
520 }
521
522 public function setDomainPrefix( $prefix ) {
523 $this->localDomain = new DatabaseDomain(
524 $this->localDomain->getDatabase(),
525 null,
526 $prefix
527 );
528
529 $this->forEachLB( function( ILoadBalancer $lb ) use ( $prefix ) {
530 $lb->setDomainPrefix( $prefix );
531 } );
532 }
533
534 public function closeAll() {
535 $this->forEachLBCallMethod( 'closeAll', [] );
536 }
537
538 public function setAgentName( $agent ) {
539 $this->agent = $agent;
540 }
541
542 public function appendPreShutdownTimeAsQuery( $url, $time ) {
543 $usedCluster = 0;
544 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$usedCluster ) {
545 $usedCluster |= ( $lb->getServerCount() > 1 );
546 } );
547
548 if ( !$usedCluster ) {
549 return $url; // no master/replica clusters touched
550 }
551
552 return strpos( $url, '?' ) === false ? "$url?cpPosTime=$time" : "$url&cpPosTime=$time";
553 }
554
555 public function setRequestInfo( array $info ) {
556 $this->requestInfo = $info + $this->requestInfo;
557 }
558
559 /**
560 * Make PHP ignore user aborts/disconnects until the returned
561 * value leaves scope. This returns null and does nothing in CLI mode.
562 *
563 * @return ScopedCallback|null
564 */
565 final protected function getScopedPHPBehaviorForCommit() {
566 if ( PHP_SAPI != 'cli' ) { // https://bugs.php.net/bug.php?id=47540
567 $old = ignore_user_abort( true ); // avoid half-finished operations
568 return new ScopedCallback( function () use ( $old ) {
569 ignore_user_abort( $old );
570 } );
571 }
572
573 return null;
574 }
575
576 function __destruct() {
577 $this->destroy();
578 }
579 }
580
581 class_alias( LBFactory::class, 'LBFactory' );