Merge "rdbms: add setTempTablesOnlyMode() to suppress CONN_TRX_AUTOCOMMIT during...
[lhc/web/wiklou.git] / includes / libs / rdbms / loadbalancer / LoadBalancer.php
1 <?php
2 /**
3 * Database load balancing manager
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22 namespace Wikimedia\Rdbms;
23
24 use Psr\Log\LoggerInterface;
25 use Psr\Log\NullLogger;
26 use Wikimedia\ScopedCallback;
27 use BagOStuff;
28 use EmptyBagOStuff;
29 use WANObjectCache;
30 use ArrayUtils;
31 use LogicException;
32 use UnexpectedValueException;
33 use InvalidArgumentException;
34 use RuntimeException;
35 use Exception;
36
37 /**
38 * Database connection, tracking, load balancing, and transaction manager for a cluster
39 *
40 * @ingroup Database
41 */
42 class LoadBalancer implements ILoadBalancer {
43 /** @var ILoadMonitor */
44 private $loadMonitor;
45 /** @var callable|null Callback to run before the first connection attempt */
46 private $chronologyCallback;
47 /** @var BagOStuff */
48 private $srvCache;
49 /** @var WANObjectCache */
50 private $wanCache;
51 /** @var mixed Class name or object With profileIn/profileOut methods */
52 private $profiler;
53 /** @var TransactionProfiler */
54 private $trxProfiler;
55 /** @var LoggerInterface */
56 private $replLogger;
57 /** @var LoggerInterface */
58 private $connLogger;
59 /** @var LoggerInterface */
60 private $queryLogger;
61 /** @var LoggerInterface */
62 private $perfLogger;
63 /** @var callable Exception logger */
64 private $errorLogger;
65 /** @var callable Deprecation logger */
66 private $deprecationLogger;
67
68 /** @var DatabaseDomain Local DB domain ID and default for selectDB() calls */
69 private $localDomain;
70
71 /** @var Database[][][] Map of (connection category => server index => IDatabase[]) */
72 private $conns;
73
74 /** @var array[] Map of (server index => server config array) */
75 private $servers;
76 /** @var array[] Map of (group => server index => weight) */
77 private $groupLoads;
78 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
79 private $allowLagged;
80 /** @var int Seconds to spend waiting on replica DB lag to resolve */
81 private $waitTimeout;
82 /** @var array The LoadMonitor configuration */
83 private $loadMonitorConfig;
84 /** @var string Alternate local DB domain instead of DatabaseDomain::getId() */
85 private $localDomainIdAlias;
86 /** @var int Amount of replication lag, in seconds, that is considered "high" */
87 private $maxLag;
88 /** @var string|null Default query group to use with getConnection() */
89 private $defaultGroup;
90
91 /** @var string Current server name */
92 private $hostname;
93 /** @var bool Whether this PHP instance is for a CLI script */
94 private $cliMode;
95 /** @var string Agent name for query profiling */
96 private $agent;
97
98 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
99 private $tableAliases = [];
100 /** @var string[] Map of (index alias => index) */
101 private $indexAliases = [];
102 /** @var array[] Map of (name => callable) */
103 private $trxRecurringCallbacks = [];
104 /** @var bool[] Map of (domain => whether to use "temp tables only" mode) */
105 private $tempTablesOnlyMode = [];
106
107 /** @var Database Connection handle that caused a problem */
108 private $errorConnection;
109 /** @var int[] The group replica server indexes keyed by group */
110 private $readIndexByGroup = [];
111 /** @var bool|DBMasterPos Replication sync position or false if not set */
112 private $waitForPos;
113 /** @var bool Whether the generic reader fell back to a lagged replica DB */
114 private $laggedReplicaMode = false;
115 /** @var string The last DB selection or connection error */
116 private $lastError = 'Unknown error';
117 /** @var string|bool Reason this instance is read-only or false if not */
118 private $readOnlyReason = false;
119 /** @var int Total number of new connections ever made with this instance */
120 private $connectionCounter = 0;
121 /** @var bool */
122 private $disabled = false;
123 /** @var bool Whether any connection has been attempted yet */
124 private $connectionAttempted = false;
125
126 /** var int An identifier for this class instance */
127 private $id;
128 /** @var int|null Integer ID of the managing LBFactory instance or null if none */
129 private $ownerId;
130 /** @var string|bool Explicit DBO_TRX transaction round active or false if none */
131 private $trxRoundId = false;
132 /** @var string Stage of the current transaction round in the transaction round life-cycle */
133 private $trxRoundStage = self::ROUND_CURSORY;
134
135 /** @var int Warn when this many connection are held */
136 const CONN_HELD_WARN_THRESHOLD = 10;
137
138 /** @var int Default 'maxLag' when unspecified */
139 const MAX_LAG_DEFAULT = 6;
140 /** @var int Default 'waitTimeout' when unspecified */
141 const MAX_WAIT_DEFAULT = 10;
142 /** @var int Seconds to cache master DB server read-only status */
143 const TTL_CACHE_READONLY = 5;
144
145 const KEY_LOCAL = 'local';
146 const KEY_FOREIGN_FREE = 'foreignFree';
147 const KEY_FOREIGN_INUSE = 'foreignInUse';
148
149 const KEY_LOCAL_NOROUND = 'localAutoCommit';
150 const KEY_FOREIGN_FREE_NOROUND = 'foreignFreeAutoCommit';
151 const KEY_FOREIGN_INUSE_NOROUND = 'foreignInUseAutoCommit';
152
153 /** @var string Transaction round, explicit or implicit, has not finished writing */
154 const ROUND_CURSORY = 'cursory';
155 /** @var string Transaction round writes are complete and ready for pre-commit checks */
156 const ROUND_FINALIZED = 'finalized';
157 /** @var string Transaction round passed final pre-commit checks */
158 const ROUND_APPROVED = 'approved';
159 /** @var string Transaction round was committed and post-commit callbacks must be run */
160 const ROUND_COMMIT_CALLBACKS = 'commit-callbacks';
161 /** @var string Transaction round was rolled back and post-rollback callbacks must be run */
162 const ROUND_ROLLBACK_CALLBACKS = 'rollback-callbacks';
163 /** @var string Transaction round encountered an error */
164 const ROUND_ERROR = 'error';
165
166 public function __construct( array $params ) {
167 if ( !isset( $params['servers'] ) || !count( $params['servers'] ) ) {
168 throw new InvalidArgumentException( 'Missing or empty "servers" parameter' );
169 }
170
171 $listKey = -1;
172 $this->servers = [];
173 $this->groupLoads = [ self::GROUP_GENERIC => [] ];
174 foreach ( $params['servers'] as $i => $server ) {
175 if ( ++$listKey !== $i ) {
176 throw new UnexpectedValueException( 'List expected for "servers" parameter' );
177 }
178 $this->servers[$i] = $server;
179 foreach ( ( $server['groupLoads'] ?? [] ) as $group => $ratio ) {
180 $this->groupLoads[$group][$i] = $ratio;
181 }
182 $this->groupLoads[self::GROUP_GENERIC][$i] = $server['load'];
183 }
184
185 $localDomain = isset( $params['localDomain'] )
186 ? DatabaseDomain::newFromId( $params['localDomain'] )
187 : DatabaseDomain::newUnspecified();
188 $this->setLocalDomain( $localDomain );
189
190 $this->waitTimeout = $params['waitTimeout'] ?? self::MAX_WAIT_DEFAULT;
191
192 $this->conns = self::newTrackedConnectionsArray();
193 $this->waitForPos = false;
194 $this->allowLagged = false;
195
196 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
197 $this->readOnlyReason = $params['readOnlyReason'];
198 }
199
200 $this->maxLag = $params['maxLag'] ?? self::MAX_LAG_DEFAULT;
201
202 $this->loadMonitorConfig = $params['loadMonitor'] ?? [ 'class' => 'LoadMonitorNull' ];
203 $this->loadMonitorConfig += [ 'lagWarnThreshold' => $this->maxLag ];
204
205 $this->srvCache = $params['srvCache'] ?? new EmptyBagOStuff();
206 $this->wanCache = $params['wanCache'] ?? WANObjectCache::newEmpty();
207 $this->profiler = $params['profiler'] ?? null;
208 $this->trxProfiler = $params['trxProfiler'] ?? new TransactionProfiler();
209
210 $this->errorLogger = $params['errorLogger'] ?? function ( Exception $e ) {
211 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
212 };
213 $this->deprecationLogger = $params['deprecationLogger'] ?? function ( $msg ) {
214 trigger_error( $msg, E_USER_DEPRECATED );
215 };
216
217 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
218 $this->$key = $params[$key] ?? new NullLogger();
219 }
220
221 $this->hostname = $params['hostname'] ?? ( gethostname() ?: 'unknown' );
222 $this->cliMode = $params['cliMode'] ?? ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' );
223 $this->agent = $params['agent'] ?? '';
224
225 if ( isset( $params['chronologyCallback'] ) ) {
226 $this->chronologyCallback = $params['chronologyCallback'];
227 }
228
229 if ( isset( $params['roundStage'] ) ) {
230 if ( $params['roundStage'] === self::STAGE_POSTCOMMIT_CALLBACKS ) {
231 $this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS;
232 } elseif ( $params['roundStage'] === self::STAGE_POSTROLLBACK_CALLBACKS ) {
233 $this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS;
234 }
235 }
236
237 $group = $params['defaultGroup'] ?? self::GROUP_GENERIC;
238 $this->defaultGroup = isset( $this->groupLoads[$group] ) ? $group : self::GROUP_GENERIC;
239
240 static $nextId;
241 $this->id = $nextId = ( is_int( $nextId ) ? $nextId++ : mt_rand() );
242 $this->ownerId = $params['ownerId'] ?? null;
243 }
244
245 private static function newTrackedConnectionsArray() {
246 return [
247 // Connection were transaction rounds may be applied
248 self::KEY_LOCAL => [],
249 self::KEY_FOREIGN_INUSE => [],
250 self::KEY_FOREIGN_FREE => [],
251 // Auto-committing counterpart connections that ignore transaction rounds
252 self::KEY_LOCAL_NOROUND => [],
253 self::KEY_FOREIGN_INUSE_NOROUND => [],
254 self::KEY_FOREIGN_FREE_NOROUND => []
255 ];
256 }
257
258 public function getLocalDomainID() {
259 return $this->localDomain->getId();
260 }
261
262 public function resolveDomainID( $domain ) {
263 if ( $domain === $this->localDomainIdAlias || $domain === false ) {
264 // Local connection requested via some backwards-compatibility domain alias
265 return $this->getLocalDomainID();
266 }
267
268 return (string)$domain;
269 }
270
271 /**
272 * Resolve $groups into a list of query groups defining as having database servers
273 *
274 * @param string[]|string|bool $groups Query group(s) in preference order, [], or false
275 * @param int $i Specific server index or DB_MASTER/DB_REPLICA
276 * @return string[] Non-empty group list in preference order with the default group appended
277 */
278 private function resolveGroups( $groups, $i ) {
279 // If a specific replica server was specified, then $groups makes no sense
280 if ( $i > 0 && $groups !== [] && $groups !== false ) {
281 $list = implode( ', ', (array)$groups );
282 throw new LogicException( "Query group(s) ($list) given with server index (#$i)" );
283 }
284
285 if ( $groups === [] || $groups === false || $groups === $this->defaultGroup ) {
286 $resolvedGroups = [ $this->defaultGroup ]; // common case
287 } elseif ( is_string( $groups ) && isset( $this->groupLoads[$groups] ) ) {
288 $resolvedGroups = [ $groups, $this->defaultGroup ];
289 } elseif ( is_array( $groups ) ) {
290 $resolvedGroups = array_keys( array_flip( $groups ) + [ self::GROUP_GENERIC => 1 ] );
291 } else {
292 $resolvedGroups = [ $this->defaultGroup ];
293 }
294
295 return $resolvedGroups;
296 }
297
298 /**
299 * @param int $flags Bitfield of class CONN_* constants
300 * @param int $i Specific server index or DB_MASTER/DB_REPLICA
301 * @param string $domain Database domain
302 * @return int Sanitized bitfield
303 */
304 private function sanitizeConnectionFlags( $flags, $i, $domain ) {
305 // Whether an outside caller is explicitly requesting the master database server
306 if ( $i === self::DB_MASTER || $i === $this->getWriterIndex() ) {
307 $flags |= self::CONN_INTENT_WRITABLE;
308 }
309
310 if ( ( $flags & self::CONN_TRX_AUTOCOMMIT ) == self::CONN_TRX_AUTOCOMMIT ) {
311 // Callers use CONN_TRX_AUTOCOMMIT to bypass REPEATABLE-READ staleness without
312 // resorting to row locks (e.g. FOR UPDATE) or to make small out-of-band commits
313 // during larger transactions. This is useful for avoiding lock contention.
314
315 // Master DB server attributes (should match those of the replica DB servers)
316 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
317 if ( $attributes[Database::ATTR_DB_LEVEL_LOCKING] ) {
318 // The RDBMS does not support concurrent writes (e.g. SQLite), so attempts
319 // to use separate connections would just cause self-deadlocks. Note that
320 // REPEATABLE-READ staleness is not an issue since DB-level locking means
321 // that transactions are Strict Serializable anyway.
322 $flags &= ~self::CONN_TRX_AUTOCOMMIT;
323 $type = $this->getServerType( $this->getWriterIndex() );
324 $this->connLogger->info( __METHOD__ . ": CONN_TRX_AUTOCOMMIT disallowed ($type)" );
325 } elseif ( isset( $this->tempTablesOnlyMode[$domain] ) ) {
326 // T202116: integration tests are active and queries should be all be using
327 // temporary clone tables (via prefix). Such tables are not visible accross
328 // different connections nor can there be REPEATABLE-READ snapshot staleness,
329 // so use the same connection for everything.
330 $flags &= ~self::CONN_TRX_AUTOCOMMIT;
331 }
332 }
333
334 return $flags;
335 }
336
337 /**
338 * @param IDatabase $conn
339 * @param int $flags
340 * @throws DBUnexpectedError
341 */
342 private function enforceConnectionFlags( IDatabase $conn, $flags ) {
343 if ( ( $flags & self::CONN_TRX_AUTOCOMMIT ) == self::CONN_TRX_AUTOCOMMIT ) {
344 if ( $conn->trxLevel() ) { // sanity
345 throw new DBUnexpectedError(
346 $conn,
347 'Handle requested with CONN_TRX_AUTOCOMMIT yet it has a transaction'
348 );
349 }
350
351 $conn->clearFlag( $conn::DBO_TRX ); // auto-commit mode
352 }
353 }
354
355 /**
356 * Get a LoadMonitor instance
357 *
358 * @return ILoadMonitor
359 */
360 private function getLoadMonitor() {
361 if ( !isset( $this->loadMonitor ) ) {
362 $compat = [
363 'LoadMonitor' => LoadMonitor::class,
364 'LoadMonitorNull' => LoadMonitorNull::class,
365 'LoadMonitorMySQL' => LoadMonitorMySQL::class,
366 ];
367
368 $class = $this->loadMonitorConfig['class'];
369 if ( isset( $compat[$class] ) ) {
370 $class = $compat[$class];
371 }
372
373 $this->loadMonitor = new $class(
374 $this, $this->srvCache, $this->wanCache, $this->loadMonitorConfig );
375 $this->loadMonitor->setLogger( $this->replLogger );
376 }
377
378 return $this->loadMonitor;
379 }
380
381 /**
382 * @param array $loads
383 * @param bool|string $domain Domain to get non-lagged for
384 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
385 * @return bool|int|string
386 */
387 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF ) {
388 $lags = $this->getLagTimes( $domain );
389
390 # Unset excessively lagged servers
391 foreach ( $lags as $i => $lag ) {
392 if ( $i !== $this->getWriterIndex() ) {
393 # How much lag this server nominally is allowed to have
394 $maxServerLag = $this->servers[$i]['max lag'] ?? $this->maxLag; // default
395 # Constrain that futher by $maxLag argument
396 $maxServerLag = min( $maxServerLag, $maxLag );
397
398 $host = $this->getServerName( $i );
399 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
400 $this->replLogger->debug(
401 __METHOD__ .
402 ": server {host} is not replicating?", [ 'host' => $host ] );
403 unset( $loads[$i] );
404 } elseif ( $lag > $maxServerLag ) {
405 $this->replLogger->debug(
406 __METHOD__ .
407 ": server {host} has {lag} seconds of lag (>= {maxlag})",
408 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
409 );
410 unset( $loads[$i] );
411 }
412 }
413 }
414
415 # Find out if all the replica DBs with non-zero load are lagged
416 $sum = 0;
417 foreach ( $loads as $load ) {
418 $sum += $load;
419 }
420 if ( $sum == 0 ) {
421 # No appropriate DB servers except maybe the master and some replica DBs with zero load
422 # Do NOT use the master
423 # Instead, this function will return false, triggering read-only mode,
424 # and a lagged replica DB will be used instead.
425 return false;
426 }
427
428 if ( count( $loads ) == 0 ) {
429 return false;
430 }
431
432 # Return a random representative of the remainder
433 return ArrayUtils::pickRandom( $loads );
434 }
435
436 /**
437 * Get the server index to use for a specified server index and query group list
438 *
439 * @param int $i Specific server index or DB_MASTER/DB_REPLICA
440 * @param string[] $groups Non-empty query group list in preference order
441 * @param string|bool $domain
442 * @return int A specific server index (replica DBs are checked for connectivity)
443 */
444 private function getConnectionIndex( $i, array $groups, $domain ) {
445 if ( $i === self::DB_MASTER ) {
446 $i = $this->getWriterIndex();
447 } elseif ( $i === self::DB_REPLICA ) {
448 foreach ( $groups as $group ) {
449 $groupIndex = $this->getReaderIndex( $group, $domain );
450 if ( $groupIndex !== false ) {
451 $i = $groupIndex; // group connection succeeded
452 break;
453 }
454 }
455 } elseif ( !isset( $this->servers[$i] ) ) {
456 throw new UnexpectedValueException( "Invalid server index index #$i" );
457 }
458
459 if ( $i === self::DB_REPLICA ) {
460 $this->lastError = 'Unknown error'; // set here in case of worse failure
461 $this->lastError = 'No working replica DB server: ' . $this->lastError;
462 $this->reportConnectionError();
463 return null; // unreachable due to exception
464 }
465
466 return $i;
467 }
468
469 public function getReaderIndex( $group = false, $domain = false ) {
470 if ( $this->getServerCount() == 1 ) {
471 // Skip the load balancing if there's only one server
472 return $this->getWriterIndex();
473 }
474
475 $group = is_string( $group ) ? $group : self::GROUP_GENERIC;
476
477 $index = $this->getExistingReaderIndex( $group );
478 if ( $index >= 0 ) {
479 // A reader index was already selected and "waitForPos" was handled
480 return $index;
481 }
482
483 // Use the server weight array for this load group
484 if ( isset( $this->groupLoads[$group] ) ) {
485 $loads = $this->groupLoads[$group];
486 } else {
487 $this->connLogger->info( __METHOD__ . ": no loads for group $group" );
488
489 return false;
490 }
491
492 // Scale the configured load ratios according to each server's load and state
493 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
494
495 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
496 $this->lazyLoadReplicationPositions(); // optimizes server candidate selection
497 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
498 if ( $i === false ) {
499 // DB connection unsuccessful
500 return false;
501 }
502
503 // If data seen by queries is expected to reflect the transactions committed as of
504 // or after a given replication position then wait for the DB to apply those changes
505 if ( $this->waitForPos && $i !== $this->getWriterIndex() && !$this->doWait( $i ) ) {
506 // Data will be outdated compared to what was expected
507 $laggedReplicaMode = true;
508 }
509
510 // Cache the reader index for future DB_REPLICA handles
511 $this->setExistingReaderIndex( $group, $i );
512 // Record whether the generic reader index is in "lagged replica DB" mode
513 if ( $group === self::GROUP_GENERIC && $laggedReplicaMode ) {
514 $this->laggedReplicaMode = true;
515 }
516
517 $serverName = $this->getServerName( $i );
518 $this->connLogger->debug( __METHOD__ . ": using server $serverName for group '$group'" );
519
520 return $i;
521 }
522
523 /**
524 * Get the server index chosen by the load balancer for use with the given query group
525 *
526 * @param string $group Query group; use false for the generic group
527 * @return int Server index or -1 if none was chosen
528 */
529 protected function getExistingReaderIndex( $group ) {
530 return $this->readIndexByGroup[$group] ?? -1;
531 }
532
533 /**
534 * Set the server index chosen by the load balancer for use with the given query group
535 *
536 * @param string $group Query group; use false for the generic group
537 * @param int $index The index of a specific server
538 */
539 private function setExistingReaderIndex( $group, $index ) {
540 if ( $index < 0 ) {
541 throw new UnexpectedValueException( "Cannot set a negative read server index" );
542 }
543 $this->readIndexByGroup[$group] = $index;
544 }
545
546 /**
547 * @param array $loads List of server weights
548 * @param string|bool $domain
549 * @return array (reader index, lagged replica mode) or (false, false) on failure
550 */
551 private function pickReaderIndex( array $loads, $domain = false ) {
552 if ( $loads === [] ) {
553 throw new InvalidArgumentException( "Server configuration array is empty" );
554 }
555
556 /** @var int|bool $i Index of selected server */
557 $i = false;
558 /** @var bool $laggedReplicaMode Whether server is considered lagged */
559 $laggedReplicaMode = false;
560
561 // Quickly look through the available servers for a server that meets criteria...
562 $currentLoads = $loads;
563 while ( count( $currentLoads ) ) {
564 if ( $this->allowLagged || $laggedReplicaMode ) {
565 $i = ArrayUtils::pickRandom( $currentLoads );
566 } else {
567 $i = false;
568 if ( $this->waitForPos && $this->waitForPos->asOfTime() ) {
569 $this->replLogger->debug( __METHOD__ . ": replication positions detected" );
570 // "chronologyCallback" sets "waitForPos" for session consistency.
571 // This triggers doWait() after connect, so it's especially good to
572 // avoid lagged servers so as to avoid excessive delay in that method.
573 $ago = microtime( true ) - $this->waitForPos->asOfTime();
574 // Aim for <= 1 second of waiting (being too picky can backfire)
575 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago + 1 );
576 }
577 if ( $i === false ) {
578 // Any server with less lag than it's 'max lag' param is preferable
579 $i = $this->getRandomNonLagged( $currentLoads, $domain );
580 }
581 if ( $i === false && count( $currentLoads ) ) {
582 // All replica DBs lagged. Switch to read-only mode
583 $this->replLogger->error(
584 __METHOD__ . ": all replica DBs lagged. Switch to read-only mode" );
585 $i = ArrayUtils::pickRandom( $currentLoads );
586 $laggedReplicaMode = true;
587 }
588 }
589
590 if ( $i === false ) {
591 // pickRandom() returned false.
592 // This is permanent and means the configuration or the load monitor
593 // wants us to return false.
594 $this->connLogger->debug( __METHOD__ . ": pickRandom() returned false" );
595
596 return [ false, false ];
597 }
598
599 $serverName = $this->getServerName( $i );
600 $this->connLogger->debug( __METHOD__ . ": Using reader #$i: $serverName..." );
601
602 // Get a connection to this server without triggering other server connections
603 $conn = $this->getServerConnection( $i, $domain, self::CONN_SILENCE_ERRORS );
604 if ( !$conn ) {
605 $this->connLogger->warning( __METHOD__ . ": Failed connecting to $i/$domain" );
606 unset( $currentLoads[$i] ); // avoid this server next iteration
607 $i = false;
608 continue;
609 }
610
611 // Decrement reference counter, we are finished with this connection.
612 // It will be incremented for the caller later.
613 if ( $domain !== false ) {
614 $this->reuseConnection( $conn );
615 }
616
617 // Return this server
618 break;
619 }
620
621 // If all servers were down, quit now
622 if ( $currentLoads === [] ) {
623 $this->connLogger->error( __METHOD__ . ": all servers down" );
624 }
625
626 return [ $i, $laggedReplicaMode ];
627 }
628
629 public function waitFor( $pos ) {
630 $oldPos = $this->waitForPos;
631 try {
632 $this->waitForPos = $pos;
633 // If a generic reader connection was already established, then wait now
634 $i = $this->getExistingReaderIndex( self::GROUP_GENERIC );
635 if ( $i > 0 && !$this->doWait( $i ) ) {
636 $this->laggedReplicaMode = true;
637 }
638 // Otherwise, wait until a connection is established in getReaderIndex()
639 } finally {
640 // Restore the older position if it was higher since this is used for lag-protection
641 $this->setWaitForPositionIfHigher( $oldPos );
642 }
643 }
644
645 public function waitForOne( $pos, $timeout = null ) {
646 $oldPos = $this->waitForPos;
647 try {
648 $this->waitForPos = $pos;
649
650 $i = $this->getExistingReaderIndex( self::GROUP_GENERIC );
651 if ( $i <= 0 ) {
652 // Pick a generic replica DB if there isn't one yet
653 $readLoads = $this->groupLoads[self::GROUP_GENERIC];
654 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
655 $readLoads = array_filter( $readLoads ); // with non-zero load
656 $i = ArrayUtils::pickRandom( $readLoads );
657 }
658
659 if ( $i > 0 ) {
660 $ok = $this->doWait( $i, true, $timeout );
661 } else {
662 $ok = true; // no applicable loads
663 }
664 } finally {
665 // Restore the old position; this is used for throttling, not lag-protection
666 $this->waitForPos = $oldPos;
667 }
668
669 return $ok;
670 }
671
672 public function waitForAll( $pos, $timeout = null ) {
673 $timeout = $timeout ?: $this->waitTimeout;
674
675 $oldPos = $this->waitForPos;
676 try {
677 $this->waitForPos = $pos;
678 $serverCount = $this->getServerCount();
679
680 $ok = true;
681 for ( $i = 1; $i < $serverCount; $i++ ) {
682 if ( $this->serverHasLoadInAnyGroup( $i ) ) {
683 $start = microtime( true );
684 $ok = $this->doWait( $i, true, $timeout ) && $ok;
685 $timeout -= intval( microtime( true ) - $start );
686 if ( $timeout <= 0 ) {
687 break; // timeout reached
688 }
689 }
690 }
691 } finally {
692 // Restore the old position; this is used for throttling, not lag-protection
693 $this->waitForPos = $oldPos;
694 }
695
696 return $ok;
697 }
698
699 /**
700 * @param int $i Specific server index
701 * @return bool
702 */
703 private function serverHasLoadInAnyGroup( $i ) {
704 foreach ( $this->groupLoads as $loadsByIndex ) {
705 if ( ( $loadsByIndex[$i] ?? 0 ) > 0 ) {
706 return true;
707 }
708 }
709
710 return false;
711 }
712
713 /**
714 * @param DBMasterPos|bool $pos
715 */
716 private function setWaitForPositionIfHigher( $pos ) {
717 if ( !$pos ) {
718 return;
719 }
720
721 if ( !$this->waitForPos || $pos->hasReached( $this->waitForPos ) ) {
722 $this->waitForPos = $pos;
723 }
724 }
725
726 public function getAnyOpenConnection( $i, $flags = 0 ) {
727 $i = ( $i === self::DB_MASTER ) ? $this->getWriterIndex() : $i;
728 // Connection handles required to be in auto-commit mode use a separate connection
729 // pool since the main pool is effected by implicit and explicit transaction rounds
730 $autocommit = ( ( $flags & self::CONN_TRX_AUTOCOMMIT ) == self::CONN_TRX_AUTOCOMMIT );
731
732 $conn = false;
733 foreach ( $this->conns as $connsByServer ) {
734 // Get the connection array server indexes to inspect
735 if ( $i === self::DB_REPLICA ) {
736 $indexes = array_keys( $connsByServer );
737 } else {
738 $indexes = isset( $connsByServer[$i] ) ? [ $i ] : [];
739 }
740
741 foreach ( $indexes as $index ) {
742 $conn = $this->pickAnyOpenConnection( $connsByServer[$index], $autocommit );
743 if ( $conn ) {
744 break;
745 }
746 }
747 }
748
749 if ( $conn ) {
750 $this->enforceConnectionFlags( $conn, $flags );
751 }
752
753 return $conn;
754 }
755
756 /**
757 * @param IDatabase[] $candidateConns
758 * @param bool $autocommit Whether to only look for auto-commit connections
759 * @return IDatabase|false An appropriate open connection or false if none found
760 */
761 private function pickAnyOpenConnection( $candidateConns, $autocommit ) {
762 $conn = false;
763
764 foreach ( $candidateConns as $candidateConn ) {
765 if ( !$candidateConn->isOpen() ) {
766 continue; // some sort of error occured?
767 } elseif (
768 $autocommit &&
769 (
770 // Connection is transaction round aware
771 !$candidateConn->getLBInfo( 'autoCommitOnly' ) ||
772 // Some sort of error left a transaction open?
773 $candidateConn->trxLevel()
774 )
775 ) {
776 continue; // some sort of error left a transaction open?
777 }
778
779 $conn = $candidateConn;
780 }
781
782 return $conn;
783 }
784
785 /**
786 * Wait for a given replica DB to catch up to the master pos stored in "waitForPos"
787 * @param int $index Specific server index
788 * @param bool $open Check the server even if a new connection has to be made
789 * @param int|null $timeout Max seconds to wait; default is "waitTimeout"
790 * @return bool
791 */
792 protected function doWait( $index, $open = false, $timeout = null ) {
793 $timeout = max( 1, intval( $timeout ?: $this->waitTimeout ) );
794
795 // Check if we already know that the DB has reached this point
796 $server = $this->getServerName( $index );
797 $key = $this->srvCache->makeGlobalKey( __CLASS__, 'last-known-pos', $server, 'v1' );
798 /** @var DBMasterPos $knownReachedPos */
799 $knownReachedPos = $this->srvCache->get( $key );
800 if (
801 $knownReachedPos instanceof DBMasterPos &&
802 $knownReachedPos->hasReached( $this->waitForPos )
803 ) {
804 $this->replLogger->debug(
805 __METHOD__ .
806 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
807 [ 'dbserver' => $server ]
808 );
809 return true;
810 }
811
812 // Find a connection to wait on, creating one if needed and allowed
813 $close = false; // close the connection afterwards
814 $flags = self::CONN_SILENCE_ERRORS;
815 $conn = $this->getAnyOpenConnection( $index, $flags );
816 if ( !$conn ) {
817 if ( !$open ) {
818 $this->replLogger->debug(
819 __METHOD__ . ': no connection open for {dbserver}',
820 [ 'dbserver' => $server ]
821 );
822
823 return false;
824 }
825 // Get a connection to this server without triggering other server connections
826 $conn = $this->getServerConnection( $index, self::DOMAIN_ANY, $flags );
827 if ( !$conn ) {
828 $this->replLogger->warning(
829 __METHOD__ . ': failed to connect to {dbserver}',
830 [ 'dbserver' => $server ]
831 );
832
833 return false;
834 }
835 // Avoid connection spam in waitForAll() when connections
836 // are made just for the sake of doing this lag check.
837 $close = true;
838 }
839
840 $this->replLogger->info(
841 __METHOD__ .
842 ': waiting for replica DB {dbserver} to catch up...',
843 [ 'dbserver' => $server ]
844 );
845
846 $result = $conn->masterPosWait( $this->waitForPos, $timeout );
847
848 if ( $result === null ) {
849 $this->replLogger->warning(
850 __METHOD__ . ': Errored out waiting on {host} pos {pos}',
851 [
852 'host' => $server,
853 'pos' => $this->waitForPos,
854 'trace' => ( new RuntimeException() )->getTraceAsString()
855 ]
856 );
857 $ok = false;
858 } elseif ( $result == -1 ) {
859 $this->replLogger->warning(
860 __METHOD__ . ': Timed out waiting on {host} pos {pos}',
861 [
862 'host' => $server,
863 'pos' => $this->waitForPos,
864 'trace' => ( new RuntimeException() )->getTraceAsString()
865 ]
866 );
867 $ok = false;
868 } else {
869 $this->replLogger->debug( __METHOD__ . ": done waiting" );
870 $ok = true;
871 // Remember that the DB reached this point
872 $this->srvCache->set( $key, $this->waitForPos, BagOStuff::TTL_DAY );
873 }
874
875 if ( $close ) {
876 $this->closeConnection( $conn );
877 }
878
879 return $ok;
880 }
881
882 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
883 $domain = $this->resolveDomainID( $domain );
884 $groups = $this->resolveGroups( $groups, $i );
885 $flags = $this->sanitizeConnectionFlags( $flags, $i, $domain );
886 // If given DB_MASTER/DB_REPLICA, resolve it to a specific server index. Resolving
887 // DB_REPLICA might trigger getServerConnection() calls due to the getReaderIndex()
888 // connectivity checks or LoadMonitor::scaleLoads() server state cache regeneration.
889 // The use of getServerConnection() instead of getConnection() avoids infinite loops.
890 $serverIndex = $this->getConnectionIndex( $i, $groups, $domain );
891 // Get an open connection to that server (might trigger a new connection)
892 $conn = $this->getServerConnection( $serverIndex, $domain, $flags );
893 // Set master DB handles as read-only if there is high replication lag
894 if ( $serverIndex === $this->getWriterIndex() && $this->getLaggedReplicaMode( $domain ) ) {
895 $reason = ( $this->getExistingReaderIndex( self::GROUP_GENERIC ) >= 0 )
896 ? 'The database is read-only until replication lag decreases.'
897 : 'The database is read-only until replica database servers becomes reachable.';
898 $conn->setLBInfo( 'readOnlyReason', $reason );
899 }
900
901 return $conn;
902 }
903
904 /**
905 * @param int $i Specific server index
906 * @param string $domain Resolved DB domain
907 * @param int $flags Bitfield of class CONN_* constants
908 * @return IDatabase|bool
909 * @throws InvalidArgumentException When the server index is invalid
910 */
911 public function getServerConnection( $i, $domain, $flags = 0 ) {
912 // Number of connections made before getting the server index and handle
913 $priorConnectionsMade = $this->connectionCounter;
914 // Get an open connection to this server (might trigger a new connection)
915 $conn = $this->localDomain->equals( $domain )
916 ? $this->getLocalConnection( $i, $flags )
917 : $this->getForeignConnection( $i, $domain, $flags );
918 // Throw an error or otherwise bail out if the connection attempt failed
919 if ( !( $conn instanceof IDatabase ) ) {
920 if ( ( $flags & self::CONN_SILENCE_ERRORS ) != self::CONN_SILENCE_ERRORS ) {
921 $this->reportConnectionError();
922 }
923
924 return false;
925 }
926
927 // Profile any new connections caused by this method
928 if ( $this->connectionCounter > $priorConnectionsMade ) {
929 $this->trxProfiler->recordConnection(
930 $conn->getServer(),
931 $conn->getDBname(),
932 ( ( $flags & self::CONN_INTENT_WRITABLE ) == self::CONN_INTENT_WRITABLE )
933 );
934 }
935
936 if ( !$conn->isOpen() ) {
937 $this->errorConnection = $conn;
938 // Connection was made but later unrecoverably lost for some reason.
939 // Do not return a handle that will just throw exceptions on use, but
940 // let the calling code, e.g. getReaderIndex(), try another server.
941 return false;
942 }
943
944 // Make sure that flags like CONN_TRX_AUTOCOMMIT are respected by this handle
945 $this->enforceConnectionFlags( $conn, $flags );
946 // Set master DB handles as read-only if the load balancer is configured as read-only
947 // or the master database server is running in server-side read-only mode. Note that
948 // replica DB handles are always read-only via Database::assertIsWritableMaster().
949 // Read-only mode due to replication lag is *avoided* here to avoid recursion.
950 if ( $conn->getLBInfo( 'serverIndex' ) === $this->getWriterIndex() ) {
951 if ( $this->readOnlyReason !== false ) {
952 $conn->setLBInfo( 'readOnlyReason', $this->readOnlyReason );
953 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
954 $conn->setLBInfo(
955 'readOnlyReason',
956 'The master database server is running in read-only mode.'
957 );
958 }
959 }
960
961 return $conn;
962 }
963
964 public function reuseConnection( IDatabase $conn ) {
965 $serverIndex = $conn->getLBInfo( 'serverIndex' );
966 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
967 if ( $serverIndex === null || $refCount === null ) {
968 return; // non-foreign connection; no domain-use tracking to update
969 } elseif ( $conn instanceof DBConnRef ) {
970 // DBConnRef already handles calling reuseConnection() and only passes the live
971 // Database instance to this method. Any caller passing in a DBConnRef is broken.
972 $this->connLogger->error(
973 __METHOD__ . ": got DBConnRef instance.\n" .
974 ( new LogicException() )->getTraceAsString() );
975
976 return;
977 }
978
979 if ( $this->disabled ) {
980 return; // DBConnRef handle probably survived longer than the LoadBalancer
981 }
982
983 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
984 $connFreeKey = self::KEY_FOREIGN_FREE_NOROUND;
985 $connInUseKey = self::KEY_FOREIGN_INUSE_NOROUND;
986 } else {
987 $connFreeKey = self::KEY_FOREIGN_FREE;
988 $connInUseKey = self::KEY_FOREIGN_INUSE;
989 }
990
991 $domain = $conn->getDomainID();
992 if ( !isset( $this->conns[$connInUseKey][$serverIndex][$domain] ) ) {
993 throw new InvalidArgumentException(
994 "Connection $serverIndex/$domain not found; it may have already been freed" );
995 } elseif ( $this->conns[$connInUseKey][$serverIndex][$domain] !== $conn ) {
996 throw new InvalidArgumentException(
997 "Connection $serverIndex/$domain mismatched; it may have already been freed" );
998 }
999
1000 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
1001 if ( $refCount <= 0 ) {
1002 $this->conns[$connFreeKey][$serverIndex][$domain] = $conn;
1003 unset( $this->conns[$connInUseKey][$serverIndex][$domain] );
1004 if ( !$this->conns[$connInUseKey][$serverIndex] ) {
1005 unset( $this->conns[$connInUseKey][$serverIndex] ); // clean up
1006 }
1007 $this->connLogger->debug( __METHOD__ . ": freed connection $serverIndex/$domain" );
1008 } else {
1009 $this->connLogger->debug( __METHOD__ .
1010 ": reference count for $serverIndex/$domain reduced to $refCount" );
1011 }
1012 }
1013
1014 public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1015 $domain = $this->resolveDomainID( $domain );
1016 $role = $this->getRoleFromIndex( $i );
1017
1018 return new DBConnRef( $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
1019 }
1020
1021 public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1022 $domain = $this->resolveDomainID( $domain );
1023 $role = $this->getRoleFromIndex( $i );
1024
1025 return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role );
1026 }
1027
1028 public function getMaintenanceConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
1029 $domain = $this->resolveDomainID( $domain );
1030 $role = $this->getRoleFromIndex( $i );
1031
1032 return new MaintainableDBConnRef(
1033 $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
1034 }
1035
1036 /**
1037 * @param int $i Server index or DB_MASTER/DB_REPLICA
1038 * @return int One of DB_MASTER/DB_REPLICA
1039 */
1040 private function getRoleFromIndex( $i ) {
1041 return ( $i === self::DB_MASTER || $i === $this->getWriterIndex() )
1042 ? self::DB_MASTER
1043 : self::DB_REPLICA;
1044 }
1045
1046 /**
1047 * @param int $i
1048 * @param string|bool $domain
1049 * @param int $flags
1050 * @return Database|bool Live database handle or false on failure
1051 * @deprecated Since 1.34 Use getConnection() instead
1052 */
1053 public function openConnection( $i, $domain = false, $flags = 0 ) {
1054 return $this->getConnection( $i, [], $domain, $flags | self::CONN_SILENCE_ERRORS );
1055 }
1056
1057 /**
1058 * Open a connection to a local DB, or return one if it is already open.
1059 *
1060 * On error, returns false, and the connection which caused the
1061 * error will be available via $this->errorConnection.
1062 *
1063 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
1064 *
1065 * @param int $i Specific server index
1066 * @param int $flags Class CONN_* constant bitfield
1067 * @return Database
1068 * @throws InvalidArgumentException When the server index is invalid
1069 * @throws UnexpectedValueException When the DB domain of the connection is corrupted
1070 */
1071 private function getLocalConnection( $i, $flags = 0 ) {
1072 $autoCommit = ( ( $flags & self::CONN_TRX_AUTOCOMMIT ) == self::CONN_TRX_AUTOCOMMIT );
1073 // Connection handles required to be in auto-commit mode use a separate connection
1074 // pool since the main pool is effected by implicit and explicit transaction rounds
1075 $connKey = $autoCommit ? self::KEY_LOCAL_NOROUND : self::KEY_LOCAL;
1076
1077 if ( isset( $this->conns[$connKey][$i][0] ) ) {
1078 $conn = $this->conns[$connKey][$i][0];
1079 } else {
1080 $conn = $this->reallyOpenConnection(
1081 $i,
1082 $this->localDomain,
1083 [ 'autoCommitOnly' => $autoCommit ]
1084 );
1085 if ( $conn->isOpen() ) {
1086 $this->connLogger->debug( __METHOD__ . ": opened new connection for $i" );
1087 $this->conns[$connKey][$i][0] = $conn;
1088 } else {
1089 $this->connLogger->warning( __METHOD__ . ": connection error for $i" );
1090 $this->errorConnection = $conn;
1091 $conn = false;
1092 }
1093 }
1094
1095 // Sanity check to make sure that the right domain is selected
1096 if (
1097 $conn instanceof IDatabase &&
1098 !$this->localDomain->isCompatible( $conn->getDomainID() )
1099 ) {
1100 throw new UnexpectedValueException(
1101 "Got connection to '{$conn->getDomainID()}', " .
1102 "but expected local domain ('{$this->localDomain}')"
1103 );
1104 }
1105
1106 return $conn;
1107 }
1108
1109 /**
1110 * Open a connection to a foreign DB, or return one if it is already open.
1111 *
1112 * Increments a reference count on the returned connection which locks the
1113 * connection to the requested domain. This reference count can be
1114 * decremented by calling reuseConnection().
1115 *
1116 * If a connection is open to the appropriate server already, but with the wrong
1117 * database, it will be switched to the right database and returned, as long as
1118 * it has been freed first with reuseConnection().
1119 *
1120 * On error, returns false, and the connection which caused the
1121 * error will be available via $this->errorConnection.
1122 *
1123 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
1124 *
1125 * @param int $i Specific server index
1126 * @param string $domain Domain ID to open
1127 * @param int $flags Class CONN_* constant bitfield
1128 * @return Database|bool Returns false on connection error
1129 * @throws DBError When database selection fails
1130 * @throws InvalidArgumentException When the server index is invalid
1131 * @throws UnexpectedValueException When the DB domain of the connection is corrupted
1132 */
1133 private function getForeignConnection( $i, $domain, $flags = 0 ) {
1134 $domainInstance = DatabaseDomain::newFromId( $domain );
1135 $autoCommit = ( ( $flags & self::CONN_TRX_AUTOCOMMIT ) == self::CONN_TRX_AUTOCOMMIT );
1136 // Connection handles required to be in auto-commit mode use a separate connection
1137 // pool since the main pool is effected by implicit and explicit transaction rounds
1138 if ( $autoCommit ) {
1139 $connFreeKey = self::KEY_FOREIGN_FREE_NOROUND;
1140 $connInUseKey = self::KEY_FOREIGN_INUSE_NOROUND;
1141 } else {
1142 $connFreeKey = self::KEY_FOREIGN_FREE;
1143 $connInUseKey = self::KEY_FOREIGN_INUSE;
1144 }
1145
1146 /** @var Database $conn */
1147 $conn = null;
1148
1149 if ( isset( $this->conns[$connInUseKey][$i][$domain] ) ) {
1150 // Reuse an in-use connection for the same domain
1151 $conn = $this->conns[$connInUseKey][$i][$domain];
1152 $this->connLogger->debug( __METHOD__ . ": reusing connection $i/$domain" );
1153 } elseif ( isset( $this->conns[$connFreeKey][$i][$domain] ) ) {
1154 // Reuse a free connection for the same domain
1155 $conn = $this->conns[$connFreeKey][$i][$domain];
1156 unset( $this->conns[$connFreeKey][$i][$domain] );
1157 $this->conns[$connInUseKey][$i][$domain] = $conn;
1158 $this->connLogger->debug( __METHOD__ . ": reusing free connection $i/$domain" );
1159 } elseif ( !empty( $this->conns[$connFreeKey][$i] ) ) {
1160 // Reuse a free connection from another domain if possible
1161 foreach ( $this->conns[$connFreeKey][$i] as $oldDomain => $conn ) {
1162 if ( $domainInstance->getDatabase() !== null ) {
1163 // Check if changing the database will require a new connection.
1164 // In that case, leave the connection handle alone and keep looking.
1165 // This prevents connections from being closed mid-transaction and can
1166 // also avoid overhead if the same database will later be requested.
1167 if (
1168 $conn->databasesAreIndependent() &&
1169 $conn->getDBname() !== $domainInstance->getDatabase()
1170 ) {
1171 continue;
1172 }
1173 // Select the new database, schema, and prefix
1174 $conn->selectDomain( $domainInstance );
1175 } else {
1176 // Stay on the current database, but update the schema/prefix
1177 $conn->dbSchema( $domainInstance->getSchema() );
1178 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1179 }
1180 unset( $this->conns[$connFreeKey][$i][$oldDomain] );
1181 // Note that if $domain is an empty string, getDomainID() might not match it
1182 $this->conns[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1183 $this->connLogger->debug( __METHOD__ .
1184 ": reusing free connection from $oldDomain for $domain" );
1185 break;
1186 }
1187 }
1188
1189 if ( !$conn ) {
1190 $conn = $this->reallyOpenConnection(
1191 $i,
1192 $domainInstance,
1193 [
1194 'autoCommitOnly' => $autoCommit,
1195 'foreign' => true,
1196 'foreignPoolRefCount' => 0
1197 ]
1198 );
1199 if ( $conn->isOpen() ) {
1200 // Note that if $domain is an empty string, getDomainID() might not match it
1201 $this->conns[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1202 $this->connLogger->debug( __METHOD__ . ": opened new connection for $i/$domain" );
1203 } else {
1204 $this->connLogger->warning( __METHOD__ . ": connection error for $i/$domain" );
1205 $this->errorConnection = $conn;
1206 $conn = false;
1207 }
1208 }
1209
1210 if ( $conn instanceof IDatabase ) {
1211 // Sanity check to make sure that the right domain is selected
1212 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1213 throw new UnexpectedValueException(
1214 "Got connection to '{$conn->getDomainID()}', but expected '$domain'" );
1215 }
1216 // Increment reference count
1217 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1218 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
1219 }
1220
1221 return $conn;
1222 }
1223
1224 public function getServerAttributes( $i ) {
1225 return Database::attributesFromType(
1226 $this->getServerType( $i ),
1227 $this->servers[$i]['driver'] ?? null
1228 );
1229 }
1230
1231 /**
1232 * Test if the specified index represents an open connection
1233 *
1234 * @param int $index Server index
1235 * @return bool
1236 */
1237 private function isOpen( $index ) {
1238 return (bool)$this->getAnyOpenConnection( $index );
1239 }
1240
1241 /**
1242 * Open a new network connection to a server (uncached)
1243 *
1244 * Returns a Database object whether or not the connection was successful.
1245 *
1246 * @param int $i Specific server index
1247 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
1248 * @param array $lbInfo Additional information for setLBInfo()
1249 * @return Database
1250 * @throws DBAccessError
1251 * @throws InvalidArgumentException
1252 */
1253 protected function reallyOpenConnection( $i, DatabaseDomain $domain, array $lbInfo ) {
1254 if ( $this->disabled ) {
1255 throw new DBAccessError();
1256 }
1257
1258 $server = $this->getServerInfoStrict( $i );
1259 $server = array_merge( $server, [
1260 // Use the database specified in $domain (null means "none or entrypoint DB");
1261 // fallback to the $server default if the RDBMs is an embedded library using a file
1262 // on disk since there would be nothing to access to without a DB/file name.
1263 'dbname' => $this->getServerAttributes( $i )[Database::ATTR_DB_IS_FILE]
1264 ? ( $domain->getDatabase() ?? $server['dbname'] ?? null )
1265 : $domain->getDatabase(),
1266 // Override the $server default schema with that of $domain if specified
1267 'schema' => $domain->getSchema() ?? $server['schema'] ?? null,
1268 // Use the table prefix specified in $domain
1269 'tablePrefix' => $domain->getTablePrefix(),
1270 // Participate in transaction rounds if $server does not specify otherwise
1271 'flags' => $server['flags'] ?? IDatabase::DBO_DEFAULT,
1272 // Inject the PHP execution mode and the agent string
1273 'cliMode' => $this->cliMode,
1274 'agent' => $this->agent,
1275 // Inject object and callback dependencies
1276 'srvCache' => $this->srvCache,
1277 'connLogger' => $this->connLogger,
1278 'queryLogger' => $this->queryLogger,
1279 'errorLogger' => $this->errorLogger,
1280 'deprecationLogger' => $this->deprecationLogger,
1281 'profiler' => $this->profiler,
1282 'trxProfiler' => $this->trxProfiler
1283 ] );
1284
1285 $lbInfo = array_merge( $lbInfo, [
1286 'ownerId' => $this->id,
1287 'serverIndex' => $i,
1288 'master' => ( $i === $this->getWriterIndex() ),
1289 'replica' => ( $i !== $this->getWriterIndex() ),
1290 // Name of the master server of the relevant DB cluster (e.g. "db1052")
1291 'clusterMasterHost' => $this->getServerName( $this->getWriterIndex() )
1292 ] );
1293
1294 $conn = Database::factory( $server['type'], $server, Database::NEW_UNCONNECTED );
1295 try {
1296 $conn->initConnection();
1297 ++$this->connectionCounter;
1298 } catch ( DBConnectionError $e ) {
1299 // ignore; let the DB handle the logging
1300 }
1301
1302 $conn->setLBInfo( $lbInfo );
1303 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1304 if ( $this->cliMode ) {
1305 $conn->clearFlag( $conn::DBO_TRX );
1306 } else {
1307 $conn->setFlag( $conn::DBO_TRX );
1308 }
1309 }
1310 if ( $i === $this->getWriterIndex() ) {
1311 if ( $this->trxRoundId !== false ) {
1312 $this->applyTransactionRoundFlags( $conn );
1313 }
1314 foreach ( $this->trxRecurringCallbacks as $name => $callback ) {
1315 $conn->setTransactionListener( $name, $callback );
1316 }
1317 }
1318 $conn->setTableAliases( $this->tableAliases );
1319 $conn->setIndexAliases( $this->indexAliases );
1320
1321 $conn->setLazyMasterHandle(
1322 $this->getLazyConnectionRef( self::DB_MASTER, [], $conn->getDomainID() )
1323 );
1324
1325 $this->lazyLoadReplicationPositions(); // session consistency
1326
1327 // Log when many connection are made on requests
1328 $count = $this->getCurrentConnectionCount();
1329 if ( $count >= self::CONN_HELD_WARN_THRESHOLD ) {
1330 $this->perfLogger->warning(
1331 __METHOD__ . ": {connections}+ connections made (master={masterdb})",
1332 [
1333 'connections' => $count,
1334 'dbserver' => $conn->getServer(),
1335 'masterdb' => $conn->getLBInfo( 'clusterMasterHost' )
1336 ]
1337 );
1338 }
1339
1340 return $conn;
1341 }
1342
1343 /**
1344 * Make sure that any "waitForPos" positions are loaded and available to doWait()
1345 */
1346 private function lazyLoadReplicationPositions() {
1347 if ( !$this->connectionAttempted && $this->chronologyCallback ) {
1348 $this->connectionAttempted = true;
1349 ( $this->chronologyCallback )( $this ); // generally calls waitFor()
1350 $this->connLogger->debug( __METHOD__ . ': executed chronology callback.' );
1351 }
1352 }
1353
1354 /**
1355 * @throws DBConnectionError
1356 */
1357 private function reportConnectionError() {
1358 $conn = $this->errorConnection; // the connection which caused the error
1359 $context = [
1360 'method' => __METHOD__,
1361 'last_error' => $this->lastError,
1362 ];
1363
1364 if ( $conn instanceof IDatabase ) {
1365 $context['db_server'] = $conn->getServer();
1366 $this->connLogger->warning(
1367 __METHOD__ . ": connection error: {last_error} ({db_server})",
1368 $context
1369 );
1370
1371 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1372 } else {
1373 // No last connection, probably due to all servers being too busy
1374 $this->connLogger->error(
1375 __METHOD__ .
1376 ": LB failure with no last connection. Connection error: {last_error}",
1377 $context
1378 );
1379
1380 // If all servers were busy, "lastError" will contain something sensible
1381 throw new DBConnectionError( null, $this->lastError );
1382 }
1383 }
1384
1385 public function getWriterIndex() {
1386 return 0;
1387 }
1388
1389 /**
1390 * Returns true if the specified index is a valid server index
1391 *
1392 * @param int $i
1393 * @return bool
1394 * @deprecated Since 1.34
1395 */
1396 public function haveIndex( $i ) {
1397 return array_key_exists( $i, $this->servers );
1398 }
1399
1400 /**
1401 * Returns true if the specified index is valid and has non-zero load
1402 *
1403 * @param int $i
1404 * @return bool
1405 * @deprecated Since 1.34
1406 */
1407 public function isNonZeroLoad( $i ) {
1408 return ( isset( $this->servers[$i] ) && $this->groupLoads[self::GROUP_GENERIC][$i] > 0 );
1409 }
1410
1411 public function getServerCount() {
1412 return count( $this->servers );
1413 }
1414
1415 public function hasReplicaServers() {
1416 return ( $this->getServerCount() > 1 );
1417 }
1418
1419 public function hasStreamingReplicaServers() {
1420 foreach ( $this->servers as $i => $server ) {
1421 if ( $i !== $this->getWriterIndex() && empty( $server['is static'] ) ) {
1422 return true;
1423 }
1424 }
1425
1426 return false;
1427 }
1428
1429 public function getServerName( $i ) {
1430 $name = $this->servers[$i]['hostName'] ?? ( $this->servers[$i]['host'] ?? '' );
1431
1432 return ( $name != '' ) ? $name : 'localhost';
1433 }
1434
1435 public function getServerInfo( $i ) {
1436 return $this->servers[$i] ?? false;
1437 }
1438
1439 public function getServerType( $i ) {
1440 return $this->servers[$i]['type'] ?? 'unknown';
1441 }
1442
1443 public function getMasterPos() {
1444 $index = $this->getWriterIndex();
1445
1446 $conn = $this->getAnyOpenConnection( $index );
1447 if ( $conn ) {
1448 return $conn->getMasterPos();
1449 }
1450
1451 $conn = $this->getConnection( $index, self::CONN_SILENCE_ERRORS );
1452 if ( !$conn ) {
1453 $this->reportConnectionError();
1454 return null; // unreachable due to exception
1455 }
1456
1457 try {
1458 $pos = $conn->getMasterPos();
1459 } finally {
1460 $this->closeConnection( $conn );
1461 }
1462
1463 return $pos;
1464 }
1465
1466 public function getReplicaResumePos() {
1467 // Get the position of any existing master server connection
1468 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1469 if ( $masterConn ) {
1470 return $masterConn->getMasterPos();
1471 }
1472
1473 // Get the highest position of any existing replica server connection
1474 $highestPos = false;
1475 $serverCount = $this->getServerCount();
1476 for ( $i = 1; $i < $serverCount; $i++ ) {
1477 if ( !empty( $this->servers[$i]['is static'] ) ) {
1478 continue; // server does not use replication
1479 }
1480
1481 $conn = $this->getAnyOpenConnection( $i );
1482 $pos = $conn ? $conn->getReplicaPos() : false;
1483 if ( !$pos ) {
1484 continue; // no open connection or could not get position
1485 }
1486
1487 $highestPos = $highestPos ?: $pos;
1488 if ( $pos->hasReached( $highestPos ) ) {
1489 $highestPos = $pos;
1490 }
1491 }
1492
1493 return $highestPos;
1494 }
1495
1496 public function disable() {
1497 $this->closeAll();
1498 $this->disabled = true;
1499 }
1500
1501 public function closeAll() {
1502 $fname = __METHOD__;
1503 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( $fname ) {
1504 $host = $conn->getServer();
1505 $this->connLogger->debug(
1506 $fname . ": closing connection to database '$host'." );
1507 $conn->close();
1508 } );
1509
1510 $this->conns = self::newTrackedConnectionsArray();
1511 }
1512
1513 public function closeConnection( IDatabase $conn ) {
1514 if ( $conn instanceof DBConnRef ) {
1515 // Avoid calling close() but still leaving the handle in the pool
1516 throw new RuntimeException( 'Cannot close DBConnRef instance; it must be shareable' );
1517 }
1518
1519 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1520 foreach ( $this->conns as $type => $connsByServer ) {
1521 if ( !isset( $connsByServer[$serverIndex] ) ) {
1522 continue;
1523 }
1524
1525 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1526 if ( $conn === $trackedConn ) {
1527 $host = $this->getServerName( $i );
1528 $this->connLogger->debug(
1529 __METHOD__ . ": closing connection to database $i at '$host'." );
1530 unset( $this->conns[$type][$serverIndex][$i] );
1531 break 2;
1532 }
1533 }
1534 }
1535
1536 $conn->close();
1537 }
1538
1539 public function commitAll( $fname = __METHOD__, $owner = null ) {
1540 $this->commitMasterChanges( $fname, $owner );
1541 $this->flushMasterSnapshots( $fname );
1542 $this->flushReplicaSnapshots( $fname );
1543 }
1544
1545 public function finalizeMasterChanges( $fname = __METHOD__, $owner = null ) {
1546 $this->assertOwnership( $fname, $owner );
1547 $this->assertTransactionRoundStage( [ self::ROUND_CURSORY, self::ROUND_FINALIZED ] );
1548
1549 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1550 // Loop until callbacks stop adding callbacks on other connections
1551 $total = 0;
1552 do {
1553 $count = 0; // callbacks execution attempts
1554 $this->forEachOpenMasterConnection( function ( Database $conn ) use ( &$count ) {
1555 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1556 // Any error should cause all (peer) transactions to be rolled back together.
1557 $count += $conn->runOnTransactionPreCommitCallbacks();
1558 } );
1559 $total += $count;
1560 } while ( $count > 0 );
1561 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1562 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1563 $conn->setTrxEndCallbackSuppression( true );
1564 } );
1565 $this->trxRoundStage = self::ROUND_FINALIZED;
1566
1567 return $total;
1568 }
1569
1570 public function approveMasterChanges( array $options, $fname = __METHOD__, $owner = null ) {
1571 $this->assertOwnership( $fname, $owner );
1572 $this->assertTransactionRoundStage( self::ROUND_FINALIZED );
1573
1574 $limit = $options['maxWriteDuration'] ?? 0;
1575
1576 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1577 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $limit ) {
1578 // If atomic sections or explicit transactions are still open, some caller must have
1579 // caught an exception but failed to properly rollback any changes. Detect that and
1580 // throw and error (causing rollback).
1581 $conn->assertNoOpenTransactions();
1582 // Assert that the time to replicate the transaction will be sane.
1583 // If this fails, then all DB transactions will be rollback back together.
1584 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY );
1585 if ( $limit > 0 && $time > $limit ) {
1586 throw new DBTransactionSizeError(
1587 $conn,
1588 "Transaction spent $time second(s) in writes, exceeding the limit of $limit",
1589 [ $time, $limit ]
1590 );
1591 }
1592 // If a connection sits idle while slow queries execute on another, that connection
1593 // may end up dropped before the commit round is reached. Ping servers to detect this.
1594 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1595 throw new DBTransactionError(
1596 $conn,
1597 "A connection to the {$conn->getDBname()} database was lost before commit"
1598 );
1599 }
1600 } );
1601 $this->trxRoundStage = self::ROUND_APPROVED;
1602 }
1603
1604 public function beginMasterChanges( $fname = __METHOD__, $owner = null ) {
1605 $this->assertOwnership( $fname, $owner );
1606 if ( $this->trxRoundId !== false ) {
1607 throw new DBTransactionError(
1608 null,
1609 "$fname: Transaction round '{$this->trxRoundId}' already started"
1610 );
1611 }
1612 $this->assertTransactionRoundStage( self::ROUND_CURSORY );
1613
1614 // Clear any empty transactions (no writes/callbacks) from the implicit round
1615 $this->flushMasterSnapshots( $fname );
1616
1617 $this->trxRoundId = $fname;
1618 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1619 // Mark applicable handles as participating in this explicit transaction round.
1620 // For each of these handles, any writes and callbacks will be tied to a single
1621 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1622 // are part of an en masse commit or an en masse rollback.
1623 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1624 $this->applyTransactionRoundFlags( $conn );
1625 } );
1626 $this->trxRoundStage = self::ROUND_CURSORY;
1627 }
1628
1629 public function commitMasterChanges( $fname = __METHOD__, $owner = null ) {
1630 $this->assertOwnership( $fname, $owner );
1631 $this->assertTransactionRoundStage( self::ROUND_APPROVED );
1632
1633 $failures = [];
1634
1635 /** @noinspection PhpUnusedLocalVariableInspection */
1636 $scope = ScopedCallback::newScopedIgnoreUserAbort(); // try to ignore client aborts
1637
1638 $restore = ( $this->trxRoundId !== false );
1639 $this->trxRoundId = false;
1640 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1641 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1642 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1643 $this->forEachOpenMasterConnection(
1644 function ( IDatabase $conn ) use ( $fname, &$failures ) {
1645 try {
1646 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1647 } catch ( DBError $e ) {
1648 ( $this->errorLogger )( $e );
1649 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1650 }
1651 }
1652 );
1653 if ( $failures ) {
1654 throw new DBTransactionError(
1655 null,
1656 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1657 );
1658 }
1659 if ( $restore ) {
1660 // Unmark handles as participating in this explicit transaction round
1661 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1662 $this->undoTransactionRoundFlags( $conn );
1663 } );
1664 }
1665 $this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS;
1666 }
1667
1668 public function runMasterTransactionIdleCallbacks( $fname = __METHOD__, $owner = null ) {
1669 $this->assertOwnership( $fname, $owner );
1670 if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
1671 $type = IDatabase::TRIGGER_COMMIT;
1672 } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
1673 $type = IDatabase::TRIGGER_ROLLBACK;
1674 } else {
1675 throw new DBTransactionError(
1676 null,
1677 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1678 );
1679 }
1680
1681 $oldStage = $this->trxRoundStage;
1682 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1683
1684 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1685 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1686 $conn->setTrxEndCallbackSuppression( false );
1687 } );
1688
1689 $e = null; // first exception
1690 $fname = __METHOD__;
1691 // Loop until callbacks stop adding callbacks on other connections
1692 do {
1693 // Run any pending callbacks for each connection...
1694 $count = 0; // callback execution attempts
1695 $this->forEachOpenMasterConnection(
1696 function ( Database $conn ) use ( $type, &$e, &$count ) {
1697 if ( $conn->trxLevel() ) {
1698 return; // retry in the next iteration, after commit() is called
1699 }
1700 try {
1701 $count += $conn->runOnTransactionIdleCallbacks( $type );
1702 } catch ( Exception $ex ) {
1703 $e = $e ?: $ex;
1704 }
1705 }
1706 );
1707 // Clear out any active transactions left over from callbacks...
1708 $this->forEachOpenMasterConnection( function ( Database $conn ) use ( &$e, $fname ) {
1709 if ( $conn->writesPending() ) {
1710 // A callback from another handle wrote to this one and DBO_TRX is set
1711 $this->queryLogger->warning( $fname . ": found writes pending." );
1712 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1713 $this->queryLogger->warning(
1714 $fname . ": found writes pending ($fnames).",
1715 [
1716 'db_server' => $conn->getServer(),
1717 'db_name' => $conn->getDBname()
1718 ]
1719 );
1720 } elseif ( $conn->trxLevel() ) {
1721 // A callback from another handle read from this one and DBO_TRX is set,
1722 // which can easily happen if there is only one DB (no replicas)
1723 $this->queryLogger->debug( $fname . ": found empty transaction." );
1724 }
1725 try {
1726 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1727 } catch ( Exception $ex ) {
1728 $e = $e ?: $ex;
1729 }
1730 } );
1731 } while ( $count > 0 );
1732
1733 $this->trxRoundStage = $oldStage;
1734
1735 return $e;
1736 }
1737
1738 public function runMasterTransactionListenerCallbacks( $fname = __METHOD__, $owner = null ) {
1739 $this->assertOwnership( $fname, $owner );
1740 if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
1741 $type = IDatabase::TRIGGER_COMMIT;
1742 } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
1743 $type = IDatabase::TRIGGER_ROLLBACK;
1744 } else {
1745 throw new DBTransactionError(
1746 null,
1747 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1748 );
1749 }
1750
1751 $e = null;
1752
1753 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1754 $this->forEachOpenMasterConnection( function ( Database $conn ) use ( $type, &$e ) {
1755 try {
1756 $conn->runTransactionListenerCallbacks( $type );
1757 } catch ( Exception $ex ) {
1758 $e = $e ?: $ex;
1759 }
1760 } );
1761 $this->trxRoundStage = self::ROUND_CURSORY;
1762
1763 return $e;
1764 }
1765
1766 public function rollbackMasterChanges( $fname = __METHOD__, $owner = null ) {
1767 $this->assertOwnership( $fname, $owner );
1768
1769 $restore = ( $this->trxRoundId !== false );
1770 $this->trxRoundId = false;
1771 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1772 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $fname ) {
1773 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS );
1774 } );
1775 if ( $restore ) {
1776 // Unmark handles as participating in this explicit transaction round
1777 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1778 $this->undoTransactionRoundFlags( $conn );
1779 } );
1780 }
1781 $this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS;
1782 }
1783
1784 /**
1785 * @param string|string[] $stage
1786 * @throws DBTransactionError
1787 */
1788 private function assertTransactionRoundStage( $stage ) {
1789 $stages = (array)$stage;
1790
1791 if ( !in_array( $this->trxRoundStage, $stages, true ) ) {
1792 $stageList = implode(
1793 '/',
1794 array_map( function ( $v ) {
1795 return "'$v'";
1796 }, $stages )
1797 );
1798 throw new DBTransactionError(
1799 null,
1800 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1801 );
1802 }
1803 }
1804
1805 /**
1806 * @param string $fname
1807 * @param int|null $owner Owner ID of the caller
1808 * @throws DBTransactionError
1809 */
1810 private function assertOwnership( $fname, $owner ) {
1811 if ( $this->ownerId !== null && $owner !== $this->ownerId ) {
1812 throw new DBTransactionError(
1813 null,
1814 "$fname: LoadBalancer is owned by LBFactory #{$this->ownerId} (got '$owner')."
1815 );
1816 }
1817 }
1818
1819 /**
1820 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1821 *
1822 * Some servers may have neither flag enabled, meaning that they opt out of such
1823 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1824 * when a DB server is used for something like simple key/value storage.
1825 *
1826 * @param Database $conn
1827 */
1828 private function applyTransactionRoundFlags( Database $conn ) {
1829 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1830 return; // transaction rounds do not apply to these connections
1831 }
1832
1833 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1834 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1835 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1836 $conn->setFlag( $conn::DBO_TRX, $conn::REMEMBER_PRIOR );
1837 }
1838
1839 if ( $conn->getFlag( $conn::DBO_TRX ) ) {
1840 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId );
1841 }
1842 }
1843
1844 /**
1845 * @param Database $conn
1846 */
1847 private function undoTransactionRoundFlags( Database $conn ) {
1848 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1849 return; // transaction rounds do not apply to these connections
1850 }
1851
1852 if ( $conn->getFlag( $conn::DBO_TRX ) ) {
1853 $conn->setLBInfo( 'trxRoundId', null ); // remove the round ID
1854 }
1855
1856 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1857 $conn->restoreFlags( $conn::RESTORE_PRIOR );
1858 }
1859 }
1860
1861 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
1862 $this->forEachOpenReplicaConnection( function ( IDatabase $conn ) use ( $fname ) {
1863 $conn->flushSnapshot( $fname );
1864 } );
1865 }
1866
1867 public function flushMasterSnapshots( $fname = __METHOD__ ) {
1868 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $fname ) {
1869 $conn->flushSnapshot( $fname );
1870 } );
1871 }
1872
1873 /**
1874 * @return string
1875 * @since 1.32
1876 */
1877 public function getTransactionRoundStage() {
1878 return $this->trxRoundStage;
1879 }
1880
1881 public function hasMasterConnection() {
1882 return $this->isOpen( $this->getWriterIndex() );
1883 }
1884
1885 public function hasMasterChanges() {
1886 $pending = 0;
1887 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$pending ) {
1888 $pending |= $conn->writesOrCallbacksPending();
1889 } );
1890
1891 return (bool)$pending;
1892 }
1893
1894 public function lastMasterChangeTimestamp() {
1895 $lastTime = false;
1896 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$lastTime ) {
1897 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1898 } );
1899
1900 return $lastTime;
1901 }
1902
1903 public function hasOrMadeRecentMasterChanges( $age = null ) {
1904 $age = ( $age === null ) ? $this->waitTimeout : $age;
1905
1906 return ( $this->hasMasterChanges()
1907 || $this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1908 }
1909
1910 public function pendingMasterChangeCallers() {
1911 $fnames = [];
1912 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$fnames ) {
1913 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1914 } );
1915
1916 return $fnames;
1917 }
1918
1919 public function getLaggedReplicaMode( $domain = false ) {
1920 if ( $this->laggedReplicaMode ) {
1921 return true; // stay in lagged replica mode
1922 }
1923
1924 if ( $this->hasStreamingReplicaServers() ) {
1925 // This will set "laggedReplicaMode" as needed
1926 $this->getReaderIndex( self::GROUP_GENERIC, $domain );
1927 }
1928
1929 return $this->laggedReplicaMode;
1930 }
1931
1932 public function laggedReplicaUsed() {
1933 return $this->laggedReplicaMode;
1934 }
1935
1936 public function getReadOnlyReason( $domain = false, IDatabase $conn = null ) {
1937 if ( $this->readOnlyReason !== false ) {
1938 return $this->readOnlyReason;
1939 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1940 return 'The master database server is running in read-only mode.';
1941 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1942 return ( $this->getExistingReaderIndex( self::GROUP_GENERIC ) >= 0 )
1943 ? 'The database is read-only until replication lag decreases.'
1944 : 'The database is read-only until a replica database server becomes reachable.';
1945 }
1946
1947 return false;
1948 }
1949
1950 /**
1951 * @param string $domain Domain ID, or false for the current domain
1952 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1953 * @return bool
1954 */
1955 private function masterRunningReadOnly( $domain, IDatabase $conn = null ) {
1956 $cache = $this->wanCache;
1957 $masterServer = $this->getServerName( $this->getWriterIndex() );
1958
1959 return (bool)$cache->getWithSetCallback(
1960 $cache->makeGlobalKey( __CLASS__, 'server-read-only', $masterServer ),
1961 self::TTL_CACHE_READONLY,
1962 function () use ( $domain, $conn ) {
1963 $old = $this->trxProfiler->setSilenced( true );
1964 try {
1965 $index = $this->getWriterIndex();
1966 $dbw = $conn ?: $this->getServerConnection( $index, $domain );
1967 $readOnly = (int)$dbw->serverIsReadOnly();
1968 if ( !$conn ) {
1969 $this->reuseConnection( $dbw );
1970 }
1971 } catch ( DBError $e ) {
1972 $readOnly = 0;
1973 }
1974 $this->trxProfiler->setSilenced( $old );
1975
1976 return $readOnly;
1977 },
1978 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'busyValue' => 0 ]
1979 );
1980 }
1981
1982 public function allowLagged( $mode = null ) {
1983 if ( $mode === null ) {
1984 return $this->allowLagged;
1985 }
1986 $this->allowLagged = $mode;
1987
1988 return $this->allowLagged;
1989 }
1990
1991 public function pingAll() {
1992 $success = true;
1993 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$success ) {
1994 if ( !$conn->ping() ) {
1995 $success = false;
1996 }
1997 } );
1998
1999 return $success;
2000 }
2001
2002 public function forEachOpenConnection( $callback, array $params = [] ) {
2003 foreach ( $this->conns as $connsByServer ) {
2004 foreach ( $connsByServer as $serverConns ) {
2005 foreach ( $serverConns as $conn ) {
2006 $callback( $conn, ...$params );
2007 }
2008 }
2009 }
2010 }
2011
2012 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
2013 $masterIndex = $this->getWriterIndex();
2014 foreach ( $this->conns as $connsByServer ) {
2015 if ( isset( $connsByServer[$masterIndex] ) ) {
2016 /** @var IDatabase $conn */
2017 foreach ( $connsByServer[$masterIndex] as $conn ) {
2018 $callback( $conn, ...$params );
2019 }
2020 }
2021 }
2022 }
2023
2024 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
2025 foreach ( $this->conns as $connsByServer ) {
2026 foreach ( $connsByServer as $i => $serverConns ) {
2027 if ( $i === $this->getWriterIndex() ) {
2028 continue; // skip master
2029 }
2030 foreach ( $serverConns as $conn ) {
2031 $callback( $conn, ...$params );
2032 }
2033 }
2034 }
2035 }
2036
2037 /**
2038 * @return int
2039 */
2040 private function getCurrentConnectionCount() {
2041 $count = 0;
2042 foreach ( $this->conns as $connsByServer ) {
2043 foreach ( $connsByServer as $serverConns ) {
2044 $count += count( $serverConns );
2045 }
2046 }
2047
2048 return $count;
2049 }
2050
2051 public function getMaxLag( $domain = false ) {
2052 $host = '';
2053 $maxLag = -1;
2054 $maxIndex = 0;
2055
2056 if ( $this->hasReplicaServers() ) {
2057 $lagTimes = $this->getLagTimes( $domain );
2058 foreach ( $lagTimes as $i => $lag ) {
2059 if ( $this->groupLoads[self::GROUP_GENERIC][$i] > 0 && $lag > $maxLag ) {
2060 $maxLag = $lag;
2061 $host = $this->getServerInfoStrict( $i, 'host' );
2062 $maxIndex = $i;
2063 }
2064 }
2065 }
2066
2067 return [ $host, $maxLag, $maxIndex ];
2068 }
2069
2070 public function getLagTimes( $domain = false ) {
2071 if ( !$this->hasReplicaServers() ) {
2072 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
2073 }
2074
2075 $knownLagTimes = []; // map of (server index => 0 seconds)
2076 $indexesWithLag = [];
2077 foreach ( $this->servers as $i => $server ) {
2078 if ( empty( $server['is static'] ) ) {
2079 $indexesWithLag[] = $i; // DB server might have replication lag
2080 } else {
2081 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
2082 }
2083 }
2084
2085 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) + $knownLagTimes;
2086 }
2087
2088 /**
2089 * Get the lag in seconds for a given connection, or zero if this load
2090 * balancer does not have replication enabled.
2091 *
2092 * This should be used in preference to Database::getLag() in cases where
2093 * replication may not be in use, since there is no way to determine if
2094 * replication is in use at the connection level without running
2095 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
2096 * function instead of Database::getLag() avoids a fatal error in this
2097 * case on many installations.
2098 *
2099 * @param IDatabase $conn
2100 * @return int|bool Returns false on error
2101 * @deprecated Since 1.34 Use IDatabase::getLag() instead
2102 */
2103 public function safeGetLag( IDatabase $conn ) {
2104 if ( $conn->getLBInfo( 'is static' ) ) {
2105 return 0; // static dataset
2106 } elseif ( $conn->getLBInfo( 'serverIndex' ) == $this->getWriterIndex() ) {
2107 return 0; // this is the master
2108 }
2109
2110 return $conn->getLag();
2111 }
2112
2113 public function waitForMasterPos( IDatabase $conn, $pos = false, $timeout = null ) {
2114 $timeout = max( 1, $timeout ?: $this->waitTimeout );
2115
2116 if ( $conn->getLBInfo( 'serverIndex' ) === $this->getWriterIndex() ) {
2117 return true; // not a replica DB server
2118 }
2119
2120 if ( !$pos ) {
2121 // Get the current master position, opening a connection if needed
2122 $index = $this->getWriterIndex();
2123 $flags = self::CONN_SILENCE_ERRORS;
2124 $masterConn = $this->getAnyOpenConnection( $index, $flags );
2125 if ( $masterConn ) {
2126 $pos = $masterConn->getMasterPos();
2127 } else {
2128 $masterConn = $this->getServerConnection( $index, self::DOMAIN_ANY, $flags );
2129 if ( !$masterConn ) {
2130 throw new DBReplicationWaitError(
2131 null,
2132 "Could not obtain a master database connection to get the position"
2133 );
2134 }
2135 $pos = $masterConn->getMasterPos();
2136 $this->closeConnection( $masterConn );
2137 }
2138 }
2139
2140 if ( $pos instanceof DBMasterPos ) {
2141 $start = microtime( true );
2142 $result = $conn->masterPosWait( $pos, $timeout );
2143 $seconds = max( microtime( true ) - $start, 0 );
2144 if ( $result == -1 || is_null( $result ) ) {
2145 $msg = __METHOD__ . ': timed out waiting on {host} pos {pos} [{seconds}s]';
2146 $this->replLogger->warning( $msg, [
2147 'host' => $conn->getServer(),
2148 'pos' => $pos,
2149 'seconds' => round( $seconds, 6 ),
2150 'trace' => ( new RuntimeException() )->getTraceAsString()
2151 ] );
2152 $ok = false;
2153 } else {
2154 $this->replLogger->debug( __METHOD__ . ': done waiting' );
2155 $ok = true;
2156 }
2157 } else {
2158 $ok = false; // something is misconfigured
2159 $this->replLogger->error(
2160 __METHOD__ . ': could not get master pos for {host}',
2161 [
2162 'host' => $conn->getServer(),
2163 'trace' => ( new RuntimeException() )->getTraceAsString()
2164 ]
2165 );
2166 }
2167
2168 return $ok;
2169 }
2170
2171 /**
2172 * Wait for a replica DB to reach a specified master position
2173 *
2174 * This will connect to the master to get an accurate position if $pos is not given
2175 *
2176 * @param IDatabase $conn Replica DB
2177 * @param DBMasterPos|bool $pos Master position; default: current position
2178 * @param int $timeout Timeout in seconds [optional]
2179 * @return bool Success
2180 * @since 1.28
2181 * @deprecated Since 1.34 Use waitForMasterPos() instead
2182 */
2183 public function safeWaitForMasterPos( IDatabase $conn, $pos = false, $timeout = null ) {
2184 return $this->waitForMasterPos( $conn, $pos, $timeout );
2185 }
2186
2187 public function setTransactionListener( $name, callable $callback = null ) {
2188 if ( $callback ) {
2189 $this->trxRecurringCallbacks[$name] = $callback;
2190 } else {
2191 unset( $this->trxRecurringCallbacks[$name] );
2192 }
2193 $this->forEachOpenMasterConnection(
2194 function ( IDatabase $conn ) use ( $name, $callback ) {
2195 $conn->setTransactionListener( $name, $callback );
2196 }
2197 );
2198 }
2199
2200 public function setTableAliases( array $aliases ) {
2201 $this->tableAliases = $aliases;
2202 }
2203
2204 public function setIndexAliases( array $aliases ) {
2205 $this->indexAliases = $aliases;
2206 }
2207
2208 public function setLocalDomainPrefix( $prefix ) {
2209 // Find connections to explicit foreign domains still marked as in-use...
2210 $domainsInUse = [];
2211 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$domainsInUse ) {
2212 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
2213 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
2214 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
2215 $domainsInUse[] = $conn->getDomainID();
2216 }
2217 } );
2218
2219 // Do not switch connections to explicit foreign domains unless marked as safe
2220 if ( $domainsInUse ) {
2221 $domains = implode( ', ', $domainsInUse );
2222 throw new DBUnexpectedError( null,
2223 "Foreign domain connections are still in use ($domains)" );
2224 }
2225
2226 $this->setLocalDomain( new DatabaseDomain(
2227 $this->localDomain->getDatabase(),
2228 $this->localDomain->getSchema(),
2229 $prefix
2230 ) );
2231
2232 // Update the prefix for all local connections...
2233 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( $prefix ) {
2234 if ( !$conn->getLBInfo( 'foreign' ) ) {
2235 $conn->tablePrefix( $prefix );
2236 }
2237 } );
2238 }
2239
2240 public function redefineLocalDomain( $domain ) {
2241 $this->closeAll();
2242
2243 $this->setLocalDomain( DatabaseDomain::newFromId( $domain ) );
2244 }
2245
2246 public function setTempTablesOnlyMode( $value, $domain ) {
2247 $old = $this->tempTablesOnlyMode[$domain] ?? false;
2248 if ( $value ) {
2249 $this->tempTablesOnlyMode[$domain] = true;
2250 } else {
2251 unset( $this->tempTablesOnlyMode[$domain] );
2252 }
2253
2254 return $old;
2255 }
2256
2257 /**
2258 * @param DatabaseDomain $domain
2259 */
2260 private function setLocalDomain( DatabaseDomain $domain ) {
2261 $this->localDomain = $domain;
2262 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
2263 // always true, gracefully handle the case when they fail to account for escaping.
2264 if ( $this->localDomain->getTablePrefix() != '' ) {
2265 $this->localDomainIdAlias =
2266 $this->localDomain->getDatabase() . '-' . $this->localDomain->getTablePrefix();
2267 } else {
2268 $this->localDomainIdAlias = $this->localDomain->getDatabase();
2269 }
2270 }
2271
2272 /**
2273 * @param int $i Server index
2274 * @param string|null $field Server index field [optional]
2275 * @return array|mixed
2276 * @throws InvalidArgumentException
2277 */
2278 private function getServerInfoStrict( $i, $field = null ) {
2279 if ( !isset( $this->servers[$i] ) || !is_array( $this->servers[$i] ) ) {
2280 throw new InvalidArgumentException( "No server with index '$i'" );
2281 }
2282
2283 if ( $field !== null ) {
2284 if ( !array_key_exists( $field, $this->servers[$i] ) ) {
2285 throw new InvalidArgumentException( "No field '$field' in server index '$i'" );
2286 }
2287
2288 return $this->servers[$i][$field];
2289 }
2290
2291 return $this->servers[$i];
2292 }
2293
2294 function __destruct() {
2295 // Avoid connection leaks for sanity
2296 $this->disable();
2297 }
2298 }
2299
2300 /**
2301 * @deprecated since 1.29
2302 */
2303 class_alias( LoadBalancer::class, 'LoadBalancer' );