Merge "Title: Title::getSubpage should not lose the interwiki prefix"
[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 Psr\Log\NullLogger;
28 use Wikimedia\ScopedCallback;
29 use BagOStuff;
30 use EmptyBagOStuff;
31 use WANObjectCache;
32 use Exception;
33 use RuntimeException;
34 use LogicException;
35
36 /**
37 * An interface for generating database load balancers
38 * @ingroup Database
39 */
40 abstract class LBFactory implements ILBFactory {
41 /** @var ChronologyProtector */
42 private $chronProt;
43 /** @var object|string Class name or object With profileIn/profileOut methods */
44 private $profiler;
45 /** @var TransactionProfiler */
46 private $trxProfiler;
47 /** @var LoggerInterface */
48 private $replLogger;
49 /** @var LoggerInterface */
50 private $connLogger;
51 /** @var LoggerInterface */
52 private $queryLogger;
53 /** @var LoggerInterface */
54 private $perfLogger;
55 /** @var callable Error logger */
56 private $errorLogger;
57 /** @var callable Deprecation logger */
58 private $deprecationLogger;
59
60 /** @var BagOStuff */
61 protected $srvCache;
62 /** @var BagOStuff */
63 protected $memStash;
64 /** @var WANObjectCache */
65 protected $wanCache;
66
67 /** @var DatabaseDomain Local domain */
68 protected $localDomain;
69
70 /** @var string Local hostname of the app server */
71 private $hostname;
72 /** @var array Web request information about the client */
73 private $requestInfo;
74 /** @var bool Whether this PHP instance is for a CLI script */
75 private $cliMode;
76 /** @var string Agent name for query profiling */
77 private $agent;
78 /** @var string Secret string for HMAC hashing */
79 private $secret;
80
81 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
82 private $tableAliases = [];
83 /** @var string[] Map of (index alias => index) */
84 private $indexAliases = [];
85 /** @var callable[] */
86 private $replicationWaitCallbacks = [];
87
88 /** var int An identifier for this class instance */
89 private $id;
90 /** @var int|null Ticket used to delegate transaction ownership */
91 private $ticket;
92 /** @var string|bool String if a requested DBO_TRX transaction round is active */
93 private $trxRoundId = false;
94 /** @var string One of the ROUND_* class constants */
95 private $trxRoundStage = self::ROUND_CURSORY;
96
97 /** @var string|bool Reason all LBs are read-only or false if not */
98 protected $readOnlyReason = false;
99
100 /** @var string|null */
101 private $defaultGroup = null;
102
103 /** @var int|null */
104 protected $maxLag;
105
106 const ROUND_CURSORY = 'cursory';
107 const ROUND_BEGINNING = 'within-begin';
108 const ROUND_COMMITTING = 'within-commit';
109 const ROUND_ROLLING_BACK = 'within-rollback';
110 const ROUND_COMMIT_CALLBACKS = 'within-commit-callbacks';
111 const ROUND_ROLLBACK_CALLBACKS = 'within-rollback-callbacks';
112
113 private static $loggerFields =
114 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
115
116 public function __construct( array $conf ) {
117 $this->localDomain = isset( $conf['localDomain'] )
118 ? DatabaseDomain::newFromId( $conf['localDomain'] )
119 : DatabaseDomain::newUnspecified();
120
121 $this->maxLag = $conf['maxLag'] ?? null;
122 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
123 $this->readOnlyReason = $conf['readOnlyReason'];
124 }
125
126 $this->srvCache = $conf['srvCache'] ?? new EmptyBagOStuff();
127 $this->memStash = $conf['memStash'] ?? new EmptyBagOStuff();
128 $this->wanCache = $conf['wanCache'] ?? WANObjectCache::newEmpty();
129
130 foreach ( self::$loggerFields as $key ) {
131 $this->$key = $conf[$key] ?? new NullLogger();
132 }
133 $this->errorLogger = $conf['errorLogger'] ?? function ( Exception $e ) {
134 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
135 };
136 $this->deprecationLogger = $conf['deprecationLogger'] ?? function ( $msg ) {
137 trigger_error( $msg, E_USER_DEPRECATED );
138 };
139
140 $this->profiler = $conf['profiler'] ?? null;
141 $this->trxProfiler = $conf['trxProfiler'] ?? new TransactionProfiler();
142
143 $this->requestInfo = [
144 'IPAddress' => $_SERVER[ 'REMOTE_ADDR' ] ?? '',
145 'UserAgent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
146 // Headers application can inject via LBFactory::setRequestInfo()
147 'ChronologyProtection' => null,
148 'ChronologyClientId' => null, // prior $cpClientId value from LBFactory::shutdown()
149 'ChronologyPositionIndex' => null // prior $cpIndex value from LBFactory::shutdown()
150 ];
151
152 $this->cliMode = $conf['cliMode'] ?? ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' );
153 $this->hostname = $conf['hostname'] ?? gethostname();
154 $this->agent = $conf['agent'] ?? '';
155 $this->defaultGroup = $conf['defaultGroup'] ?? null;
156 $this->secret = $conf['secret'] ?? '';
157
158 $this->id = mt_rand();
159 $this->ticket = mt_rand();
160 }
161
162 public function destroy() {
163 $this->shutdown( self::SHUTDOWN_NO_CHRONPROT );
164 $this->forEachLBCallMethod( 'disable' );
165 }
166
167 public function getLocalDomainID() {
168 return $this->localDomain->getId();
169 }
170
171 public function resolveDomainID( $domain ) {
172 return ( $domain !== false ) ? (string)$domain : $this->getLocalDomainID();
173 }
174
175 public function shutdown(
176 $mode = self::SHUTDOWN_CHRONPROT_SYNC,
177 callable $workCallback = null,
178 &$cpIndex = null,
179 &$cpClientId = null
180 ) {
181 $chronProt = $this->getChronologyProtector();
182 if ( $mode === self::SHUTDOWN_CHRONPROT_SYNC ) {
183 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync', $cpIndex );
184 } elseif ( $mode === self::SHUTDOWN_CHRONPROT_ASYNC ) {
185 $this->shutdownChronologyProtector( $chronProt, null, 'async', $cpIndex );
186 }
187
188 $cpClientId = $chronProt->getClientId();
189
190 $this->commitMasterChanges( __METHOD__ ); // sanity
191 }
192
193 /**
194 * @see ILBFactory::newMainLB()
195 * @param bool $domain
196 * @return ILoadBalancer
197 */
198 abstract public function newMainLB( $domain = false );
199
200 /**
201 * @see ILBFactory::getMainLB()
202 * @param bool $domain
203 * @return ILoadBalancer
204 */
205 abstract public function getMainLB( $domain = false );
206
207 /**
208 * @see ILBFactory::newExternalLB()
209 * @param string $cluster
210 * @return ILoadBalancer
211 */
212 abstract public function newExternalLB( $cluster );
213
214 /**
215 * @see ILBFactory::getExternalLB()
216 * @param string $cluster
217 * @return ILoadBalancer
218 */
219 abstract public function getExternalLB( $cluster );
220
221 /**
222 * Call a method of each tracked load balancer
223 *
224 * @param string $methodName
225 * @param array $args
226 */
227 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
228 $this->forEachLB(
229 function ( ILoadBalancer $loadBalancer, $methodName, array $args ) {
230 $loadBalancer->$methodName( ...$args );
231 },
232 [ $methodName, $args ]
233 );
234 }
235
236 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
237 if ( $this->trxRoundId !== false && $this->trxRoundId !== $fname ) {
238 $this->queryLogger->warning(
239 "$fname: transaction round '{$this->trxRoundId}' still running",
240 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
241 );
242 }
243 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
244 }
245
246 final public function commitAll( $fname = __METHOD__, array $options = [] ) {
247 $this->commitMasterChanges( $fname, $options );
248 $this->forEachLBCallMethod( 'flushMasterSnapshots', [ $fname ] );
249 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
250 }
251
252 final public function beginMasterChanges( $fname = __METHOD__ ) {
253 $this->assertTransactionRoundStage( self::ROUND_CURSORY );
254 $this->trxRoundStage = self::ROUND_BEGINNING;
255 if ( $this->trxRoundId !== false ) {
256 throw new DBTransactionError(
257 null,
258 "$fname: transaction round '{$this->trxRoundId}' already started"
259 );
260 }
261 $this->trxRoundId = $fname;
262 // Set DBO_TRX flags on all appropriate DBs
263 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname, $this->id ] );
264 $this->trxRoundStage = self::ROUND_CURSORY;
265 }
266
267 final public function commitMasterChanges( $fname = __METHOD__, array $options = [] ) {
268 $this->assertTransactionRoundStage( self::ROUND_CURSORY );
269 $this->trxRoundStage = self::ROUND_COMMITTING;
270 if ( $this->trxRoundId !== false && $this->trxRoundId !== $fname ) {
271 throw new DBTransactionError(
272 null,
273 "$fname: transaction round '{$this->trxRoundId}' still running"
274 );
275 }
276 /** @noinspection PhpUnusedLocalVariableInspection */
277 $scope = ScopedCallback::newScopedIgnoreUserAbort(); // try to ignore client aborts
278 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
279 do {
280 $count = 0; // number of callbacks executed this iteration
281 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$count, $fname ) {
282 $count += $lb->finalizeMasterChanges( $fname, $this->id );
283 } );
284 } while ( $count > 0 );
285 $this->trxRoundId = false;
286 // Perform pre-commit checks, aborting on failure
287 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options, $fname, $this->id ] );
288 // Log the DBs and methods involved in multi-DB transactions
289 $this->logIfMultiDbTransaction();
290 // Actually perform the commit on all master DB connections and revert DBO_TRX
291 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname, $this->id ] );
292 // Run all post-commit callbacks in a separate step
293 $this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS;
294 $e = $this->executePostTransactionCallbacks();
295 $this->trxRoundStage = self::ROUND_CURSORY;
296 // Throw any last post-commit callback error
297 if ( $e instanceof Exception ) {
298 throw $e;
299 }
300 }
301
302 final public function rollbackMasterChanges( $fname = __METHOD__ ) {
303 $this->trxRoundStage = self::ROUND_ROLLING_BACK;
304 $this->trxRoundId = false;
305 // Actually perform the rollback on all master DB connections and revert DBO_TRX
306 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname, $this->id ] );
307 // Run all post-commit callbacks in a separate step
308 $this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS;
309 $this->executePostTransactionCallbacks();
310 $this->trxRoundStage = self::ROUND_CURSORY;
311 }
312
313 /**
314 * @return Exception|null
315 */
316 private function executePostTransactionCallbacks() {
317 $fname = __METHOD__;
318 // Run all post-commit callbacks until new ones stop getting added
319 $e = null; // first callback exception
320 do {
321 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$e, $fname ) {
322 $ex = $lb->runMasterTransactionIdleCallbacks( $fname, $this->id );
323 $e = $e ?: $ex;
324 } );
325 } while ( $this->hasMasterChanges() );
326 // Run all listener callbacks once
327 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$e, $fname ) {
328 $ex = $lb->runMasterTransactionListenerCallbacks( $fname, $this->id );
329 $e = $e ?: $ex;
330 } );
331
332 return $e;
333 }
334
335 public function hasTransactionRound() {
336 return ( $this->trxRoundId !== false );
337 }
338
339 public function isReadyForRoundOperations() {
340 return ( $this->trxRoundStage === self::ROUND_CURSORY );
341 }
342
343 /**
344 * Log query info if multi DB transactions are going to be committed now
345 */
346 private function logIfMultiDbTransaction() {
347 $callersByDB = [];
348 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$callersByDB ) {
349 $masterName = $lb->getServerName( $lb->getWriterIndex() );
350 $callers = $lb->pendingMasterChangeCallers();
351 if ( $callers ) {
352 $callersByDB[$masterName] = $callers;
353 }
354 } );
355
356 if ( count( $callersByDB ) >= 2 ) {
357 $dbs = implode( ', ', array_keys( $callersByDB ) );
358 $msg = "Multi-DB transaction [{$dbs}]:\n";
359 foreach ( $callersByDB as $db => $callers ) {
360 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
361 }
362 $this->queryLogger->info( $msg );
363 }
364 }
365
366 public function hasMasterChanges() {
367 $ret = false;
368 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) {
369 $ret = $ret || $lb->hasMasterChanges();
370 } );
371
372 return $ret;
373 }
374
375 public function laggedReplicaUsed() {
376 $ret = false;
377 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) {
378 $ret = $ret || $lb->laggedReplicaUsed();
379 } );
380
381 return $ret;
382 }
383
384 public function hasOrMadeRecentMasterChanges( $age = null ) {
385 $ret = false;
386 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $age, &$ret ) {
387 $ret = $ret || $lb->hasOrMadeRecentMasterChanges( $age );
388 } );
389 return $ret;
390 }
391
392 public function waitForReplication( array $opts = [] ) {
393 $opts += [
394 'domain' => false,
395 'cluster' => false,
396 'timeout' => $this->cliMode ? 60 : 1,
397 'ifWritesSince' => null
398 ];
399
400 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
401 $opts['domain'] = $opts['wiki']; // b/c
402 }
403
404 // Figure out which clusters need to be checked
405 /** @var ILoadBalancer[] $lbs */
406 $lbs = [];
407 if ( $opts['cluster'] !== false ) {
408 $lbs[] = $this->getExternalLB( $opts['cluster'] );
409 } elseif ( $opts['domain'] !== false ) {
410 $lbs[] = $this->getMainLB( $opts['domain'] );
411 } else {
412 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$lbs ) {
413 $lbs[] = $lb;
414 } );
415 if ( !$lbs ) {
416 return true; // nothing actually used
417 }
418 }
419
420 // Get all the master positions of applicable DBs right now.
421 // This can be faster since waiting on one cluster reduces the
422 // time needed to wait on the next clusters.
423 $masterPositions = array_fill( 0, count( $lbs ), false );
424 foreach ( $lbs as $i => $lb ) {
425 if (
426 // No writes to wait on getting replicated
427 !$lb->hasMasterConnection() ||
428 // No replication; avoid getMasterPos() permissions errors (T29975)
429 !$lb->hasStreamingReplicaServers() ||
430 // No writes since the last replication wait
431 (
432 $opts['ifWritesSince'] &&
433 $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
434 )
435 ) {
436 continue; // no need to wait
437 }
438
439 $masterPositions[$i] = $lb->getMasterPos();
440 }
441
442 // Run any listener callbacks *after* getting the DB positions. The more
443 // time spent in the callbacks, the less time is spent in waitForAll().
444 foreach ( $this->replicationWaitCallbacks as $callback ) {
445 $callback();
446 }
447
448 $failed = [];
449 foreach ( $lbs as $i => $lb ) {
450 if ( $masterPositions[$i] ) {
451 // The RDBMS may not support getMasterPos()
452 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
453 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
454 }
455 }
456 }
457
458 return !$failed;
459 }
460
461 public function setWaitForReplicationListener( $name, callable $callback = null ) {
462 if ( $callback ) {
463 $this->replicationWaitCallbacks[$name] = $callback;
464 } else {
465 unset( $this->replicationWaitCallbacks[$name] );
466 }
467 }
468
469 public function getEmptyTransactionTicket( $fname ) {
470 if ( $this->hasMasterChanges() ) {
471 $this->queryLogger->error(
472 __METHOD__ . ": $fname does not have outer scope",
473 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
474 );
475
476 return null;
477 }
478
479 return $this->ticket;
480 }
481
482 final public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
483 if ( $ticket !== $this->ticket ) {
484 $this->perfLogger->error(
485 __METHOD__ . ": $fname does not have outer scope",
486 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
487 );
488
489 return false;
490 }
491
492 // The transaction owner and any caller with the empty transaction ticket can commit
493 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
494 if ( $this->trxRoundId !== false && $fname !== $this->trxRoundId ) {
495 $this->queryLogger->info( "$fname: committing on behalf of {$this->trxRoundId}" );
496 $fnameEffective = $this->trxRoundId;
497 } else {
498 $fnameEffective = $fname;
499 }
500
501 $this->commitMasterChanges( $fnameEffective );
502 $waitSucceeded = $this->waitForReplication( $opts );
503 // If a nested caller committed on behalf of $fname, start another empty $fname
504 // transaction, leaving the caller with the same empty transaction state as before.
505 if ( $fnameEffective !== $fname ) {
506 $this->beginMasterChanges( $fnameEffective );
507 }
508
509 return $waitSucceeded;
510 }
511
512 public function getChronologyProtectorTouched( $dbName ) {
513 return $this->getChronologyProtector()->getTouched( $dbName );
514 }
515
516 public function disableChronologyProtection() {
517 $this->getChronologyProtector()->setEnabled( false );
518 }
519
520 /**
521 * @return ChronologyProtector
522 */
523 protected function getChronologyProtector() {
524 if ( $this->chronProt ) {
525 return $this->chronProt;
526 }
527
528 $this->chronProt = new ChronologyProtector(
529 $this->memStash,
530 [
531 'ip' => $this->requestInfo['IPAddress'],
532 'agent' => $this->requestInfo['UserAgent'],
533 'clientId' => $this->requestInfo['ChronologyClientId'] ?: null
534 ],
535 $this->requestInfo['ChronologyPositionIndex'],
536 $this->secret
537 );
538 $this->chronProt->setLogger( $this->replLogger );
539
540 if ( $this->cliMode ) {
541 $this->chronProt->setEnabled( false );
542 } elseif ( $this->requestInfo['ChronologyProtection'] === 'false' ) {
543 // Request opted out of using position wait logic. This is useful for requests
544 // done by the job queue or background ETL that do not have a meaningful session.
545 $this->chronProt->setWaitEnabled( false );
546 } elseif ( $this->memStash instanceof EmptyBagOStuff ) {
547 // No where to store any DB positions and wait for them to appear
548 $this->chronProt->setEnabled( false );
549 $this->replLogger->info( 'Cannot use ChronologyProtector with EmptyBagOStuff' );
550 }
551
552 $this->replLogger->debug(
553 __METHOD__ . ': request info ' .
554 json_encode( $this->requestInfo, JSON_PRETTY_PRINT )
555 );
556
557 return $this->chronProt;
558 }
559
560 /**
561 * Get and record all of the staged DB positions into persistent memory storage
562 *
563 * @param ChronologyProtector $cp
564 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
565 * @param string $mode One of (sync, async); whether to wait on remote datacenters
566 * @param int|null &$cpIndex DB position key write counter; incremented on update
567 */
568 protected function shutdownChronologyProtector(
569 ChronologyProtector $cp, $workCallback, $mode, &$cpIndex = null
570 ) {
571 // Record all the master positions needed
572 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $cp ) {
573 $cp->storeSessionReplicationPosition( $lb );
574 } );
575 // Write them to the persistent stash. Try to do something useful by running $work
576 // while ChronologyProtector waits for the stash write to replicate to all DCs.
577 $unsavedPositions = $cp->shutdown( $workCallback, $mode, $cpIndex );
578 if ( $unsavedPositions && $workCallback ) {
579 // Invoke callback in case it did not cache the result yet
580 $workCallback(); // work now to block for less time in waitForAll()
581 }
582 // If the positions failed to write to the stash, at least wait on local datacenter
583 // replica DBs to catch up before responding. Even if there are several DCs, this increases
584 // the chance that the user will see their own changes immediately afterwards. As long
585 // as the sticky DC cookie applies (same domain), this is not even an issue.
586 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $unsavedPositions ) {
587 $masterName = $lb->getServerName( $lb->getWriterIndex() );
588 if ( isset( $unsavedPositions[$masterName] ) ) {
589 $lb->waitForAll( $unsavedPositions[$masterName] );
590 }
591 } );
592 }
593
594 /**
595 * Base parameters to ILoadBalancer::__construct()
596 * @return array
597 */
598 final protected function baseLoadBalancerParams() {
599 if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
600 $initStage = ILoadBalancer::STAGE_POSTCOMMIT_CALLBACKS;
601 } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
602 $initStage = ILoadBalancer::STAGE_POSTROLLBACK_CALLBACKS;
603 } else {
604 $initStage = null;
605 }
606
607 return [
608 'localDomain' => $this->localDomain,
609 'readOnlyReason' => $this->readOnlyReason,
610 'srvCache' => $this->srvCache,
611 'wanCache' => $this->wanCache,
612 'profiler' => $this->profiler,
613 'trxProfiler' => $this->trxProfiler,
614 'queryLogger' => $this->queryLogger,
615 'connLogger' => $this->connLogger,
616 'replLogger' => $this->replLogger,
617 'errorLogger' => $this->errorLogger,
618 'deprecationLogger' => $this->deprecationLogger,
619 'hostname' => $this->hostname,
620 'cliMode' => $this->cliMode,
621 'agent' => $this->agent,
622 'maxLag' => $this->maxLag,
623 'defaultGroup' => $this->defaultGroup,
624 'chronologyCallback' => function ( ILoadBalancer $lb ) {
625 // Defer ChronologyProtector construction in case setRequestInfo() ends up
626 // being called later (but before the first connection attempt) (T192611)
627 $this->getChronologyProtector()->applySessionReplicationPosition( $lb );
628 },
629 'roundStage' => $initStage,
630 'ownerId' => $this->id
631 ];
632 }
633
634 /**
635 * @param ILoadBalancer $lb
636 */
637 protected function initLoadBalancer( ILoadBalancer $lb ) {
638 if ( $this->trxRoundId !== false ) {
639 $lb->beginMasterChanges( $this->trxRoundId, $this->id ); // set DBO_TRX
640 }
641
642 $lb->setTableAliases( $this->tableAliases );
643 $lb->setIndexAliases( $this->indexAliases );
644 }
645
646 public function setTableAliases( array $aliases ) {
647 $this->tableAliases = $aliases;
648 }
649
650 public function setIndexAliases( array $aliases ) {
651 $this->indexAliases = $aliases;
652 }
653
654 /**
655 * @param string $prefix
656 * @deprecated Since 1.33
657 */
658 public function setDomainPrefix( $prefix ) {
659 $this->setLocalDomainPrefix( $prefix );
660 }
661
662 public function setLocalDomainPrefix( $prefix ) {
663 $this->localDomain = new DatabaseDomain(
664 $this->localDomain->getDatabase(),
665 $this->localDomain->getSchema(),
666 $prefix
667 );
668
669 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $prefix ) {
670 $lb->setLocalDomainPrefix( $prefix );
671 } );
672 }
673
674 public function redefineLocalDomain( $domain ) {
675 $this->closeAll();
676
677 $this->localDomain = DatabaseDomain::newFromId( $domain );
678
679 $this->forEachLB( function ( ILoadBalancer $lb ) {
680 $lb->redefineLocalDomain( $this->localDomain );
681 } );
682 }
683
684 public function closeAll() {
685 $this->forEachLBCallMethod( 'closeAll' );
686 }
687
688 public function setAgentName( $agent ) {
689 $this->agent = $agent;
690 }
691
692 public function appendShutdownCPIndexAsQuery( $url, $index ) {
693 $usedCluster = 0;
694 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$usedCluster ) {
695 $usedCluster |= $lb->hasStreamingReplicaServers();
696 } );
697
698 if ( !$usedCluster ) {
699 return $url; // no master/replica clusters touched
700 }
701
702 return strpos( $url, '?' ) === false ? "$url?cpPosIndex=$index" : "$url&cpPosIndex=$index";
703 }
704
705 public function getChronologyProtectorClientId() {
706 return $this->getChronologyProtector()->getClientId();
707 }
708
709 /**
710 * @param int $index Write index
711 * @param int $time UNIX timestamp; can be used to detect stale cookies (T190082)
712 * @param string $clientId Agent ID hash from ILBFactory::shutdown()
713 * @return string Timestamp-qualified write index of the form "<index>@<timestamp>#<hash>"
714 * @since 1.32
715 */
716 public static function makeCookieValueFromCPIndex( $index, $time, $clientId ) {
717 return "$index@$time#$clientId";
718 }
719
720 /**
721 * @param string $value Possible result of LBFactory::makeCookieValueFromCPIndex()
722 * @param int $minTimestamp Lowest UNIX timestamp that a non-expired value can have
723 * @return array (index: int or null, clientId: string or null)
724 * @since 1.32
725 */
726 public static function getCPInfoFromCookieValue( $value, $minTimestamp ) {
727 static $placeholder = [ 'index' => null, 'clientId' => null ];
728
729 if ( !preg_match( '/^(\d+)@(\d+)#([0-9a-f]{32})$/', $value, $m ) ) {
730 return $placeholder; // invalid
731 }
732
733 $index = (int)$m[1];
734 if ( $index <= 0 ) {
735 return $placeholder; // invalid
736 } elseif ( isset( $m[2] ) && $m[2] !== '' && (int)$m[2] < $minTimestamp ) {
737 return $placeholder; // expired
738 }
739
740 $clientId = ( isset( $m[3] ) && $m[3] !== '' ) ? $m[3] : null;
741
742 return [ 'index' => $index, 'clientId' => $clientId ];
743 }
744
745 public function setRequestInfo( array $info ) {
746 if ( $this->chronProt ) {
747 throw new LogicException( 'ChronologyProtector already initialized' );
748 }
749
750 $this->requestInfo = $info + $this->requestInfo;
751 }
752
753 /**
754 * @param string $stage
755 */
756 private function assertTransactionRoundStage( $stage ) {
757 if ( $this->trxRoundStage !== $stage ) {
758 throw new DBTransactionError(
759 null,
760 "Transaction round stage must be '$stage' (not '{$this->trxRoundStage}')"
761 );
762 }
763 }
764
765 function __destruct() {
766 $this->destroy();
767 }
768 }