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