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