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