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