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