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