Debian Codegraph @

includes/libs/rdbms/loadbalancer/LoadBalancer.php

raw symbols SCIP
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20 namespace Wikimedia\Rdbms;
21
22 use ArrayUtils;
23 use InvalidArgumentException;
24 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
25 use LogicException;
26 use Psr\Log\LoggerInterface;
27 use Psr\Log\NullLogger;
28 use RuntimeException;
29 use Throwable;
30 use UnexpectedValueException;
31 use Wikimedia\ObjectCache\BagOStuff;
32 use Wikimedia\ObjectCache\EmptyBagOStuff;
33 use Wikimedia\ObjectCache\WANObjectCache;
34 use Wikimedia\ScopedCallback;
35 use Wikimedia\Stats\NullStatsdDataFactory;
36
37 /**
38 * @see ILoadBalancer
39 * @ingroup Database
40 */
41 class LoadBalancer implements ILoadBalancerForOwner {
42 /** @var ILoadMonitor */
43 private $loadMonitor;
44 /** @var BagOStuff */
45 private $srvCache;
46 /** @var WANObjectCache */
47 private $wanCache;
48 /** @var DatabaseFactory */
49 private $databaseFactory;
50
51 /** @var TransactionProfiler */
52 private $trxProfiler;
53 /** @var StatsdDataFactoryInterface */
54 private $statsd;
55 /** @var LoggerInterface */
56 private $logger;
57 /** @var callable Exception logger */
58 private $errorLogger;
59 /** @var DatabaseDomain Local DB domain ID and default for new connections */
60 private $localDomain;
61
62 /** @var array<string,array<int,Database[]>> Map of (connection pool => server index => Database[]) */
63 private $conns;
64
65 /** @var string The name of the DB cluster */
66 private $clusterName;
67 /** @var ServerInfo */
68 private $serverInfo;
69 /** @var array<string,array<int,int|float>> Map of (group => server index => weight) */
70 private $groupLoads;
71 /** @var string|null Default query group to use with getConnection() */
72 private $defaultGroup;
73
74 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
75 private $tableAliases = [];
76 /** @var string[] Map of (index alias => index) */
77 private $indexAliases = [];
78 /** @var DatabaseDomain[]|string[] Map of (domain alias => DB domain) */
79 private $domainAliases = [];
80 /** @var callable[] Map of (name => callable) */
81 private $trxRecurringCallbacks = [];
82 /** @var bool[] Map of (domain => whether to use "temp tables only" mode) */
83 private $tempTablesOnlyMode = [];
84
85 /** @var string|false Explicit DBO_TRX transaction round active or false if none */
86 private $trxRoundId = false;
87 /** @var string Stage of the current transaction round in the transaction round life-cycle */
88 private $trxRoundStage = self::ROUND_CURSORY;
89 /** @var int[] The group replica server indexes keyed by group */
90 private $readIndexByGroup = [];
91 /** @var DBPrimaryPos|null Replication sync position or false if not set */
92 private $waitForPos;
93 /** @var bool Whether a lagged replica DB was used */
94 private $laggedReplicaMode = false;
95 /** @var string|false Reason this instance is read-only or false if not */
96 private $readOnlyReason = false;
97 /** @var int Total number of new connections ever made with this instance */
98 private $connectionCounter = 0;
99 /** @var bool */
100 private $disabled = false;
101 private ?ChronologyProtector $chronologyProtector = null;
102 /** @var bool Whether the session consistency callback already executed */
103 private $chronologyProtectorCalled = false;
104
105 /** @var Database|null The last connection handle that caused a problem */
106 private $lastErrorConn;
107
108 /** @var DatabaseDomain[] Map of (domain ID => domain instance) */
109 private $nonLocalDomainCache = [];
110
111 /**
112 * @var int Modification counter for invalidating connections held by
113 * DBConnRef instances. This is bumped by reconfigure().
114 */
115 private $modcount = 0;
116
117 /** The "server index" LB info key; see {@link IDatabase::getLBInfo()} */
118 private const INFO_SERVER_INDEX = 'serverIndex';
119 /** The "connection category" LB info key; see {@link IDatabase::getLBInfo()} */
120 private const INFO_CONN_CATEGORY = 'connCategory';
121
122 /** Warn when this many connection are held */
123 private const CONN_HELD_WARN_THRESHOLD = 10;
124
125 /** Default 'waitTimeout' when unspecified */
126 private const MAX_WAIT_DEFAULT = 10;
127 /** Seconds to cache primary DB server read-only status */
128 private const TTL_CACHE_READONLY = 5;
129
130 /** A category of connections that are tracked and transaction round aware */
131 private const CATEGORY_ROUND = 'round';
132 /** A category of connections that are tracked and in autocommit-mode */
133 private const CATEGORY_AUTOCOMMIT = 'auto-commit';
134 /** A category of connections that are untracked and in gauge-mode */
135 private const CATEGORY_GAUGE = 'gauge';
136
137 /** Transaction round, explicit or implicit, has not finished writing */
138 private const ROUND_CURSORY = 'cursory';
139 /** Transaction round writes are complete and ready for pre-commit checks */
140 private const ROUND_FINALIZED = 'finalized';
141 /** Transaction round passed final pre-commit checks */
142 private const ROUND_APPROVED = 'approved';
143 /** Transaction round was committed and post-commit callbacks must be run */
144 private const ROUND_COMMIT_CALLBACKS = 'commit-callbacks';
145 /** Transaction round was rolled back and post-rollback callbacks must be run */
146 private const ROUND_ROLLBACK_CALLBACKS = 'rollback-callbacks';
147 /** Transaction round encountered an error */
148 private const ROUND_ERROR = 'error';
149
150 /** @var int Idiom for getExistingReaderIndex() meaning "no index selected" */
151 private const READER_INDEX_NONE = -1;
152
153 public function __construct( array $params ) {
154 $this->configure( $params );
155
156 $this->conns = self::newTrackedConnectionsArray();
157 }
158
159 /**
160 * @param array $params A database configuration array, see $wgLBFactoryConf.
161 *
162 * @return void
163 */
164 protected function configure( array $params ): void {
165 $this->localDomain = isset( $params['localDomain'] )
166 ? DatabaseDomain::newFromId( $params['localDomain'] )
167 : DatabaseDomain::newUnspecified();
168
169 $this->serverInfo = new ServerInfo();
170 $this->groupLoads = [ self::GROUP_GENERIC => [] ];
171 foreach ( $this->serverInfo->normalizeServerMaps( $params['servers'] ?? [] ) as $i => $server ) {
172 $this->serverInfo->addServer( $i, $server );
173 foreach ( $server['groupLoads'] as $group => $weight ) {
174 $this->groupLoads[$group][$i] = $weight;
175 }
176 $this->groupLoads[self::GROUP_GENERIC][$i] = $server['load'];
177 }
178 // If the cluster name is not specified, fallback to the current primary name
179 $this->clusterName = $params['clusterName']
180 ?? $this->serverInfo->getServerName( ServerInfo::WRITER_INDEX );
181
182 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
183 $this->readOnlyReason = $params['readOnlyReason'];
184 }
185
186 $this->srvCache = $params['srvCache'] ?? new EmptyBagOStuff();
187 $this->wanCache = $params['wanCache'] ?? WANObjectCache::newEmpty();
188
189 // Note: this parameter is normally absent. It is injectable for testing purposes only.
190 $this->databaseFactory = $params['databaseFactory'] ?? new DatabaseFactory( $params );
191
192 $this->errorLogger = $params['errorLogger'] ?? static function ( Throwable $e ) {
193 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
194 };
195 $this->logger = $params['logger'] ?? new NullLogger();
196
197 $this->trxProfiler = $params['trxProfiler'] ?? new TransactionProfiler();
198 $this->statsd = $params['statsdDataFactory'] ?? new NullStatsdDataFactory();
199
200 // Set up LoadMonitor
201 $loadMonitorConfig = $params['loadMonitor'] ?? [ 'class' => LoadMonitorNull::class ];
202 $compat = [
203 'LoadMonitor' => LoadMonitor::class,
204 'LoadMonitorNull' => LoadMonitorNull::class
205 ];
206 $class = $loadMonitorConfig['class'];
207 // @phan-suppress-next-line PhanImpossibleCondition
208 if ( isset( $compat[$class] ) ) {
209 $class = $compat[$class];
210 }
211 $this->loadMonitor = new $class(
212 $this, $this->srvCache, $this->wanCache, $loadMonitorConfig );
213 $this->loadMonitor->setLogger( $this->logger );
214 $this->loadMonitor->setStatsdDataFactory( $this->statsd );
215
216 if ( isset( $params['chronologyProtector'] ) ) {
217 $this->chronologyProtector = $params['chronologyProtector'];
218 }
219
220 if ( isset( $params['roundStage'] ) ) {
221 if ( $params['roundStage'] === self::STAGE_POSTCOMMIT_CALLBACKS ) {
222 $this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS;
223 } elseif ( $params['roundStage'] === self::STAGE_POSTROLLBACK_CALLBACKS ) {
224 $this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS;
225 }
226 }
227
228 $group = $params['defaultGroup'] ?? self::GROUP_GENERIC;
229 $this->defaultGroup = isset( $this->groupLoads[ $group ] ) ? $group : self::GROUP_GENERIC;
230 }
231
232 private static function newTrackedConnectionsArray() {
233 // Note that CATEGORY_GAUGE connections are untracked
234 return [
235 self::CATEGORY_ROUND => [],
236 self::CATEGORY_AUTOCOMMIT => []
237 ];
238 }
239
240 public function getClusterName(): string {
241 return $this->clusterName;
242 }
243
244 public function getLocalDomainID(): string {
245 return $this->localDomain->getId();
246 }
247
248 public function resolveDomainID( $domain ): string {
249 return $this->resolveDomainInstance( $domain )->getId();
250 }
251
252 /**
253 * @param DatabaseDomain|string|false $domain
254 * @return DatabaseDomain
255 */
256 final protected function resolveDomainInstance( $domain ): DatabaseDomain {
257 if ( $domain instanceof DatabaseDomain ) {
258 return $domain; // already a domain instance
259 } elseif ( $domain === false || $domain === $this->localDomain->getId() ) {
260 return $this->localDomain;
261 } elseif ( isset( $this->domainAliases[$domain] ) ) {
262 $this->domainAliases[$domain] =
263 DatabaseDomain::newFromId( $this->domainAliases[$domain] );
264
265 return $this->domainAliases[$domain];
266 }
267
268 $cachedDomain = $this->nonLocalDomainCache[$domain] ?? null;
269 if ( $cachedDomain === null ) {
270 $cachedDomain = DatabaseDomain::newFromId( $domain );
271 $this->nonLocalDomainCache = [ $domain => $cachedDomain ];
272 }
273
274 return $cachedDomain;
275 }
276
277 /**
278 * Get the first group in $groups with assigned servers, falling back to the default group
279 *
280 * @param string[]|string|false $groups Query group(s) in preference order, [], or false
281 * @param int $i Specific server index or DB_PRIMARY/DB_REPLICA
282 * @return string Query group
283 */
284 private function resolveGroups( $groups, $i ) {
285 // If a specific replica server was specified, then $groups makes no sense
286 if ( $i > 0 && $groups !== [] && $groups !== false ) {
287 $list = implode( ', ', (array)$groups );
288 throw new LogicException( "Query group(s) ($list) given with server index (#$i)" );
289 }
290
291 if ( $groups === [] || $groups === false || $groups === $this->defaultGroup ) {
292 $resolvedGroup = $this->defaultGroup;
293 } elseif ( is_string( $groups ) ) {
294 $resolvedGroup = isset( $this->groupLoads[$groups] ) ? $groups : $this->defaultGroup;
295 } elseif ( is_array( $groups ) ) {
296 $resolvedGroup = $this->defaultGroup;
297 foreach ( $groups as $group ) {
298 if ( isset( $this->groupLoads[$group] ) ) {
299 $resolvedGroup = $group;
300 break;
301 }
302 }
303 } else {
304 $resolvedGroup = $this->defaultGroup;
305 }
306
307 return $resolvedGroup;
308 }
309
310 /**
311 * Sanitize connection flags provided by a call to getConnection()
312 *
313 * @param int $flags Bitfield of class CONN_* constants
314 * @param string $domain Database domain
315 * @return int Sanitized bitfield
316 */
317 protected function sanitizeConnectionFlags( $flags, $domain ) {
318 if ( self::fieldHasBit( $flags, self::CONN_TRX_AUTOCOMMIT ) ) {
319 // Callers use CONN_TRX_AUTOCOMMIT to bypass REPEATABLE-READ staleness without
320 // resorting to row locks (e.g. FOR UPDATE) or to make small out-of-band commits
321 // during larger transactions. This is useful for avoiding lock contention.
322 // Assuming all servers are of the same type (or similar), which is overwhelmingly
323 // the case, use the primary server information to get the attributes. The information
324 // for $i cannot be used since it might be DB_REPLICA, which might require connection
325 // attempts in order to be resolved into a real server index.
326 $attributes = $this->getServerAttributes( ServerInfo::WRITER_INDEX );
327 if ( $attributes[Database::ATTR_DB_LEVEL_LOCKING] ) {
328 // The RDBMS does not support concurrent writes (e.g. SQLite), so attempts
329 // to use separate connections would just cause self-deadlocks. Note that
330 // REPEATABLE-READ staleness is not an issue since DB-level locking means
331 // that transactions are Strict Serializable anyway.
332 $flags &= ~self::CONN_TRX_AUTOCOMMIT;
333 $type = $this->serverInfo->getServerType( ServerInfo::WRITER_INDEX );
334 $this->logger->info( __METHOD__ . ": CONN_TRX_AUTOCOMMIT disallowed ($type)" );
335 } elseif ( isset( $this->tempTablesOnlyMode[$domain] ) ) {
336 // T202116: integration tests are active and queries should be all be using
337 // temporary clone tables (via prefix). Such tables are not visible across
338 // different connections nor can there be REPEATABLE-READ snapshot staleness,
339 // so use the same connection for everything.
340 $flags &= ~self::CONN_TRX_AUTOCOMMIT;
341 }
342 }
343
344 return $flags;
345 }
346
347 /**
348 * @param IDatabase $conn
349 * @param int $flags
350 * @throws DBUnexpectedError
351 */
352 private function enforceConnectionFlags( IDatabase $conn, $flags ) {
353 if (
354 self::fieldHasBit( $flags, self::CONN_TRX_AUTOCOMMIT ) ||
355 // Handles with open transactions are avoided since they might be subject
356 // to REPEATABLE-READ snapshots, which could affect the lag estimate query.
357 self::fieldHasBit( $flags, self::CONN_UNTRACKED_GAUGE )
358 ) {
359 if ( $conn->trxLevel() ) {
360 throw new DBUnexpectedError(
361 $conn,
362 'Handle requested with autocommit-mode yet it has a transaction'
363 );
364 }
365
366 $conn->clearFlag( $conn::DBO_TRX ); // auto-commit mode
367 }
368 }
369
370 /**
371 * @param array<int,int|float> $loads Map of (server index => weight) for a load group
372 * @param int|float $sessionLagLimit Additional maximum lag threshold imposed by the session;
373 * use INF if none applies. Servers will count as lagged if their lag exceeds either this
374 * value or the configured "max lag" value.
375 * @return int|false Index of a non-lagged server with non-zero weight; false if none
376 */
377 private function getRandomNonLagged( array $loads, $sessionLagLimit = INF ) {
378 $lags = $this->getLagTimes();
379
380 // Unset excessively lagged servers from the load group
381 foreach ( $lags as $i => $lag ) {
382 if ( $i !== ServerInfo::WRITER_INDEX ) {
383 // How much lag normally counts as "excessive" for this server
384 $maxServerLag = $this->serverInfo->getServerMaxLag( $i );
385 // How much lag counts as "excessive" for this server given the session
386 $maxServerLag = min( $maxServerLag, $sessionLagLimit );
387
388 $srvName = $this->serverInfo->getServerName( $i );
389 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
390 $this->logger->debug(
391 __METHOD__ . ": server {db_server} is not replicating?",
392 [ 'db_server' => $srvName ]
393 );
394 unset( $loads[$i] );
395 } elseif ( $lag > $maxServerLag ) {
396 $this->logger->debug(
397 __METHOD__ .
398 ": server {db_server} has {lag} seconds of lag (>= {maxlag})",
399 [ 'db_server' => $srvName, 'lag' => $lag, 'maxlag' => $maxServerLag ]
400 );
401 unset( $loads[$i] );
402 }
403 }
404 }
405
406 if ( array_sum( $loads ) == 0 ) {
407 // All the replicas with non-zero weight are lagged and the primary has zero load.
408 // Inform caller so that it can use switch to read-only mode and use a lagged replica.
409 return false;
410 }
411
412 // Return a server index based on weighted random selection
413 return ArrayUtils::pickRandom( $loads );
414 }
415
416 public function getReaderIndex( $group = false ) {
417 $group = is_string( $group ) ? $group : self::GROUP_GENERIC;
418
419 if ( !$this->serverInfo->hasReplicaServers() ) {
420 // There is only one possible server to use (the primary)
421 return ServerInfo::WRITER_INDEX;
422 }
423
424 $index = $this->getExistingReaderIndex( $group );
425 if ( $index !== self::READER_INDEX_NONE ) {
426 // A reader index was already selected for this query group. Keep using it,
427 // since any session replication position was already waited on and any
428 // active transaction will be reused (e.g. for point-in-time snapshots).
429 return $index;
430 }
431
432 // Get the server weight array for this load group
433 $loads = $this->groupLoads[$group] ?? [];
434 if ( !$loads ) {
435 $this->logger->info( __METHOD__ . ": no loads for group $group" );
436 return false;
437 }
438
439 // Load any session replication positions, before any connection attempts,
440 // since reading them afterwards can only cause more delay due to possibly
441 // seeing even higher replication positions (e.g. from concurrent requests).
442 $this->loadSessionPrimaryPos();
443
444 // Scale the configured load weights according to each server's load/state.
445 // This can sometimes trigger server connections due to cache regeneration.
446 $this->loadMonitor->scaleLoads( $loads );
447
448 // Pick a server, accounting for load weights, lag, and session consistency
449 $i = $this->pickReaderIndex( $loads );
450 if ( $i === false ) {
451 // Connection attempts failed
452 return false;
453 }
454
455 // If data seen by queries is expected to reflect writes from a prior transaction,
456 // then wait for the chosen server to apply those changes. This is used to improve
457 // session consistency.
458 if ( !$this->awaitSessionPrimaryPos( $i ) ) {
459 // Data will be outdated compared to what was expected
460 $this->setLaggedReplicaMode();
461 }
462
463 // Keep using this server for DB_REPLICA handles for this group
464 if ( $i < 0 ) {
465 throw new UnexpectedValueException( "Cannot set a negative read server index" );
466 }
467 $this->readIndexByGroup[$group] = $i;
468
469 $serverName = $this->getServerName( $i );
470 $this->logger->debug( __METHOD__ . ": using server $serverName for group '$group'" );
471
472 return $i;
473 }
474
475 /**
476 * Get the server index chosen for DB_REPLICA connections for the given query group
477 *
478 * @param string $group Query group; use false for the generic group
479 * @return int Specific server index or LoadBalancer::READER_INDEX_NONE if none was chosen
480 */
481 protected function getExistingReaderIndex( $group ) {
482 return $this->readIndexByGroup[$group] ?? self::READER_INDEX_NONE;
483 }
484
485 /**
486 * Pick a server that is reachable and preferably non-lagged based on the load weights
487 *
488 * This will leave the server connection open within the pool for reuse
489 *
490 * @param array<int,int|float> $loads Map of (server index => weight) for a load group
491 * @return int|false Server index to use as the load group reader index; false on failure
492 */
493 private function pickReaderIndex( array $loads ) {
494 if ( $loads === [] ) {
495 throw new InvalidArgumentException( "Load group array is empty" );
496 }
497
498 $i = false;
499 // Quickly look through the available servers for a server that meets criteria...
500 $currentLoads = $loads;
501 while ( count( $currentLoads ) ) {
502 if ( $this->waitForPos && $this->waitForPos->asOfTime() ) {
503 $this->logger->debug( __METHOD__ . ": session has replication position" );
504 // ChronologyProtector::getSessionPrimaryPos called in loadSessionPrimaryPos()
505 // sets "waitForPos" for session consistency. This triggers doWait() after
506 // connect, so it's especially good to avoid lagged servers so as to avoid
507 // excessive delay in that method.
508 $ago = microtime( true ) - $this->waitForPos->asOfTime();
509 // Aim for <= 1 second of waiting (being too picky can backfire)
510 $i = $this->getRandomNonLagged( $currentLoads, $ago + 1 );
511 } else {
512 // Any server with less lag than it's 'max lag' param is preferable
513 $i = $this->getRandomNonLagged( $currentLoads );
514 }
515
516 if ( $i === false && count( $currentLoads ) ) {
517 $this->setLaggedReplicaMode();
518 // All replica DBs lagged, just pick anything.
519 $i = ArrayUtils::pickRandom( $currentLoads );
520 }
521
522 if ( $i === false ) {
523 // pickRandom() returned false.
524 // This is permanent and means the configuration or LoadMonitor
525 // wants us to return false.
526 $this->logger->debug( __METHOD__ . ": no suitable server found" );
527 return false;
528 }
529
530 $serverName = $this->getServerName( $i );
531 $this->logger->debug( __METHOD__ . ": connecting to $serverName..." );
532
533 // Get a connection to this server without triggering complementary connections
534 // to other servers (due to things like lag or read-only checks). We want to avoid
535 // the risk of overhead and recursion here.
536 $conn = $this->getServerConnection( $i, self::DOMAIN_ANY, self::CONN_SILENCE_ERRORS );
537 if ( !$conn ) {
538 $this->logger->warning( __METHOD__ . ": failed connecting to $serverName" );
539 unset( $currentLoads[$i] ); // avoid this server next iteration
540 continue;
541 }
542
543 // Return this server
544 break;
545 }
546
547 // If all servers were down, quit now
548 if ( $currentLoads === [] ) {
549 $this->logger->error( __METHOD__ . ": all servers down" );
550 }
551
552 return $i;
553 }
554
555 public function waitForAll( DBPrimaryPos $pos, $timeout = null ) {
556 $timeout = $timeout ?: self::MAX_WAIT_DEFAULT;
557
558 $oldPos = $this->waitForPos;
559 try {
560 $this->waitForPos = $pos;
561
562 $failedReplicas = [];
563 foreach ( $this->serverInfo->getStreamingReplicaIndexes() as $i ) {
564 if ( $this->serverHasLoadInAnyGroup( $i ) ) {
565 $start = microtime( true );
566 $ok = $this->awaitSessionPrimaryPos( $i, $timeout );
567 if ( !$ok ) {
568 $failedReplicas[] = $this->getServerName( $i );
569 }
570 $timeout -= intval( microtime( true ) - $start );
571 }
572 }
573
574 // Stop spamming logs when only one replica is lagging and we have 5+ replicas.
575 // Mediawiki automatically stops sending queries to the lagged one.
576 $failed = $failedReplicas && ( count( $failedReplicas ) > 1 || $this->getServerCount() < 5 );
577 if ( $failed ) {
578 $this->logger->error(
579 "Timed out waiting for replication to reach {raw_pos}",
580 [
581 'raw_pos' => $pos->__toString(),
582 'failed_hosts' => $failedReplicas,
583 'timeout' => $timeout,
584 'exception' => new RuntimeException()
585 ]
586 );
587 }
588
589 return !$failed;
590 } finally {
591 // Restore the old position; this is used for throttling, not lag-protection
592 $this->waitForPos = $oldPos;
593 }
594 }
595
596 /**
597 * @param int $i Specific server index
598 * @return bool
599 */
600 private function serverHasLoadInAnyGroup( $i ) {
601 foreach ( $this->groupLoads as $loadsByIndex ) {
602 if ( ( $loadsByIndex[$i] ?? 0 ) > 0 ) {
603 return true;
604 }
605 }
606
607 return false;
608 }
609
610 public function getAnyOpenConnection( $i, $flags = 0 ) {
611 $i = ( $i === self::DB_PRIMARY ) ? ServerInfo::WRITER_INDEX : $i;
612 $conn = false;
613 foreach ( $this->conns as $type => $poolConnsByServer ) {
614 if ( $i === self::DB_REPLICA ) {
615 // Consider all existing connections to any server
616 $applicableConnsByServer = $poolConnsByServer;
617 } else {
618 // Consider all existing connections to a specific server
619 $applicableConnsByServer = isset( $poolConnsByServer[$i] )
620 ? [ $i => $poolConnsByServer[$i] ]
621 : [];
622 }
623
624 $conn = $this->pickAnyOpenConnection( $applicableConnsByServer );
625 if ( $conn ) {
626 $this->logger->debug( __METHOD__ . ": found '$type' connection to #$i." );
627 break;
628 }
629 }
630
631 if ( $conn ) {
632 $this->enforceConnectionFlags( $conn, $flags );
633 }
634
635 return $conn;
636 }
637
638 /**
639 * @param Database[][] $connsByServer Map of (server index => array of DB handles)
640 * @return IDatabaseForOwner|false An appropriate open connection or false if none found
641 */
642 private function pickAnyOpenConnection( array $connsByServer ) {
643 foreach ( $connsByServer as $i => $conns ) {
644 foreach ( $conns as $conn ) {
645 if ( !$conn->isOpen() ) {
646 $this->logger->warning(
647 __METHOD__ .
648 ": pooled DB handle for {db_server} (#$i) has no open connection.",
649 $this->getConnLogContext( $conn )
650 );
651 continue; // some sort of error occurred?
652 }
653 return $conn;
654 }
655 }
656
657 return false;
658 }
659
660 /**
661 * Wait for a given replica DB to catch up to the primary DB pos stored in "waitForPos"
662 *
663 * @see loadSessionPrimaryPos()
664 *
665 * @param int $index Specific server index
666 * @param int|null $timeout Max seconds to wait; default is "waitTimeout"
667 * @return bool Success
668 */
669 private function awaitSessionPrimaryPos( $index, $timeout = null ) {
670 $timeout = max( 1, intval( $timeout ?: self::MAX_WAIT_DEFAULT ) );
671
672 if ( !$this->waitForPos || $index === ServerInfo::WRITER_INDEX ) {
673 return true;
674 }
675
676 $srvName = $this->getServerName( $index );
677
678 // Check if we already know that the DB has reached this point
679 $key = $this->srvCache->makeGlobalKey( __CLASS__, 'last-known-pos', $srvName, 'v2' );
680
681 /** @var DBPrimaryPos $knownReachedPos */
682 $position = $this->srvCache->get( $key );
683 if ( !is_array( $position ) ) {
684 $knownReachedPos = null;
685 } else {
686 $class = $position['_type_'];
687 $knownReachedPos = $class::newFromArray( $position );
688 }
689 if (
690 $knownReachedPos instanceof DBPrimaryPos &&
691 $knownReachedPos->hasReached( $this->waitForPos )
692 ) {
693 $this->logger->debug(
694 __METHOD__ .
695 ": replica DB {db_server} known to be caught up (pos >= $knownReachedPos).",
696 [ 'db_server' => $srvName ]
697 );
698
699 return true;
700 }
701
702 $close = false; // close the connection afterwards
703 $flags = self::CONN_SILENCE_ERRORS;
704 // Check if there is an existing connection that can be used
705 $conn = $this->getAnyOpenConnection( $index, $flags );
706 if ( !$conn ) {
707 // Get a connection to this server without triggering complementary connections
708 // to other servers (due to things like lag or read-only checks). We want to avoid
709 // the risk of overhead and recursion here.
710 $conn = $this->getServerConnection( $index, self::DOMAIN_ANY, $flags );
711 if ( !$conn ) {
712 $this->logger->warning(
713 __METHOD__ . ': failed to connect to {db_server}',
714 [ 'db_server' => $srvName ]
715 );
716
717 return false;
718 }
719 // Avoid connection spam in waitForAll() when connections
720 // are made just for the sake of doing this lag check.
721 $close = true;
722 }
723
724 $this->logger->info(
725 __METHOD__ .
726 ': waiting for replica DB {db_server} to catch up...',
727 $this->getConnLogContext( $conn )
728 );
729
730 $result = $conn->primaryPosWait( $this->waitForPos, $timeout );
731
732 $ok = ( $result !== null && $result != -1 );
733 if ( $ok ) {
734 // Remember that the DB reached this point
735 $this->srvCache->set( $key, $this->waitForPos->toArray(), BagOStuff::TTL_DAY );
736 }
737
738 if ( $close ) {
739 $this->closeConnection( $conn );
740 }
741
742 return $ok;
743 }
744
745 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
746 if ( self::fieldHasBit( $flags, self::CONN_SILENCE_ERRORS ) ) {
747 throw new UnexpectedValueException(
748 __METHOD__ . ' got CONN_SILENCE_ERRORS; connection is already deferred'
749 );
750 }
751
752 $domain = $this->resolveDomainID( $domain );
753 $role = ( $i === self::DB_PRIMARY || $i === ServerInfo::WRITER_INDEX )
754 ? self::DB_PRIMARY
755 : self::DB_REPLICA;
756
757 return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role, $this->modcount );
758 }
759
760 public function getConnectionInternal( $i, $groups = [], $domain = false, $flags = 0 ): IDatabase {
761 $domain = $this->resolveDomainID( $domain );
762 $group = $this->resolveGroups( $groups, $i );
763 $flags = $this->sanitizeConnectionFlags( $flags, $domain );
764 // If given DB_PRIMARY/DB_REPLICA, resolve it to a specific server index. Resolving
765 // DB_REPLICA might trigger getServerConnection() calls due to the getReaderIndex()
766 // connectivity checks or LoadMonitor::scaleLoads() server state cache regeneration.
767 // The use of getServerConnection() instead of getConnection() avoids infinite loops.
768 $serverIndex = $i;
769 if ( $i === self::DB_PRIMARY ) {
770 $serverIndex = ServerInfo::WRITER_INDEX;
771 } elseif ( $i === self::DB_REPLICA ) {
772 $groupIndex = $this->getReaderIndex( $group );
773 if ( $groupIndex !== false ) {
774 // Group connection succeeded
775 $serverIndex = $groupIndex;
776 }
777 if ( $serverIndex < 0 ) {
778 $this->reportConnectionError( 'could not connect to any replica DB server' );
779 }
780 } elseif ( !$this->serverInfo->hasServerIndex( $i ) ) {
781 throw new UnexpectedValueException( "Invalid server index index #$i" );
782 }
783 // Get an open connection to that server (might trigger a new connection)
784 return $this->getServerConnection( $serverIndex, $domain, $flags );
785 }
786
787 public function getServerConnection( $i, $domain, $flags = 0 ) {
788 $domainInstance = DatabaseDomain::newFromId( $domain );
789 // Number of connections made before getting the server index and handle
790 $priorConnectionsMade = $this->connectionCounter;
791 // Get an open connection to this server (might trigger a new connection)
792 $conn = $this->reuseOrOpenConnectionForNewRef( $i, $domainInstance, $flags );
793 // Throw an error or otherwise bail out if the connection attempt failed
794 if ( !( $conn instanceof IDatabaseForOwner ) ) {
795 if ( !self::fieldHasBit( $flags, self::CONN_SILENCE_ERRORS ) ) {
796 $this->reportConnectionError();
797 }
798
799 return false;
800 }
801
802 // Profile any new connections caused by this method
803 if ( $this->connectionCounter > $priorConnectionsMade ) {
804 $this->trxProfiler->recordConnection(
805 $conn->getServerName(),
806 $conn->getDBname(),
807 ( $i === ServerInfo::WRITER_INDEX && $this->hasStreamingReplicaServers() )
808 );
809 }
810
811 if ( !$conn->isOpen() ) {
812 $this->lastErrorConn = $conn;
813 // Connection was made but later unrecoverably lost for some reason.
814 // Do not return a handle that will just throw exceptions on use, but
815 // let the calling code, e.g. getReaderIndex(), try another server.
816 if ( !self::fieldHasBit( $flags, self::CONN_SILENCE_ERRORS ) ) {
817 $this->reportConnectionError();
818 }
819 return false;
820 }
821
822 return $conn;
823 }
824
825 /**
826 * @deprecated since 1.39.
827 */
828 public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ): DBConnRef {
829 wfDeprecated( __METHOD__, '1.39' );
830 // @phan-suppress-next-line PhanTypeMismatchReturnSuperType to be removed soon
831 return $this->getConnection( $i, $groups, $domain, $flags );
832 }
833
834 public function getMaintenanceConnectionRef(
835 $i,
836 $groups = [],
837 $domain = false,
838 $flags = 0
839 ): DBConnRef {
840 if ( self::fieldHasBit( $flags, self::CONN_SILENCE_ERRORS ) ) {
841 throw new UnexpectedValueException(
842 __METHOD__ . ' CONN_SILENCE_ERRORS is not supported'
843 );
844 }
845
846 $domain = $this->resolveDomainID( $domain );
847 $role = ( $i === self::DB_PRIMARY || $i === ServerInfo::WRITER_INDEX )
848 ? self::DB_PRIMARY
849 : self::DB_REPLICA;
850
851 return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role, $this->modcount );
852 }
853
854 /**
855 * Get a live connection handle to the given domain
856 *
857 * This will reuse an existing tracked connection when possible. In some cases, this
858 * involves switching the DB domain of an existing handle in order to reuse it. If no
859 * existing handles can be reused, then a new connection will be made.
860 *
861 * @param int $i Specific server index
862 * @param DatabaseDomain $domain Database domain ID required by the reference
863 * @param int $flags Bit field of class CONN_* constants
864 * @return IDatabase|null Database or null on error
865 * @throws DBError When database selection fails
866 * @throws InvalidArgumentException When the server index is invalid
867 * @throws UnexpectedValueException When the DB domain of the connection is corrupted
868 * @throws DBAccessError If disable() was called
869 */
870 private function reuseOrOpenConnectionForNewRef( $i, DatabaseDomain $domain, $flags = 0 ) {
871 // Figure out which connection pool to use based on the flags
872 if ( $this->fieldHasBit( $flags, self::CONN_UNTRACKED_GAUGE ) ) {
873 // Use low timeouts, use autocommit mode, ignore transaction rounds
874 $category = self::CATEGORY_GAUGE;
875 } elseif ( self::fieldHasBit( $flags, self::CONN_TRX_AUTOCOMMIT ) ) {
876 // Use autocommit mode, ignore transaction rounds
877 $category = self::CATEGORY_AUTOCOMMIT;
878 } else {
879 // Respect DBO_DEFAULT, respect transaction rounds
880 $category = self::CATEGORY_ROUND;
881 }
882
883 $conn = null;
884 // Reuse a free connection in the pool from any domain if possible. There should only
885 // be one connection in this pool unless either:
886 // - a) IDatabase::databasesAreIndependent() returns true (e.g. postgres) and two
887 // or more database domains have been used during the load balancer's lifetime
888 // - b) Two or more nested function calls used getConnection() on different domains.
889 foreach ( ( $this->conns[$category][$i] ?? [] ) as $poolConn ) {
890 // Check if any required DB domain changes for the new reference are possible
891 // Calling selectDomain() would trigger a reconnect, which will break if a
892 // transaction is active or if there is any other meaningful session state.
893 $isShareable = !(
894 $poolConn->databasesAreIndependent() &&
895 $domain->getDatabase() !== null &&
896 $domain->getDatabase() !== $poolConn->getDBname()
897 );
898 if ( $isShareable ) {
899 $conn = $poolConn;
900 // Make any required DB domain changes for the new reference
901 if ( !$domain->isUnspecified() ) {
902 $conn->selectDomain( $domain );
903 }
904 $this->logger->debug( __METHOD__ . ": reusing connection for $i/$domain" );
905 break;
906 }
907 }
908
909 // If necessary, try to open a new connection and add it to the pool
910 if ( !$conn ) {
911 $conn = $this->reallyOpenConnection(
912 $i,
913 $domain,
914 [ self::INFO_CONN_CATEGORY => $category ]
915 );
916 if ( $conn->isOpen() ) {
917 // Make Database::isReadOnly() respect server-side and configuration-based
918 // read-only mode. Note that replica handles are always seen as read-only
919 // in Database::isReadOnly() and Database::assertIsWritablePrimary().
920 if ( $i === ServerInfo::WRITER_INDEX ) {
921 if ( $this->readOnlyReason !== false ) {
922 $readOnlyReason = $this->readOnlyReason;
923 } elseif ( $this->isPrimaryRunningReadOnly( $conn ) ) {
924 $readOnlyReason = 'The primary database server is running in read-only mode.';
925 } else {
926 $readOnlyReason = false;
927 }
928 $conn->setLBInfo( $conn::LB_READ_ONLY_REASON, $readOnlyReason );
929 }
930 // Connection obtained; check if it belongs to a tracked connection category
931 if ( isset( $this->conns[$category] ) ) {
932 // Track this connection for future reuse
933 $this->conns[$category][$i][] = $conn;
934 }
935 } else {
936 $this->logger->warning( __METHOD__ . ": connection error for $i/$domain" );
937 $this->lastErrorConn = $conn;
938 $conn = null;
939 }
940 }
941
942 if ( $conn instanceof IDatabaseForOwner ) {
943 // Check to make sure that the right domain is selected
944 $this->assertConnectionDomain( $conn, $domain );
945 // Check to make sure that the CONN_* flags are respected
946 $this->enforceConnectionFlags( $conn, $flags );
947 }
948
949 return $conn;
950 }
951
952 /**
953 * Sanity check to make sure that the right domain is selected
954 *
955 * @param Database $conn
956 * @param DatabaseDomain $domain
957 * @throws DBUnexpectedError
958 */
959 private function assertConnectionDomain( Database $conn, DatabaseDomain $domain ) {
960 if ( !$domain->isCompatible( $conn->getDomainID() ) ) {
961 throw new UnexpectedValueException(
962 "Got connection to '{$conn->getDomainID()}', but expected one for '{$domain}'"
963 );
964 }
965 }
966
967 public function getServerAttributes( $i ) {
968 return $this->databaseFactory->attributesFromType(
969 $this->getServerType( $i ),
970 $this->serverInfo->getServerDriver( $i )
971 );
972 }
973
974 /**
975 * Open a new network connection to a server (uncached)
976 *
977 * Returns a Database object whether or not the connection was successful.
978 *
979 * @param int $i Specific server index
980 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
981 * @param array $lbInfo Additional information for setLBInfo()
982 * @return Database
983 * @throws DBAccessError
984 * @throws InvalidArgumentException
985 */
986 protected function reallyOpenConnection( $i, DatabaseDomain $domain, array $lbInfo ) {
987 if ( $this->disabled ) {
988 throw new DBAccessError();
989 }
990
991 $server = $this->serverInfo->getServerInfoStrict( $i );
992 if ( $lbInfo[self::INFO_CONN_CATEGORY] === self::CATEGORY_GAUGE ) {
993 // Use low connection/read timeouts for connection used for gauging server health.
994 // Gauge information should be cached and used to avoid outages. Indefinite hanging
995 // while gauging servers would do the opposite.
996 $server['connectTimeout'] = min( 1, $server['connectTimeout'] ?? INF );
997 $server['receiveTimeout'] = min( 1, $server['receiveTimeout'] ?? INF );
998 // Avoid implicit transactions and avoid any SET query for session variables during
999 // Database::open(). If a server becomes slow, every extra query can cause significant
1000 // delays, even with low connect/receive timeouts.
1001 $server['flags'] ??= 0;
1002 $server['flags'] &= ~IDatabase::DBO_DEFAULT;
1003 $server['flags'] |= IDatabase::DBO_GAUGE;
1004 } else {
1005 // Use implicit transactions unless explicitly configured otherwise
1006 $server['flags'] ??= IDatabase::DBO_DEFAULT;
1007 }
1008
1009 if ( !empty( $server['is static'] ) ) {
1010 $topologyRole = IDatabase::ROLE_STATIC_CLONE;
1011 } else {
1012 $topologyRole = ( $i === ServerInfo::WRITER_INDEX )
1013 ? IDatabase::ROLE_STREAMING_MASTER
1014 : IDatabase::ROLE_STREAMING_REPLICA;
1015 }
1016
1017 $conn = $this->databaseFactory->create(
1018 $server['type'],
1019 array_merge( $server, [
1020 // Basic replication role information
1021 'topologyRole' => $topologyRole,
1022 // Use the database specified in $domain (null means "none or entrypoint DB");
1023 // fallback to the $server default if the RDBMs is an embedded library using a
1024 // file on disk since there would be nothing to access to without a DB/file name.
1025 'dbname' => $this->getServerAttributes( $i )[Database::ATTR_DB_IS_FILE]
1026 ? ( $domain->getDatabase() ?? $server['dbname'] ?? null )
1027 : $domain->getDatabase(),
1028 // Override the $server default schema with that of $domain if specified
1029 'schema' => $domain->getSchema(),
1030 // Use the table prefix specified in $domain
1031 'tablePrefix' => $domain->getTablePrefix(),
1032 'srvCache' => $this->srvCache,
1033 'logger' => $this->logger,
1034 'errorLogger' => $this->errorLogger,
1035 'trxProfiler' => $this->trxProfiler,
1036 'lbInfo' => [ self::INFO_SERVER_INDEX => $i ] + $lbInfo
1037 ] ),
1038 Database::NEW_UNCONNECTED
1039 );
1040 // Set alternative table/index names before any queries can be issued
1041 $conn->setTableAliases( $this->tableAliases );
1042 $conn->setIndexAliases( $this->indexAliases );
1043 // Account for any active transaction round and listeners
1044 if ( $i === ServerInfo::WRITER_INDEX ) {
1045 if ( $this->trxRoundId !== false ) {
1046 $this->applyTransactionRoundFlags( $conn );
1047 }
1048 foreach ( $this->trxRecurringCallbacks as $name => $callback ) {
1049 $conn->setTransactionListener( $name, $callback );
1050 }
1051 }
1052
1053 // Make the connection handle live
1054 try {
1055 $conn->initConnection();
1056 ++$this->connectionCounter;
1057 } catch ( DBConnectionError $e ) {
1058 $this->lastErrorConn = $conn;
1059 // ignore; let the DB handle the logging
1060 }
1061
1062 if ( $conn->isOpen() ) {
1063 $this->logger->debug( __METHOD__ . ": opened new connection for $i/$domain" );
1064 } else {
1065 $this->logger->warning(
1066 __METHOD__ . ": connection error for $i/{db_domain}",
1067 [ 'db_domain' => $domain->getId() ]
1068 );
1069 }
1070
1071 // Log when many connection are made during a single request/script
1072 $count = 0;
1073 foreach ( $this->conns as $poolConnsByServer ) {
1074 foreach ( $poolConnsByServer as $serverConns ) {
1075 $count += count( $serverConns );
1076 }
1077 }
1078 if ( $count >= self::CONN_HELD_WARN_THRESHOLD ) {
1079 $this->logger->warning(
1080 __METHOD__ . ": {connections}+ connections made (primary={primarydb})",
1081 $this->getConnLogContext(
1082 $conn,
1083 [
1084 'connections' => $count,
1085 'primarydb' => $this->serverInfo->getPrimaryServerName(),
1086 'db_domain' => $domain->getId()
1087 ]
1088 )
1089 );
1090 }
1091
1092 $this->assertConnectionDomain( $conn, $domain );
1093
1094 return $conn;
1095 }
1096
1097 /**
1098 * Make sure that any "waitForPos" replication positions are loaded and available
1099 *
1100 * Each load balancer cluster has up to one replication position for the session.
1101 * These are used when data read by queries is expected to reflect writes caused
1102 * by a prior request/script from the same client.
1103 *
1104 * @see awaitSessionPrimaryPos()
1105 */
1106 private function loadSessionPrimaryPos() {
1107 if ( !$this->chronologyProtectorCalled && $this->chronologyProtector ) {
1108 $this->chronologyProtectorCalled = true;
1109 $pos = $this->chronologyProtector->getSessionPrimaryPos( $this );
1110 $this->logger->debug( __METHOD__ . ': executed chronology callback.' );
1111 if ( $pos ) {
1112 if ( !$this->waitForPos || $pos->hasReached( $this->waitForPos ) ) {
1113 $this->waitForPos = $pos;
1114 }
1115 }
1116 }
1117 }
1118
1119 /**
1120 * @param string $extraLbError Separat load balancer error
1121 * @throws DBConnectionError
1122 * @return never
1123 */
1124 private function reportConnectionError( $extraLbError = '' ) {
1125 if ( $this->lastErrorConn instanceof IDatabaseForOwner ) {
1126 $srvName = $this->lastErrorConn->getServerName();
1127 $lastDbError = $this->lastErrorConn->lastError() ?: 'unknown error';
1128
1129 $exception = new DBConnectionError(
1130 $this->lastErrorConn,
1131 $extraLbError
1132 ? "{$extraLbError}; {$lastDbError} ({$srvName})"
1133 : "{$lastDbError} ({$srvName})"
1134 );
1135
1136 if ( $extraLbError ) {
1137 $this->logger->warning(
1138 __METHOD__ . ": $extraLbError; {last_error} ({db_server})",
1139 $this->getConnLogContext(
1140 $this->lastErrorConn,
1141 [
1142 'method' => __METHOD__,
1143 'last_error' => $lastDbError
1144 ]
1145 )
1146 );
1147 }
1148 } else {
1149 $exception = new DBConnectionError(
1150 null,
1151 $extraLbError ?: 'could not connect to the DB server'
1152 );
1153
1154 if ( $extraLbError ) {
1155 $this->logger->error(
1156 __METHOD__ . ": $extraLbError",
1157 [
1158 'method' => __METHOD__,
1159 'last_error' => '(last connection error missing)'
1160 ]
1161 );
1162 }
1163 }
1164
1165 throw $exception;
1166 }
1167
1168 public function getServerCount() {
1169 return $this->serverInfo->getServerCount();
1170 }
1171
1172 public function hasReplicaServers() {
1173 return $this->serverInfo->hasReplicaServers();
1174 }
1175
1176 public function hasStreamingReplicaServers() {
1177 return $this->serverInfo->hasStreamingReplicaServers();
1178 }
1179
1180 public function getServerName( $i ): string {
1181 return $this->serverInfo->getServerName( $i );
1182 }
1183
1184 public function getServerInfo( $i ) {
1185 return $this->serverInfo->getServerInfo( $i );
1186 }
1187
1188 public function getServerType( $i ) {
1189 return $this->serverInfo->getServerType( $i );
1190 }
1191
1192 public function getPrimaryPos() {
1193 $conn = $this->getAnyOpenConnection( ServerInfo::WRITER_INDEX );
1194 if ( $conn ) {
1195 return $conn->getPrimaryPos();
1196 }
1197
1198 $conn = $this->getConnectionInternal( ServerInfo::WRITER_INDEX, self::CONN_SILENCE_ERRORS );
1199 // @phan-suppress-next-line PhanRedundantCondition
1200 if ( !$conn ) {
1201 $this->reportConnectionError();
1202 }
1203
1204 // ::getConnectionInternal() should return IDatabaseForOwner but changing signature
1205 // is not straightforward (being implemented in Wikibase)
1206 '@phan-var IDatabaseForOwner $conn';
1207 try {
1208 return $conn->getPrimaryPos();
1209 } finally {
1210 $this->closeConnection( $conn );
1211 }
1212 }
1213
1214 /**
1215 * Apply updated configuration.
1216 *
1217 * This only unregisters servers that were removed in the new configuration.
1218 * It does not register new servers nor update the group load weights.
1219 *
1220 * This invalidates any open connections. However, existing connections may continue to be
1221 * used while they are in an active transaction. In that case, the old connection will be
1222 * discarded on the first operation after the transaction is complete. The next operation
1223 * will use a new connection based on the new configuration.
1224 *
1225 * @internal for use by LBFactory::reconfigure()
1226 *
1227 * @see DBConnRef::ensureConnection()
1228 * @see LBFactory::reconfigure()
1229 *
1230 * @param array $params A database configuration array, see $wgLBFactoryConf.
1231 *
1232 * @return void
1233 */
1234 public function reconfigure( array $params ) {
1235 $anyServerDepooled = false;
1236
1237 $paramServers = $params['servers'];
1238 $newIndexByServerIndex = $this->serverInfo->reconfigureServers( $paramServers );
1239 foreach ( $newIndexByServerIndex as $i => $ni ) {
1240 if ( $ni !== null ) {
1241 // Server still exists in the new config
1242 $newWeightByGroup = $paramServers[$ni]['groupLoads'] ?? [];
1243 $newWeightByGroup[ILoadBalancer::GROUP_GENERIC] = $paramServers[$ni]['load'];
1244 // Check if the server was removed from any load groups
1245 foreach ( $this->groupLoads as $group => $weightByIndex ) {
1246 if ( isset( $weightByIndex[$i] ) && !isset( $newWeightByGroup[$group] ) ) {
1247 // Server no longer in this load group in the new config
1248 $anyServerDepooled = true;
1249 unset( $this->groupLoads[$group][$i] );
1250 }
1251 }
1252 } else {
1253 // Server no longer exists in the new config
1254 $anyServerDepooled = true;
1255 // Note that if the primary server is depooled and a replica server promoted
1256 // to new primary, then DB_PRIMARY handles will fail with server index errors
1257 foreach ( $this->groupLoads as $group => $loads ) {
1258 unset( $this->groupLoads[$group][$i] );
1259 }
1260 }
1261 }
1262
1263 if ( $anyServerDepooled ) {
1264 // NOTE: We could close all connection here, but some may be in the middle of
1265 // a transaction. So instead, we leave it to DBConnRef to close the
1266 // connection when it detects that the modcount has changed and no
1267 // transaction is open.
1268 $this->logger->info( 'Reconfiguring dbs!' );
1269 // Unpin DB_REPLICA connection groups from server indexes
1270 $this->readIndexByGroup = [];
1271 // We could close all connection here, but some may be in the middle of a
1272 // transaction. So instead, we leave it to DBConnRef to close the connection
1273 // when it detects that the modcount has changed and no transaction is open.
1274 $this->conns = self::newTrackedConnectionsArray();
1275 // Bump modification counter to invalidate the connections held by DBConnRef
1276 // instances. This will cause the next call to a method on the DBConnRef
1277 // to get a new connection from getConnectionInternal()
1278 $this->modcount++;
1279 }
1280 }
1281
1282 public function disable( $fname = __METHOD__ ) {
1283 $this->closeAll( $fname );
1284 $this->disabled = true;
1285 }
1286
1287 public function closeAll( $fname = __METHOD__ ) {
1288 /** @noinspection PhpUnusedLocalVariableInspection */
1289 $scope = ScopedCallback::newScopedIgnoreUserAbort();
1290 foreach ( $this->getOpenConnections() as $conn ) {
1291 $conn->close( $fname );
1292 }
1293
1294 $this->conns = self::newTrackedConnectionsArray();
1295 }
1296
1297 /**
1298 * Close a connection
1299 *
1300 * Using this function makes sure the LoadBalancer knows the connection is closed.
1301 * If you use $conn->close() directly, the load balancer won't update its state.
1302 *
1303 * @param IDatabaseForOwner $conn
1304 */
1305 private function closeConnection( IDatabaseForOwner $conn ) {
1306 if ( $conn instanceof DBConnRef ) {
1307 // Avoid calling close() but still leaving the handle in the pool
1308 throw new RuntimeException( 'Cannot close DBConnRef instance; it must be shareable' );
1309 }
1310
1311 $domain = $conn->getDomainID();
1312 $serverIndex = $conn->getLBInfo( self::INFO_SERVER_INDEX );
1313 if ( $serverIndex === null ) {
1314 throw new UnexpectedValueException( "Handle on '$domain' missing server index" );
1315 }
1316
1317 $srvName = $this->serverInfo->getServerName( $serverIndex );
1318
1319 $found = false;
1320 foreach ( $this->conns as $type => $poolConnsByServer ) {
1321 $key = array_search( $conn, $poolConnsByServer[$serverIndex] ?? [], true );
1322 if ( $key !== false ) {
1323 $found = true;
1324 unset( $this->conns[$type][$serverIndex][$key] );
1325 }
1326 }
1327
1328 if ( !$found ) {
1329 $this->logger->warning(
1330 __METHOD__ .
1331 ": orphaned connection to database {$this->stringifyConn( $conn )} at '$srvName'."
1332 );
1333 }
1334
1335 $this->logger->debug(
1336 __METHOD__ .
1337 ": closing connection to database {$this->stringifyConn( $conn )} at '$srvName'."
1338 );
1339
1340 $conn->close( __METHOD__ );
1341 }
1342
1343 public function finalizePrimaryChanges( $fname = __METHOD__ ) {
1344 $this->assertTransactionRoundStage( [ self::ROUND_CURSORY, self::ROUND_FINALIZED ] );
1345 /** @noinspection PhpUnusedLocalVariableInspection */
1346 $scope = ScopedCallback::newScopedIgnoreUserAbort();
1347
1348 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1349 // Loop until callbacks stop adding callbacks on other connections
1350 $total = 0;
1351 do {
1352 $count = 0; // callbacks execution attempts
1353 foreach ( $this->getOpenPrimaryConnections() as $conn ) {
1354 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1355 // Any error should cause all (peer) transactions to be rolled back together.
1356 $count += $conn->runOnTransactionPreCommitCallbacks();
1357 }
1358 $total += $count;
1359 } while ( $count > 0 );
1360 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1361 foreach ( $this->getOpenPrimaryConnections() as $conn ) {
1362 $conn->setTrxEndCallbackSuppression( true );
1363 }
1364 $this->trxRoundStage = self::ROUND_FINALIZED;
1365
1366 return $total;
1367 }
1368
1369 public function approvePrimaryChanges( int $maxWriteDuration, $fname = __METHOD__ ) {
1370 $this->assertTransactionRoundStage( self::ROUND_FINALIZED );
1371 /** @noinspection PhpUnusedLocalVariableInspection */
1372 $scope = ScopedCallback::newScopedIgnoreUserAbort();
1373
1374 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1375 foreach ( $this->getOpenPrimaryConnections() as $conn ) {
1376 // Any atomic sections should have been closed by now and there definitely should
1377 // not be any open transactions started by begin() from callers outside Database.
1378 if ( $conn->explicitTrxActive() ) {
1379 throw new DBTransactionError(
1380 $conn,
1381 "Explicit transaction still active; a caller might have failed to call " .
1382 "endAtomic() or cancelAtomic()."
1383 );
1384 }
1385 // Assert that the time to replicate the transaction will be reasonable.
1386 // If this fails, then all DB transactions will be rollback back together.
1387 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY );
1388 if ( $maxWriteDuration > 0 ) {
1389 if ( $time > $maxWriteDuration ) {
1390 $humanTimeSec = round( $time, 3 );
1391 throw new DBTransactionSizeError(
1392 $conn,
1393 "Transaction spent {time}s in writes, exceeding the {$maxWriteDuration}s limit",
1394 // Message parameters for: transaction-duration-limit-exceeded
1395 [ $time, $maxWriteDuration ],
1396 null,
1397 [ 'time' => $humanTimeSec ]
1398 );
1399 } elseif ( $time > 0 ) {
1400 $timeMs = $time * 1000;
1401 $humanTimeMs = round( $timeMs, $timeMs > 1 ? 0 : 3 );
1402 $this->logger->debug(
1403 "Transaction spent {time_ms}ms in writes, under the {$maxWriteDuration}s limit",
1404 [ 'time_ms' => $humanTimeMs ]
1405 );
1406 }
1407 }
1408 // If a connection sits idle for too long it might be dropped, causing transaction
1409 // writes and session locks to be lost. Ping all the server connections before making
1410 // any attempt to commit the transactions belonging to the active transaction round.
1411 if ( $conn->writesOrCallbacksPending() || $conn->sessionLocksPending() ) {
1412 if ( !$conn->ping() ) {
1413 throw new DBTransactionError(
1414 $conn,
1415 "Pre-commit ping failed on server {$conn->getServerName()}"
1416 );
1417 }
1418 }
1419 }
1420 $this->trxRoundStage = self::ROUND_APPROVED;
1421 }
1422
1423 public function beginPrimaryChanges( $fname = __METHOD__ ) {
1424 if ( $this->trxRoundId !== false ) {
1425 throw new DBTransactionError(
1426 null,
1427 "Transaction round '{$this->trxRoundId}' already started"
1428 );
1429 }
1430 $this->assertTransactionRoundStage( self::ROUND_CURSORY );
1431 /** @noinspection PhpUnusedLocalVariableInspection */
1432 $scope = ScopedCallback::newScopedIgnoreUserAbort();
1433
1434 // Clear any empty transactions (no writes/callbacks) from the implicit round
1435 $this->flushPrimarySnapshots( $fname );
1436
1437 $this->trxRoundId = $fname;
1438 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1439 // Mark applicable handles as participating in this explicit transaction round.
1440 // For each of these handles, any writes and callbacks will be tied to a single
1441 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1442 // are part of an en masse commit or an en masse rollback.
1443 foreach ( $this->getOpenPrimaryConnections() as $conn ) {
1444 $this->applyTransactionRoundFlags( $conn );
1445 }
1446 $this->trxRoundStage = self::ROUND_CURSORY;
1447 }
1448
1449 public function commitPrimaryChanges( $fname = __METHOD__ ) {
1450 $this->assertTransactionRoundStage( self::ROUND_APPROVED );
1451 /** @noinspection PhpUnusedLocalVariableInspection */
1452 $scope = ScopedCallback::newScopedIgnoreUserAbort();
1453
1454 $failures = [];
1455
1456 $restore = ( $this->trxRoundId !== false );
1457 $this->trxRoundId = false;
1458 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1459 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1460 // Note that callbacks should already be suppressed due to finalizePrimaryChanges().
1461 foreach ( $this->getOpenPrimaryConnections() as $conn ) {
1462 try {
1463 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1464 } catch ( DBError $e ) {
1465 ( $this->errorLogger )( $e );
1466 $failures[] = "{$conn->getServerName()}: {$e->getMessage()}";
1467 }
1468 }
1469 if ( $failures ) {
1470 throw new DBTransactionError(
1471 null,
1472 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1473 );
1474 }
1475 if ( $restore ) {
1476 // Unmark handles as participating in this explicit transaction round
1477 foreach ( $this->getOpenPrimaryConnections() as $conn ) {
1478 $this->undoTransactionRoundFlags( $conn );
1479 }
1480 }
1481 $this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS;
1482 }
1483
1484 public function runPrimaryTransactionIdleCallbacks( $fname = __METHOD__ ) {
1485 if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
1486 $type = IDatabase::TRIGGER_COMMIT;
1487 } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
1488 $type = IDatabase::TRIGGER_ROLLBACK;
1489 } else {
1490 throw new DBTransactionError(
1491 null,
1492 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1493 );
1494 }
1495 /** @noinspection PhpUnusedLocalVariableInspection */
1496 $scope = ScopedCallback::newScopedIgnoreUserAbort();
1497
1498 $oldStage = $this->trxRoundStage;
1499 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1500
1501 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1502 foreach ( $this->getOpenPrimaryConnections() as $conn ) {
1503 $conn->setTrxEndCallbackSuppression( false );
1504 }
1505
1506 $errors = [];
1507 $fname = __METHOD__;
1508 // Loop until callbacks stop adding callbacks on other connections
1509 do {
1510 // Run any pending callbacks for each connection...
1511 $count = 0; // callback execution attempts
1512 foreach ( $this->getOpenPrimaryConnections() as $conn ) {
1513 if ( $conn->trxLevel() ) {
1514 continue; // retry in the next iteration, after commit() is called
1515 }
1516 $count += $conn->runOnTransactionIdleCallbacks( $type, $errors );
1517 }
1518 // Clear out any active transactions left over from callbacks...
1519 foreach ( $this->getOpenPrimaryConnections() as $conn ) {
1520 if ( $conn->writesPending() ) {
1521 // A callback from another handle wrote to this one and DBO_TRX is set
1522 $fnames = implode( ', ', $conn->pendingWriteCallers() );
1523 $this->logger->info(
1524 "$fname: found writes pending ($fnames).",
1525 $this->getConnLogContext(
1526 $conn,
1527 [ 'exception' => new RuntimeException() ]
1528 )
1529 );
1530 } elseif ( $conn->trxLevel() ) {
1531 // A callback from another handle read from this one and DBO_TRX is set,
1532 // which can easily happen if there is only one DB (no replicas)
1533 $this->logger->debug( "$fname: found empty transaction." );
1534 }
1535 try {
1536 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1537 } catch ( DBError $ex ) {
1538 $errors[] = $ex;
1539 }
1540 }
1541 } while ( $count > 0 );
1542
1543 $this->trxRoundStage = $oldStage;
1544
1545 return $errors[0] ?? null;
1546 }
1547
1548 public function runPrimaryTransactionListenerCallbacks( $fname = __METHOD__ ) {
1549 if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
1550 $type = IDatabase::TRIGGER_COMMIT;
1551 } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
1552 $type = IDatabase::TRIGGER_ROLLBACK;
1553 } else {
1554 throw new DBTransactionError(
1555 null,
1556 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1557 );
1558 }
1559 /** @noinspection PhpUnusedLocalVariableInspection */
1560 $scope = ScopedCallback::newScopedIgnoreUserAbort();
1561
1562 $errors = [];
1563 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1564 foreach ( $this->getOpenPrimaryConnections() as $conn ) {
1565 $conn->runTransactionListenerCallbacks( $type, $errors );
1566 }
1567 $this->trxRoundStage = self::ROUND_CURSORY;
1568
1569 return $errors[0] ?? null;
1570 }
1571
1572 public function rollbackPrimaryChanges( $fname = __METHOD__ ) {
1573 /** @noinspection PhpUnusedLocalVariableInspection */
1574 $scope = ScopedCallback::newScopedIgnoreUserAbort();
1575
1576 $restore = ( $this->trxRoundId !== false );
1577 $this->trxRoundId = false;
1578 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1579 foreach ( $this->getOpenPrimaryConnections() as $conn ) {
1580 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS );
1581 }
1582 if ( $restore ) {
1583 // Unmark handles as participating in this explicit transaction round
1584 foreach ( $this->getOpenPrimaryConnections() as $conn ) {
1585 $this->undoTransactionRoundFlags( $conn );
1586 }
1587 }
1588 $this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS;
1589 }
1590
1591 public function flushPrimarySessions( $fname = __METHOD__ ) {
1592 $this->assertTransactionRoundStage( [ self::ROUND_CURSORY ] );
1593 if ( $this->hasPrimaryChanges() ) {
1594 // Any transaction should have been rolled back beforehand
1595 throw new DBTransactionError( null, "Cannot reset session while writes are pending" );
1596 }
1597
1598 foreach ( $this->getOpenPrimaryConnections() as $conn ) {
1599 $conn->flushSession( $fname, $conn::FLUSHING_ALL_PEERS );
1600 }
1601 }
1602
1603 /**
1604 * @param string|string[] $stage
1605 * @throws DBTransactionError
1606 */
1607 private function assertTransactionRoundStage( $stage ) {
1608 $stages = (array)$stage;
1609
1610 if ( !in_array( $this->trxRoundStage, $stages, true ) ) {
1611 $stageList = implode(
1612 '/',
1613 array_map( static function ( $v ) {
1614 return "'$v'";
1615 }, $stages )
1616 );
1617 $transactionName = $this->trxRoundId ?: '<unknown>';
1618 throw new DBTransactionError(
1619 null,
1620 "Transaction '$transactionName' round stage must be '$stageList' (not '{$this->trxRoundStage}')"
1621 );
1622 }
1623 }
1624
1625 /**
1626 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1627 *
1628 * Some servers may have neither flag enabled, meaning that they opt out of such
1629 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1630 * when a DB server is used for something like simple key/value storage.
1631 *
1632 * @param Database $conn
1633 */
1634 private function applyTransactionRoundFlags( Database $conn ) {
1635 if ( $conn->getLBInfo( self::INFO_CONN_CATEGORY ) !== self::CATEGORY_ROUND ) {
1636 return; // transaction rounds do not apply to these connections
1637 }
1638
1639 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1640 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1641 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1642 $conn->setFlag( $conn::DBO_TRX, $conn::REMEMBER_PRIOR );
1643 }
1644
1645 if ( $conn->getFlag( $conn::DBO_TRX ) ) {
1646 $conn->setLBInfo( $conn::LB_TRX_ROUND_ID, $this->trxRoundId );
1647 }
1648 }
1649
1650 /**
1651 * @param Database $conn
1652 */
1653 private function undoTransactionRoundFlags( Database $conn ) {
1654 if ( $conn->getLBInfo( self::INFO_CONN_CATEGORY ) !== self::CATEGORY_ROUND ) {
1655 return; // transaction rounds do not apply to these connections
1656 }
1657
1658 if ( $conn->getFlag( $conn::DBO_TRX ) ) {
1659 $conn->setLBInfo( $conn::LB_TRX_ROUND_ID, null ); // remove the round ID
1660 }
1661
1662 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1663 $conn->restoreFlags( $conn::RESTORE_PRIOR );
1664 }
1665 }
1666
1667 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
1668 foreach ( $this->conns as $poolConnsByServer ) {
1669 foreach ( $poolConnsByServer as $serverIndex => $serverConns ) {
1670 if ( $serverIndex === ServerInfo::WRITER_INDEX ) {
1671 continue; // skip primary
1672 }
1673 foreach ( $serverConns as $conn ) {
1674 $conn->flushSnapshot( $fname );
1675 }
1676 }
1677 }
1678 }
1679
1680 public function flushPrimarySnapshots( $fname = __METHOD__ ) {
1681 foreach ( $this->getOpenPrimaryConnections() as $conn ) {
1682 $conn->flushSnapshot( $fname );
1683 }
1684 }
1685
1686 public function hasPrimaryConnection() {
1687 return (bool)$this->getAnyOpenConnection( ServerInfo::WRITER_INDEX );
1688 }
1689
1690 public function hasPrimaryChanges() {
1691 foreach ( $this->getOpenPrimaryConnections() as $conn ) {
1692 if ( $conn->writesOrCallbacksPending() ) {
1693 return true;
1694 }
1695 }
1696
1697 return false;
1698 }
1699
1700 public function lastPrimaryChangeTimestamp() {
1701 $lastTime = false;
1702 foreach ( $this->getOpenPrimaryConnections() as $conn ) {
1703 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1704 }
1705
1706 return $lastTime;
1707 }
1708
1709 public function hasOrMadeRecentPrimaryChanges( $age = null ) {
1710 $age ??= self::MAX_WAIT_DEFAULT;
1711
1712 return ( $this->hasPrimaryChanges()
1713 || $this->lastPrimaryChangeTimestamp() > microtime( true ) - $age );
1714 }
1715
1716 public function pendingPrimaryChangeCallers() {
1717 $fnames = [];
1718 foreach ( $this->getOpenPrimaryConnections() as $conn ) {
1719 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1720 }
1721
1722 return $fnames;
1723 }
1724
1725 public function explicitTrxActive() {
1726 foreach ( $this->getOpenPrimaryConnections() as $conn ) {
1727 if ( $conn->explicitTrxActive() ) {
1728 return true;
1729 }
1730 }
1731 return false;
1732 }
1733
1734 private function setLaggedReplicaMode(): void {
1735 $this->laggedReplicaMode = true;
1736 $this->logger->warning( __METHOD__ . ": setting lagged replica mode" );
1737 }
1738
1739 public function laggedReplicaUsed() {
1740 return $this->laggedReplicaMode;
1741 }
1742
1743 public function getReadOnlyReason() {
1744 if ( $this->readOnlyReason !== false ) {
1745 return $this->readOnlyReason;
1746 } elseif ( $this->isPrimaryRunningReadOnly() ) {
1747 return 'The primary database server is running in read-only mode.';
1748 }
1749
1750 return false;
1751 }
1752
1753 /**
1754 * @note This method suppresses DBError exceptions in order to avoid severe downtime
1755 * @param IDatabaseForOwner|null $conn Recently acquired primary connection; null if not applicable
1756 * @return bool Whether the entire primary DB server or the local domain DB is read-only
1757 */
1758 private function isPrimaryRunningReadOnly( ?IDatabaseForOwner $conn = null ) {
1759 // Context will often be HTTP GET/HEAD; heavily cache the results
1760 return (bool)$this->wanCache->getWithSetCallback(
1761 // Note that table prefixes are not related to server-side read-only mode
1762 $this->wanCache->makeGlobalKey(
1763 'rdbms-server-readonly',
1764 $this->serverInfo->getPrimaryServerName()
1765 ),
1766 self::TTL_CACHE_READONLY,
1767 function ( $oldValue ) use ( $conn ) {
1768 $scope = $this->trxProfiler->silenceForScope();
1769 $conn ??= $this->getServerConnection(
1770 ServerInfo::WRITER_INDEX,
1771 self::DOMAIN_ANY,
1772 self::CONN_SILENCE_ERRORS
1773 );
1774 if ( $conn ) {
1775 try {
1776 $value = (int)$conn->serverIsReadOnly();
1777 } catch ( DBError $e ) {
1778 $value = is_int( $oldValue ) ? $oldValue : 0;
1779 }
1780 } else {
1781 $value = 0;
1782 }
1783 ScopedCallback::consume( $scope );
1784
1785 return $value;
1786 },
1787 [
1788 'busyValue' => 0,
1789 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1790 ]
1791 );
1792 }
1793
1794 public function pingAll() {
1795 $success = true;
1796 foreach ( $this->getOpenConnections() as $conn ) {
1797 if ( !$conn->ping() ) {
1798 $success = false;
1799 }
1800 }
1801
1802 return $success;
1803 }
1804
1805 /**
1806 * Get all open connections
1807 * @return \Generator|Database[]
1808 */
1809 private function getOpenConnections() {
1810 foreach ( $this->conns as $poolConnsByServer ) {
1811 foreach ( $poolConnsByServer as $serverConns ) {
1812 foreach ( $serverConns as $conn ) {
1813 yield $conn;
1814 }
1815 }
1816 }
1817 }
1818
1819 /**
1820 * Get all open primary connections
1821 * @return \Generator|Database[]
1822 */
1823 private function getOpenPrimaryConnections() {
1824 foreach ( $this->conns as $poolConnsByServer ) {
1825 /** @var IDatabaseForOwner $conn */
1826 foreach ( ( $poolConnsByServer[ServerInfo::WRITER_INDEX] ?? [] ) as $conn ) {
1827 yield $conn;
1828 }
1829 }
1830 }
1831
1832 public function getMaxLag() {
1833 $host = '';
1834 $maxLag = -1;
1835 $maxIndex = 0;
1836
1837 if ( $this->serverInfo->hasReplicaServers() ) {
1838 $lagTimes = $this->getLagTimes();
1839 foreach ( $lagTimes as $i => $lag ) {
1840 // Allowing the value to be unset due to stale cache (T361824)
1841 $load = $this->groupLoads[self::GROUP_GENERIC][$i] ?? 0;
1842 if ( $load > 0 && $lag > $maxLag ) {
1843 $maxLag = $lag;
1844 $host = $this->serverInfo->getServerInfoStrict( $i, 'host' );
1845 $maxIndex = $i;
1846 }
1847 }
1848 }
1849
1850 return [ $host, $maxLag, $maxIndex ];
1851 }
1852
1853 public function getLagTimes() {
1854 if ( !$this->hasReplicaServers() ) {
1855 return [ ServerInfo::WRITER_INDEX => 0 ]; // no replication = no lag
1856 }
1857 $fname = __METHOD__;
1858 return $this->wanCache->getWithSetCallback(
1859 $this->wanCache->makeGlobalKey( 'rdbms-lags', $this->getClusterName() ),
1860 // Add jitter to avoid stampede
1861 10 + mt_rand( 1, 10 ),
1862 function () use ( $fname ) {
1863 $lags = [];
1864 foreach ( $this->serverInfo->getStreamingReplicaIndexes() as $i ) {
1865 $conn = $this->getServerConnection(
1866 $i,
1867 self::DOMAIN_ANY,
1868 self::CONN_SILENCE_ERRORS | self::CONN_UNTRACKED_GAUGE
1869 );
1870 if ( $conn ) {
1871 $lags[$i] = $conn->getLag();
1872 $conn->close( $fname );
1873 } else {
1874 $lags[$i] = false;
1875 }
1876 }
1877 return $lags;
1878 },
1879 [ 'lockTSE' => 30 ]
1880 );
1881 }
1882
1883 public function waitForPrimaryPos( IDatabase $conn ) {
1884 if ( $conn->getLBInfo( self::INFO_SERVER_INDEX ) === ServerInfo::WRITER_INDEX ) {
1885 return true; // not a replica DB server
1886 }
1887
1888 // Get the current primary DB position, opening a connection only if needed
1889 $flags = self::CONN_SILENCE_ERRORS;
1890 $primaryConn = $this->getAnyOpenConnection( ServerInfo::WRITER_INDEX, $flags );
1891 if ( $primaryConn ) {
1892 $pos = $primaryConn->getPrimaryPos();
1893 } else {
1894 $primaryConn = $this->getServerConnection( ServerInfo::WRITER_INDEX, self::DOMAIN_ANY, $flags );
1895 if ( !$primaryConn ) {
1896 throw new DBReplicationWaitError(
1897 null,
1898 "Could not obtain a primary database connection to get the position"
1899 );
1900 }
1901 $pos = $primaryConn->getPrimaryPos();
1902 $this->closeConnection( $primaryConn );
1903 }
1904
1905 if ( $pos instanceof DBPrimaryPos && $conn instanceof IDatabaseForOwner ) {
1906 $this->logger->debug( __METHOD__ . ': waiting' );
1907 $result = $conn->primaryPosWait( $pos, self::MAX_WAIT_DEFAULT );
1908 $ok = ( $result !== null && $result != -1 );
1909 if ( $ok ) {
1910 $this->logger->debug( __METHOD__ . ': done waiting (success)' );
1911 } else {
1912 $this->logger->debug( __METHOD__ . ': done waiting (failure)' );
1913 }
1914 } else {
1915 $ok = false; // something is misconfigured
1916 $this->logger->error(
1917 __METHOD__ . ': could not get primary pos for {db_server}',
1918 $this->getConnLogContext( $conn, [ 'exception' => new RuntimeException() ] )
1919 );
1920 }
1921
1922 return $ok;
1923 }
1924
1925 public function setTransactionListener( $name, ?callable $callback = null ) {
1926 if ( $callback ) {
1927 $this->trxRecurringCallbacks[$name] = $callback;
1928 } else {
1929 unset( $this->trxRecurringCallbacks[$name] );
1930 }
1931 foreach ( $this->getOpenPrimaryConnections() as $conn ) {
1932 $conn->setTransactionListener( $name, $callback );
1933 }
1934 }
1935
1936 public function setTableAliases( array $aliases ) {
1937 $this->tableAliases = $aliases;
1938 }
1939
1940 public function setIndexAliases( array $aliases ) {
1941 $this->indexAliases = $aliases;
1942 }
1943
1944 public function setDomainAliases( array $aliases ) {
1945 $this->domainAliases = $aliases;
1946 }
1947
1948 public function setLocalDomainPrefix( $prefix ) {
1949 $oldLocalDomain = $this->localDomain;
1950 $this->localDomain = new DatabaseDomain(
1951 $this->localDomain->getDatabase(),
1952 $this->localDomain->getSchema(),
1953 $prefix
1954 );
1955
1956 // Update the prefix for existing connections.
1957 // Existing DBConnRef handles will not be affected.
1958 foreach ( $this->getOpenConnections() as $conn ) {
1959 if ( $oldLocalDomain->equals( $conn->getDomainID() ) ) {
1960 $conn->tablePrefix( $prefix );
1961 }
1962 }
1963 }
1964
1965 public function redefineLocalDomain( $domain ) {
1966 $this->closeAll( __METHOD__ );
1967 $this->localDomain = DatabaseDomain::newFromId( $domain );
1968 }
1969
1970 public function setTempTablesOnlyMode( $value, $domain ) {
1971 $old = $this->tempTablesOnlyMode[$domain] ?? false;
1972 if ( $value ) {
1973 $this->tempTablesOnlyMode[$domain] = true;
1974 } else {
1975 unset( $this->tempTablesOnlyMode[$domain] );
1976 }
1977
1978 return $old;
1979 }
1980
1981 /**
1982 * @param IDatabase $conn
1983 * @return string Description of a connection handle for log messages
1984 * @throws InvalidArgumentException
1985 */
1986 private function stringifyConn( IDatabase $conn ) {
1987 return $conn->getLBInfo( self::INFO_SERVER_INDEX ) . '/' . $conn->getDomainID();
1988 }
1989
1990 /**
1991 * @param int $flags A bitfield of flags
1992 * @param int $bit Bit flag constant
1993 * @return bool Whether the bit field has the specified bit flag set
1994 */
1995 private function fieldHasBit( int $flags, int $bit ) {
1996 return ( ( $flags & $bit ) === $bit );
1997 }
1998
1999 /**
2000 * Create a log context to pass to PSR-3 logger functions.
2001 *
2002 * @param IDatabase $conn
2003 * @param array $extras Additional data to add to context
2004 * @return array
2005 */
2006 protected function getConnLogContext( IDatabase $conn, array $extras = [] ) {
2007 return array_merge(
2008 [
2009 'db_server' => $conn->getServerName(),
2010 'db_domain' => $conn->getDomainID()
2011 ],
2012 $extras
2013 );
2014 }
2015
2016 /**
2017 * @param float|null &$time Mock UNIX timestamp for testing
2018 * @internal
2019 * @codeCoverageIgnore
2020 */
2021 public function setMockTime( &$time ) {
2022 $this->loadMonitor->setMockTime( $time );
2023 }
2024 }