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