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