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