Merge ".mailmap: Correct two contributor names"
[mediawiki.git] / includes / libs / rdbms / lbfactory / LBFactory.php
blobd7f467eeff3784f51805b50975d8120fc237b9a4
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
18 * @file
20 namespace Wikimedia\Rdbms;
22 use Exception;
23 use Generator;
24 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
25 use Psr\Log\LoggerInterface;
26 use Psr\Log\NullLogger;
27 use RuntimeException;
28 use Throwable;
29 use Wikimedia\ObjectCache\BagOStuff;
30 use Wikimedia\ObjectCache\EmptyBagOStuff;
31 use Wikimedia\ObjectCache\WANObjectCache;
32 use Wikimedia\RequestTimeout\CriticalSectionProvider;
33 use Wikimedia\ScopedCallback;
34 use Wikimedia\Stats\NullStatsdDataFactory;
35 use Wikimedia\Telemetry\NoopTracer;
36 use Wikimedia\Telemetry\TracerInterface;
38 /**
39 * @see ILBFactory
40 * @ingroup Database
42 abstract class LBFactory implements ILBFactory {
43 /** @var CriticalSectionProvider|null */
44 private $csProvider;
45 /**
46 * @var callable|null An optional callback that returns a ScopedCallback instance,
47 * meant to profile the actual query execution in {@see Database::doQuery}
49 private $profiler;
50 /** @var TransactionProfiler */
51 private $trxProfiler;
52 /** @var TracerInterface */
53 private $tracer;
54 /** @var StatsdDataFactoryInterface */
55 private $statsd;
56 /** @var LoggerInterface */
57 private $logger;
58 /** @var callable Error logger */
59 private $errorLogger;
60 /** @var callable Deprecation logger */
61 private $deprecationLogger;
63 /** @var ChronologyProtector */
64 protected $chronologyProtector;
65 /** @var BagOStuff */
66 protected $srvCache;
67 /** @var WANObjectCache */
68 protected $wanCache;
69 /** @var DatabaseDomain Local domain */
70 protected $localDomain;
72 /** @var bool Whether this PHP instance is for a CLI script */
73 private $cliMode;
74 /** @var string Agent name for query profiling */
75 private $agent;
77 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
78 private $tableAliases = [];
79 /** @var string[] Map of (index alias => index) */
80 private $indexAliases = [];
81 /** @var DatabaseDomain[]|string[] Map of (domain alias => DB domain) */
82 protected $domainAliases = [];
83 /** @var array[] Map of virtual domain to array of cluster and domain */
84 protected array $virtualDomainsMapping = [];
85 /** @var string[] List of registered virtual domains */
86 protected array $virtualDomains = [];
87 /** @var callable[] */
88 private $replicationWaitCallbacks = [];
90 /** @var int|null Ticket used to delegate transaction ownership */
91 private $ticket;
92 /** @var string|null Active explicit transaction round owner or null if none */
93 private $trxRoundFname = null;
94 /** @var string One of the ROUND_* class constants */
95 private $trxRoundStage = self::ROUND_CURSORY;
96 /** @var int Default replication wait timeout */
97 private $replicationWaitTimeout;
99 /** @var string|false Reason all LBs are read-only or false if not */
100 protected $readOnlyReason = false;
102 /** @var string|null */
103 private $defaultGroup = null;
105 private const ROUND_CURSORY = 'cursory';
106 private const ROUND_BEGINNING = 'within-begin';
107 private const ROUND_COMMITTING = 'within-commit';
108 private const ROUND_ROLLING_BACK = 'within-rollback';
109 private const ROUND_COMMIT_CALLBACKS = 'within-commit-callbacks';
110 private const ROUND_ROLLBACK_CALLBACKS = 'within-rollback-callbacks';
111 private const ROUND_ROLLBACK_SESSIONS = 'within-rollback-session';
114 * @var callable
116 private $configCallback = null;
118 public function __construct( array $conf ) {
119 $this->configure( $conf );
121 if ( isset( $conf['configCallback'] ) ) {
122 $this->configCallback = $conf['configCallback'];
127 * @param array $conf
128 * @return void
130 protected function configure( array $conf ): void {
131 $this->localDomain = isset( $conf['localDomain'] )
132 ? DatabaseDomain::newFromId( $conf['localDomain'] )
133 : DatabaseDomain::newUnspecified();
135 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
136 $this->readOnlyReason = $conf['readOnlyReason'];
139 $this->chronologyProtector = $conf['chronologyProtector'] ?? new ChronologyProtector();
140 $this->srvCache = $conf['srvCache'] ?? new EmptyBagOStuff();
141 $this->wanCache = $conf['wanCache'] ?? WANObjectCache::newEmpty();
143 $this->logger = $conf['logger'] ?? new NullLogger();
144 $this->errorLogger = $conf['errorLogger'] ?? static function ( Throwable $e ) {
145 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
147 $this->deprecationLogger = $conf['deprecationLogger'] ?? static function ( $msg ) {
148 trigger_error( $msg, E_USER_DEPRECATED );
151 $this->profiler = $conf['profiler'] ?? null;
152 $this->trxProfiler = $conf['trxProfiler'] ?? new TransactionProfiler();
153 $this->statsd = $conf['statsdDataFactory'] ?? new NullStatsdDataFactory();
154 $this->tracer = $conf['tracer'] ?? new NoopTracer();
156 $this->csProvider = $conf['criticalSectionProvider'] ?? null;
158 $this->cliMode = $conf['cliMode'] ?? ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' );
159 $this->agent = $conf['agent'] ?? '';
160 $this->defaultGroup = $conf['defaultGroup'] ?? null;
161 $this->replicationWaitTimeout = $this->cliMode ? 60 : 1;
162 $this->virtualDomainsMapping = $conf['virtualDomainsMapping'] ?? [];
163 $this->virtualDomains = $conf['virtualDomains'] ?? [];
165 static $nextTicket;
166 $this->ticket = $nextTicket = ( is_int( $nextTicket ) ? $nextTicket++ : mt_rand() );
169 public function destroy() {
170 /** @noinspection PhpUnusedLocalVariableInspection */
171 $scope = ScopedCallback::newScopedIgnoreUserAbort();
173 foreach ( $this->getLBsForOwner() as $lb ) {
174 $lb->disable( __METHOD__ );
179 * Reload config using the callback passed defined $config['configCallback'].
181 * If the config returned by the callback is different from the existing config,
182 * this calls reconfigure() on all load balancers, which causes them to invalidate
183 * any existing connections and re-connect using the new configuration.
185 * Long-running processes should call this from time to time
186 * (but not too often, because it is somewhat expensive),
187 * preferably after each batch.
188 * Maintenance scripts can do that by calling $this->waitForReplication(),
189 * which calls this method.
191 public function autoReconfigure(): void {
192 if ( !$this->configCallback ) {
193 return;
196 $conf = ( $this->configCallback )();
197 if ( $conf ) {
198 $this->reconfigure( $conf );
203 * Reconfigure using the given config array.
204 * Any fields omitted from $conf will be taken from the current config.
206 * If the config changed, this calls reconfigure() on all load balancers,
207 * which causes them to close all existing connections.
209 * @note This invalidates the current transaction ticket.
211 * @warning This must only be called in top level code such as the execute()
212 * method of a maintenance script. Any database connection in use when this
213 * method is called will become defunct.
215 * @since 1.39
217 * @param array $conf A configuration array, using the same structure as
218 * the one passed to the constructor (see also $wgLBFactoryConf).
220 public function reconfigure( array $conf ): void {
221 if ( !$conf ) {
222 return;
225 foreach ( $this->getLBsForOwner() as $lb ) {
226 $lb->reconfigure( $conf );
230 public function getLocalDomainID(): string {
231 return $this->localDomain->getId();
234 public function shutdown(
235 $flags = self::SHUTDOWN_NORMAL,
236 ?callable $workCallback = null,
237 &$cpIndex = null,
238 &$cpClientId = null
240 /** @noinspection PhpUnusedLocalVariableInspection */
241 $scope = ScopedCallback::newScopedIgnoreUserAbort();
243 if ( ( $flags & self::SHUTDOWN_NO_CHRONPROT ) != self::SHUTDOWN_NO_CHRONPROT ) {
244 // Remark all of the relevant DB primary positions
245 foreach ( $this->getLBsForOwner() as $lb ) {
246 if ( $lb->hasPrimaryConnection() ) {
247 $this->chronologyProtector->stageSessionPrimaryPos( $lb );
250 // Write the positions to the persistent stash
251 $this->chronologyProtector->persistSessionReplicationPositions( $cpIndex );
252 $this->logger->debug( __METHOD__ . ': finished ChronologyProtector shutdown' );
254 $cpClientId = $this->chronologyProtector->getClientId();
256 $this->commitPrimaryChanges( __METHOD__ );
258 $this->logger->debug( 'LBFactory shutdown completed' );
261 public function getAllLBs() {
262 foreach ( $this->getLBsForOwner() as $lb ) {
263 yield $lb;
268 * Get all tracked load balancers with the internal "for owner" interface.
270 * @return Generator|ILoadBalancerForOwner[]
272 abstract protected function getLBsForOwner();
274 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
275 if ( $this->trxRoundFname !== null && $this->trxRoundFname !== $fname ) {
276 $this->logger->warning(
277 "$fname: transaction round '{$this->trxRoundFname}' still running",
278 [ 'exception' => new RuntimeException() ]
281 foreach ( $this->getLBsForOwner() as $lb ) {
282 $lb->flushReplicaSnapshots( $fname );
286 final public function beginPrimaryChanges( $fname = __METHOD__ ) {
287 $this->assertTransactionRoundStage( self::ROUND_CURSORY );
288 /** @noinspection PhpUnusedLocalVariableInspection */
289 $scope = ScopedCallback::newScopedIgnoreUserAbort();
291 foreach ( $this->getLBsForOwner() as $lb ) {
292 $lb->flushReplicaSnapshots( $fname );
295 $this->trxRoundStage = self::ROUND_BEGINNING;
296 if ( $this->trxRoundFname !== null ) {
297 throw new DBTransactionError(
298 null,
299 "$fname: transaction round '{$this->trxRoundFname}' already started"
302 $this->trxRoundFname = $fname;
303 // Flush snapshots and appropriately set DBO_TRX on primary connections
304 foreach ( $this->getLBsForOwner() as $lb ) {
305 $lb->beginPrimaryChanges( $fname );
307 $this->trxRoundStage = self::ROUND_CURSORY;
310 final public function commitPrimaryChanges( $fname = __METHOD__, int $maxWriteDuration = 0 ) {
311 $this->assertTransactionRoundStage( self::ROUND_CURSORY );
312 /** @noinspection PhpUnusedLocalVariableInspection */
313 $scope = ScopedCallback::newScopedIgnoreUserAbort();
315 $this->trxRoundStage = self::ROUND_COMMITTING;
316 if ( $this->trxRoundFname !== null && $this->trxRoundFname !== $fname ) {
317 throw new DBTransactionError(
318 null,
319 "$fname: transaction round '{$this->trxRoundFname}' still running"
322 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
323 do {
324 $count = 0; // number of callbacks executed this iteration
325 foreach ( $this->getLBsForOwner() as $lb ) {
326 $count += $lb->finalizePrimaryChanges( $fname );
328 } while ( $count > 0 );
329 $this->trxRoundFname = null;
330 // Perform pre-commit checks, aborting on failure
331 foreach ( $this->getLBsForOwner() as $lb ) {
332 $lb->approvePrimaryChanges( $maxWriteDuration, $fname );
334 // Log the DBs and methods involved in multi-DB transactions
335 $this->logIfMultiDbTransaction();
336 // Actually perform the commit on all primary DB connections and revert DBO_TRX
337 foreach ( $this->getLBsForOwner() as $lb ) {
338 $lb->commitPrimaryChanges( $fname );
340 // Run all post-commit callbacks in a separate step
341 $this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS;
342 $e = $this->executePostTransactionCallbacks();
343 $this->trxRoundStage = self::ROUND_CURSORY;
344 // Throw any last post-commit callback error
345 if ( $e instanceof Exception ) {
346 throw $e;
349 foreach ( $this->getLBsForOwner() as $lb ) {
350 $lb->flushReplicaSnapshots( $fname );
354 final public function rollbackPrimaryChanges( $fname = __METHOD__ ) {
355 /** @noinspection PhpUnusedLocalVariableInspection */
356 $scope = ScopedCallback::newScopedIgnoreUserAbort();
358 $this->trxRoundStage = self::ROUND_ROLLING_BACK;
359 $this->trxRoundFname = null;
360 // Actually perform the rollback on all primary DB connections and revert DBO_TRX
361 foreach ( $this->getLBsForOwner() as $lb ) {
362 $lb->rollbackPrimaryChanges( $fname );
364 // Run all post-commit callbacks in a separate step
365 $this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS;
366 $this->executePostTransactionCallbacks();
367 $this->trxRoundStage = self::ROUND_CURSORY;
369 foreach ( $this->getLBsForOwner() as $lb ) {
370 $lb->flushReplicaSnapshots( $fname );
374 final public function flushPrimarySessions( $fname = __METHOD__ ) {
375 /** @noinspection PhpUnusedLocalVariableInspection */
376 $scope = ScopedCallback::newScopedIgnoreUserAbort();
378 // Release named locks and table locks on all primary DB connections
379 $this->trxRoundStage = self::ROUND_ROLLBACK_SESSIONS;
380 foreach ( $this->getLBsForOwner() as $lb ) {
381 $lb->flushPrimarySessions( $fname );
383 $this->trxRoundStage = self::ROUND_CURSORY;
387 * @return Exception|null
389 private function executePostTransactionCallbacks() {
390 $fname = __METHOD__;
391 // Run all post-commit callbacks until new ones stop getting added
392 $e = null; // first callback exception
393 do {
394 foreach ( $this->getLBsForOwner() as $lb ) {
395 $ex = $lb->runPrimaryTransactionIdleCallbacks( $fname );
396 $e = $e ?: $ex;
398 } while ( $this->hasPrimaryChanges() );
399 // Run all listener callbacks once
400 foreach ( $this->getLBsForOwner() as $lb ) {
401 $ex = $lb->runPrimaryTransactionListenerCallbacks( $fname );
402 $e = $e ?: $ex;
405 return $e;
408 public function hasTransactionRound() {
409 // TODO: check for implicit rounds or rename and check for implicit rounds with writes?
410 return ( $this->trxRoundFname !== null );
413 public function isReadyForRoundOperations() {
414 return ( $this->trxRoundStage === self::ROUND_CURSORY );
418 * Log query info if multi DB transactions are going to be committed now
420 private function logIfMultiDbTransaction() {
421 $callersByDB = [];
422 foreach ( $this->getLBsForOwner() as $lb ) {
423 $primaryName = $lb->getServerName( ServerInfo::WRITER_INDEX );
424 $callers = $lb->pendingPrimaryChangeCallers();
425 if ( $callers ) {
426 $callersByDB[$primaryName] = $callers;
430 if ( count( $callersByDB ) >= 2 ) {
431 $dbs = implode( ', ', array_keys( $callersByDB ) );
432 $msg = "Multi-DB transaction [{$dbs}]:\n";
433 foreach ( $callersByDB as $db => $callers ) {
434 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
436 $this->logger->info( $msg );
440 public function hasPrimaryChanges() {
441 foreach ( $this->getLBsForOwner() as $lb ) {
442 if ( $lb->hasPrimaryChanges() ) {
443 return true;
446 return false;
449 public function laggedReplicaUsed() {
450 foreach ( $this->getLBsForOwner() as $lb ) {
451 if ( $lb->laggedReplicaUsed() ) {
452 return true;
455 return false;
458 public function hasOrMadeRecentPrimaryChanges( $age = null ) {
459 foreach ( $this->getLBsForOwner() as $lb ) {
460 if ( $lb->hasOrMadeRecentPrimaryChanges( $age ) ) {
461 return true;
464 return false;
467 public function waitForReplication( array $opts = [] ) {
468 $opts += [
469 'timeout' => $this->replicationWaitTimeout,
470 'ifWritesSince' => null
473 $lbs = [];
474 foreach ( $this->getLBsForOwner() as $lb ) {
475 $lbs[] = $lb;
478 // Get all the primary DB positions of applicable DBs right now.
479 // This can be faster since waiting on one cluster reduces the
480 // time needed to wait on the next clusters.
481 $primaryPositions = array_fill( 0, count( $lbs ), false );
482 foreach ( $lbs as $i => $lb ) {
483 if (
484 // No writes to wait on getting replicated
485 !$lb->hasPrimaryConnection() ||
486 // No replication; avoid getPrimaryPos() permissions errors (T29975)
487 !$lb->hasStreamingReplicaServers() ||
488 // No writes since the last replication wait
490 $opts['ifWritesSince'] &&
491 $lb->lastPrimaryChangeTimestamp() < $opts['ifWritesSince']
494 continue; // no need to wait
497 $primaryPositions[$i] = $lb->getPrimaryPos();
500 // Run any listener callbacks *after* getting the DB positions. The more
501 // time spent in the callbacks, the less time is spent in waitForAll().
502 foreach ( $this->replicationWaitCallbacks as $callback ) {
503 $callback();
506 $failed = [];
507 foreach ( $lbs as $i => $lb ) {
508 if ( $primaryPositions[$i] ) {
509 // The RDBMS may not support getPrimaryPos()
510 if ( !$lb->waitForAll( $primaryPositions[$i], $opts['timeout'] ) ) {
511 $failed[] = $lb->getServerName( ServerInfo::WRITER_INDEX );
516 return !$failed;
519 public function setWaitForReplicationListener( $name, ?callable $callback = null ) {
520 if ( $callback ) {
521 $this->replicationWaitCallbacks[$name] = $callback;
522 } else {
523 unset( $this->replicationWaitCallbacks[$name] );
527 public function getEmptyTransactionTicket( $fname ) {
528 if ( $this->hasPrimaryChanges() ) {
529 $this->logger->error(
530 __METHOD__ . ": $fname does not have outer scope",
531 [ 'exception' => new RuntimeException() ]
534 return null;
537 return $this->ticket;
540 public function getPrimaryDatabase( $domain = false ): IDatabase {
541 return $this->getMappedDatabase( DB_PRIMARY, [], $domain );
544 public function getAutoCommitPrimaryConnection( $domain = false ): IDatabase {
545 return $this->getLoadBalancer( $domain )
546 ->getConnection( DB_PRIMARY, [], $this->getMappedDomain( $domain ), ILoadBalancer::CONN_TRX_AUTOCOMMIT );
549 public function getReplicaDatabase( $domain = false, $group = null ): IReadableDatabase {
550 if ( $group === null ) {
551 $groups = [];
552 } else {
553 $groups = [ $group ];
555 return $this->getMappedDatabase( DB_REPLICA, $groups, $domain );
558 public function getLoadBalancer( $domain = false ): ILoadBalancer {
559 if ( $domain !== false && in_array( $domain, $this->virtualDomains ) ) {
560 if ( isset( $this->virtualDomainsMapping[$domain] ) ) {
561 $config = $this->virtualDomainsMapping[$domain];
562 if ( isset( $config['cluster'] ) ) {
563 return $this->getExternalLB( $config['cluster'] );
565 $domain = $config['db'];
566 } else {
567 // It's not configured, assume local db.
568 $domain = false;
571 return $this->getMainLB( $domain );
575 * Helper for getPrimaryDatabase and getReplicaDatabase() providing virtual
576 * domain mapping.
578 * @param int $index
579 * @param array $groups
580 * @param string|false $domain
581 * @return IDatabase
583 private function getMappedDatabase( $index, $groups, $domain ) {
584 return $this->getLoadBalancer( $domain )
585 ->getConnection( $index, $groups, $this->getMappedDomain( $domain ) );
589 * @internal For installer and getMappedDatabase
590 * @param string|false $domain
591 * @return string|false
593 public function getMappedDomain( $domain ) {
594 if ( $domain !== false && in_array( $domain, $this->virtualDomains ) ) {
595 return $this->virtualDomainsMapping[$domain]['db'] ?? false;
596 } else {
597 return $domain;
602 * Determine whether, after mapping, the domain refers to the main domain
603 * of the local wiki.
605 * @internal for installer
606 * @param string|false $domain
607 * @return bool
609 public function isLocalDomain( $domain ) {
610 if ( $domain !== false && in_array( $domain, $this->virtualDomains ) ) {
611 if ( isset( $this->virtualDomainsMapping[$domain] ) ) {
612 $config = $this->virtualDomainsMapping[$domain];
613 if ( isset( $config['cluster'] ) ) {
614 // In an external cluster
615 return false;
617 $domain = $config['db'];
618 } else {
619 // Unconfigured virtual domain is always local
620 return true;
623 return $domain === false || $domain === $this->getLocalDomainID();
627 * Is the domain a virtual domain with a statically configured database name?
629 * @internal for installer
630 * @param string|false $domain
631 * @return bool
633 public function isSharedVirtualDomain( $domain ) {
634 if ( $domain !== false
635 && in_array( $domain, $this->virtualDomains )
636 && isset( $this->virtualDomainsMapping[$domain] )
638 return $this->virtualDomainsMapping[$domain]['db'] !== false;
640 return false;
643 final public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
644 if ( $ticket !== $this->ticket ) {
645 $this->logger->error(
646 __METHOD__ . ": $fname does not have outer scope ($ticket vs {$this->ticket})",
647 [ 'exception' => new RuntimeException() ]
650 return false;
653 // The transaction owner and any caller with the empty transaction ticket can commit
654 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
655 if ( $this->trxRoundFname !== null && $fname !== $this->trxRoundFname ) {
656 $this->logger->info( "$fname: committing on behalf of {$this->trxRoundFname}" );
657 $fnameEffective = $this->trxRoundFname;
658 } else {
659 $fnameEffective = $fname;
662 $this->commitPrimaryChanges( $fnameEffective );
663 $waitSucceeded = $this->waitForReplication( $opts );
664 // If a nested caller committed on behalf of $fname, start another empty $fname
665 // transaction, leaving the caller with the same empty transaction state as before.
666 if ( $fnameEffective !== $fname ) {
667 $this->beginPrimaryChanges( $fnameEffective );
670 return $waitSucceeded;
673 public function disableChronologyProtection() {
674 $this->chronologyProtector->setEnabled( false );
678 * Get parameters to ILoadBalancer::__construct()
680 * @return array
682 final protected function baseLoadBalancerParams() {
683 if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
684 $initStage = ILoadBalancerForOwner::STAGE_POSTCOMMIT_CALLBACKS;
685 } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
686 $initStage = ILoadBalancerForOwner::STAGE_POSTROLLBACK_CALLBACKS;
687 } else {
688 $initStage = null;
691 return [
692 'localDomain' => $this->localDomain,
693 'readOnlyReason' => $this->readOnlyReason,
694 'srvCache' => $this->srvCache,
695 'wanCache' => $this->wanCache,
696 'profiler' => $this->profiler,
697 'trxProfiler' => $this->trxProfiler,
698 'tracer' => $this->tracer,
699 'logger' => $this->logger,
700 'errorLogger' => $this->errorLogger,
701 'deprecationLogger' => $this->deprecationLogger,
702 'statsdDataFactory' => $this->statsd,
703 'cliMode' => $this->cliMode,
704 'agent' => $this->agent,
705 'defaultGroup' => $this->defaultGroup,
706 'chronologyProtector' => $this->chronologyProtector,
707 'roundStage' => $initStage,
708 'criticalSectionProvider' => $this->csProvider
713 * @param ILoadBalancerForOwner $lb
715 protected function initLoadBalancer( ILoadBalancerForOwner $lb ) {
716 if ( $this->trxRoundFname !== null ) {
717 $lb->beginPrimaryChanges( $this->trxRoundFname ); // set DBO_TRX
720 $lb->setTableAliases( $this->tableAliases );
721 $lb->setIndexAliases( $this->indexAliases );
722 $lb->setDomainAliases( $this->domainAliases );
725 public function setTableAliases( array $aliases ) {
726 $this->tableAliases = $aliases;
729 public function setIndexAliases( array $aliases ) {
730 $this->indexAliases = $aliases;
733 public function setDomainAliases( array $aliases ) {
734 $this->domainAliases = $aliases;
737 public function getTransactionProfiler(): TransactionProfiler {
738 return $this->trxProfiler;
741 public function setLocalDomainPrefix( $prefix ) {
742 $this->localDomain = new DatabaseDomain(
743 $this->localDomain->getDatabase(),
744 $this->localDomain->getSchema(),
745 $prefix
748 foreach ( $this->getLBsForOwner() as $lb ) {
749 $lb->setLocalDomainPrefix( $prefix );
753 public function redefineLocalDomain( $domain ) {
754 $this->closeAll( __METHOD__ );
756 $this->localDomain = DatabaseDomain::newFromId( $domain );
758 foreach ( $this->getLBsForOwner() as $lb ) {
759 $lb->redefineLocalDomain( $this->localDomain );
763 public function closeAll( $fname = __METHOD__ ) {
764 /** @noinspection PhpUnusedLocalVariableInspection */
765 $scope = ScopedCallback::newScopedIgnoreUserAbort();
767 foreach ( $this->getLBsForOwner() as $lb ) {
768 $lb->closeAll( $fname );
772 public function setAgentName( $agent ) {
773 $this->agent = $agent;
776 public function hasStreamingReplicaServers() {
777 foreach ( $this->getLBsForOwner() as $lb ) {
778 if ( $lb->hasStreamingReplicaServers() ) {
779 return true;
782 return false;
785 public function setDefaultReplicationWaitTimeout( $seconds ) {
786 $old = $this->replicationWaitTimeout;
787 $this->replicationWaitTimeout = max( 1, (int)$seconds );
789 return $old;
793 * @param string $stage
795 private function assertTransactionRoundStage( $stage ) {
796 if ( $this->trxRoundStage !== $stage ) {
797 throw new DBTransactionError(
798 null,
799 "Transaction round stage must be '$stage' (not '{$this->trxRoundStage}')"