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