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