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