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