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