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