6617ab1261e719052d63f16644e1fed44dbf75d3
[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 connections opened */
121 private $connsOpened = 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::newConnsArray();
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 newConnsArray() {
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->connsOpened;
838
839 // Choose a server if $i is DB_MASTER/DB_REPLICA (might trigger new connections)
840 $serverIndex = $this->getConnectionIndex( $i, $groups, $domain );
841 // Get an open connection to that server (might trigger a new connection)
842 $conn = $this->localDomain->equals( $domain )
843 ? $this->getLocalConnection( $serverIndex, $flags )
844 : $this->getForeignConnection( $serverIndex, $domain, $flags );
845 // Throw an error or bail out if the connection attempt failed
846 if ( !( $conn instanceof IDatabase ) ) {
847 if ( ( $flags & self::CONN_SILENCE_ERRORS ) != self::CONN_SILENCE_ERRORS ) {
848 $this->reportConnectionError();
849 }
850
851 return false;
852 }
853
854 // Profile any new connections caused by this method
855 if ( $this->connsOpened > $priorConnectionsMade ) {
856 $host = $conn->getServer();
857 $dbname = $conn->getDBname();
858 $this->trxProfiler->recordConnection( $host, $dbname, $masterOnly );
859 }
860
861 if ( !$conn->isOpen() ) {
862 // Connection was made but later unrecoverably lost for some reason.
863 // Do not return a handle that will just throw exceptions on use,
864 // but let the calling code (e.g. getReaderIndex) try another server.
865 $this->errorConnection = $conn;
866 return false;
867 }
868
869 $this->enforceConnectionFlags( $conn, $flags );
870 if ( $serverIndex === $this->getWriterIndex() ) {
871 // If the load balancer is read-only, perhaps due to replication lag, then master
872 // DB handles will reflect that. Note that Database::assertIsWritableMaster() takes
873 // care of replica DB handles whereas getReadOnlyReason() would cause infinite loops.
874 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
875 }
876
877 return $conn;
878 }
879
880 public function reuseConnection( IDatabase $conn ) {
881 $serverIndex = $conn->getLBInfo( 'serverIndex' );
882 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
883 if ( $serverIndex === null || $refCount === null ) {
884 /**
885 * This can happen in code like:
886 * foreach ( $dbs as $db ) {
887 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
888 * ...
889 * $lb->reuseConnection( $conn );
890 * }
891 * When a connection to the local DB is opened in this way, reuseConnection()
892 * should be ignored
893 */
894 return;
895 } elseif ( $conn instanceof DBConnRef ) {
896 // DBConnRef already handles calling reuseConnection() and only passes the live
897 // Database instance to this method. Any caller passing in a DBConnRef is broken.
898 $this->connLogger->error(
899 __METHOD__ . ": got DBConnRef instance.\n" .
900 ( new RuntimeException() )->getTraceAsString() );
901
902 return;
903 }
904
905 if ( $this->disabled ) {
906 return; // DBConnRef handle probably survived longer than the LoadBalancer
907 }
908
909 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
910 $connFreeKey = self::KEY_FOREIGN_FREE_NOROUND;
911 $connInUseKey = self::KEY_FOREIGN_INUSE_NOROUND;
912 } else {
913 $connFreeKey = self::KEY_FOREIGN_FREE;
914 $connInUseKey = self::KEY_FOREIGN_INUSE;
915 }
916
917 $domain = $conn->getDomainID();
918 if ( !isset( $this->conns[$connInUseKey][$serverIndex][$domain] ) ) {
919 throw new InvalidArgumentException(
920 "Connection $serverIndex/$domain not found; it may have already been freed" );
921 } elseif ( $this->conns[$connInUseKey][$serverIndex][$domain] !== $conn ) {
922 throw new InvalidArgumentException(
923 "Connection $serverIndex/$domain mismatched; it may have already been freed" );
924 }
925
926 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
927 if ( $refCount <= 0 ) {
928 $this->conns[$connFreeKey][$serverIndex][$domain] = $conn;
929 unset( $this->conns[$connInUseKey][$serverIndex][$domain] );
930 if ( !$this->conns[$connInUseKey][$serverIndex] ) {
931 unset( $this->conns[$connInUseKey][$serverIndex] ); // clean up
932 }
933 $this->connLogger->debug( __METHOD__ . ": freed connection $serverIndex/$domain" );
934 } else {
935 $this->connLogger->debug( __METHOD__ .
936 ": reference count for $serverIndex/$domain reduced to $refCount" );
937 }
938 }
939
940 public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
941 $domain = $this->resolveDomainID( $domain );
942 $role = $this->getRoleFromIndex( $i );
943
944 return new DBConnRef( $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
945 }
946
947 public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
948 $domain = $this->resolveDomainID( $domain );
949 $role = $this->getRoleFromIndex( $i );
950
951 return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role );
952 }
953
954 public function getMaintenanceConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ) {
955 $domain = $this->resolveDomainID( $domain );
956 $role = $this->getRoleFromIndex( $i );
957
958 return new MaintainableDBConnRef(
959 $this, $this->getConnection( $i, $groups, $domain, $flags ), $role );
960 }
961
962 /**
963 * @param int $i Server index or DB_MASTER/DB_REPLICA
964 * @return int One of DB_MASTER/DB_REPLICA
965 */
966 private function getRoleFromIndex( $i ) {
967 return ( $i === self::DB_MASTER || $i === $this->getWriterIndex() )
968 ? self::DB_MASTER
969 : self::DB_REPLICA;
970 }
971
972 /**
973 * @param int $i
974 * @param bool $domain
975 * @param int $flags
976 * @return Database|bool Live database handle or false on failure
977 * @deprecated Since 1.34 Use getConnection() instead
978 */
979 public function openConnection( $i, $domain = false, $flags = 0 ) {
980 return $this->getConnection( $i, [], $domain, $flags | self::CONN_SILENCE_ERRORS );
981 }
982
983 /**
984 * Open a connection to a local DB, or return one if it is already open.
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 int $flags Class CONN_* constant bitfield
993 * @return Database
994 */
995 private function getLocalConnection( $i, $flags = 0 ) {
996 // Connection handles required to be in auto-commit mode use a separate connection
997 // pool since the main pool is effected by implicit and explicit transaction rounds
998 $autoCommit = ( ( $flags & self::CONN_TRX_AUTOCOMMIT ) == self::CONN_TRX_AUTOCOMMIT );
999
1000 $connKey = $autoCommit ? self::KEY_LOCAL_NOROUND : self::KEY_LOCAL;
1001 if ( isset( $this->conns[$connKey][$i][0] ) ) {
1002 $conn = $this->conns[$connKey][$i][0];
1003 } else {
1004 // Open a new connection
1005 $server = $this->getServerInfoStrict( $i );
1006 $server['serverIndex'] = $i;
1007 $server['autoCommitOnly'] = $autoCommit;
1008 $conn = $this->reallyOpenConnection( $server, $this->localDomain );
1009 $host = $this->getServerName( $i );
1010 if ( $conn->isOpen() ) {
1011 $this->connLogger->debug(
1012 __METHOD__ . ": connected to database $i at '$host'." );
1013 $this->conns[$connKey][$i][0] = $conn;
1014 } else {
1015 $this->connLogger->warning(
1016 __METHOD__ . ": failed to connect to database $i at '$host'." );
1017 $this->errorConnection = $conn;
1018 $conn = false;
1019 }
1020 }
1021
1022 // Final sanity check to make sure the right domain is selected
1023 if (
1024 $conn instanceof IDatabase &&
1025 !$this->localDomain->isCompatible( $conn->getDomainID() )
1026 ) {
1027 throw new UnexpectedValueException(
1028 "Got connection to '{$conn->getDomainID()}', " .
1029 "but expected local domain ('{$this->localDomain}')" );
1030 }
1031
1032 return $conn;
1033 }
1034
1035 /**
1036 * Open a connection to a foreign DB, or return one if it is already open.
1037 *
1038 * Increments a reference count on the returned connection which locks the
1039 * connection to the requested domain. This reference count can be
1040 * decremented by calling reuseConnection().
1041 *
1042 * If a connection is open to the appropriate server already, but with the wrong
1043 * database, it will be switched to the right database and returned, as long as
1044 * it has been freed first with reuseConnection().
1045 *
1046 * On error, returns false, and the connection which caused the
1047 * error will be available via $this->errorConnection.
1048 *
1049 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
1050 *
1051 * @param int $i Server index
1052 * @param string $domain Domain ID to open
1053 * @param int $flags Class CONN_* constant bitfield
1054 * @return Database|bool Returns false on connection error
1055 * @throws DBError When database selection fails
1056 */
1057 private function getForeignConnection( $i, $domain, $flags = 0 ) {
1058 $domainInstance = DatabaseDomain::newFromId( $domain );
1059 // Connection handles required to be in auto-commit mode use a separate connection
1060 // pool since the main pool is effected by implicit and explicit transaction rounds
1061 $autoCommit = ( ( $flags & self::CONN_TRX_AUTOCOMMIT ) == self::CONN_TRX_AUTOCOMMIT );
1062
1063 if ( $autoCommit ) {
1064 $connFreeKey = self::KEY_FOREIGN_FREE_NOROUND;
1065 $connInUseKey = self::KEY_FOREIGN_INUSE_NOROUND;
1066 } else {
1067 $connFreeKey = self::KEY_FOREIGN_FREE;
1068 $connInUseKey = self::KEY_FOREIGN_INUSE;
1069 }
1070
1071 /** @var Database $conn */
1072 $conn = null;
1073
1074 if ( isset( $this->conns[$connInUseKey][$i][$domain] ) ) {
1075 // Reuse an in-use connection for the same domain
1076 $conn = $this->conns[$connInUseKey][$i][$domain];
1077 $this->connLogger->debug( __METHOD__ . ": reusing connection $i/$domain" );
1078 } elseif ( isset( $this->conns[$connFreeKey][$i][$domain] ) ) {
1079 // Reuse a free connection for the same domain
1080 $conn = $this->conns[$connFreeKey][$i][$domain];
1081 unset( $this->conns[$connFreeKey][$i][$domain] );
1082 $this->conns[$connInUseKey][$i][$domain] = $conn;
1083 $this->connLogger->debug( __METHOD__ . ": reusing free connection $i/$domain" );
1084 } elseif ( !empty( $this->conns[$connFreeKey][$i] ) ) {
1085 // Reuse a free connection from another domain if possible
1086 foreach ( $this->conns[$connFreeKey][$i] as $oldDomain => $conn ) {
1087 if ( $domainInstance->getDatabase() !== null ) {
1088 // Check if changing the database will require a new connection.
1089 // In that case, leave the connection handle alone and keep looking.
1090 // This prevents connections from being closed mid-transaction and can
1091 // also avoid overhead if the same database will later be requested.
1092 if (
1093 $conn->databasesAreIndependent() &&
1094 $conn->getDBname() !== $domainInstance->getDatabase()
1095 ) {
1096 continue;
1097 }
1098 // Select the new database, schema, and prefix
1099 $conn->selectDomain( $domainInstance );
1100 } else {
1101 // Stay on the current database, but update the schema/prefix
1102 $conn->dbSchema( $domainInstance->getSchema() );
1103 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1104 }
1105 unset( $this->conns[$connFreeKey][$i][$oldDomain] );
1106 // Note that if $domain is an empty string, getDomainID() might not match it
1107 $this->conns[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1108 $this->connLogger->debug( __METHOD__ .
1109 ": reusing free connection from $oldDomain for $domain" );
1110 break;
1111 }
1112 }
1113
1114 if ( !$conn ) {
1115 // Open a new connection
1116 $server = $this->getServerInfoStrict( $i );
1117 $server['serverIndex'] = $i;
1118 $server['foreignPoolRefCount'] = 0;
1119 $server['foreign'] = true;
1120 $server['autoCommitOnly'] = $autoCommit;
1121 $conn = $this->reallyOpenConnection( $server, $domainInstance );
1122 if ( !$conn->isOpen() ) {
1123 $this->connLogger->warning( __METHOD__ . ": connection error for $i/$domain" );
1124 $this->errorConnection = $conn;
1125 $conn = false;
1126 } else {
1127 // Note that if $domain is an empty string, getDomainID() might not match it
1128 $this->conns[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1129 $this->connLogger->debug( __METHOD__ . ": opened new connection for $i/$domain" );
1130 }
1131 }
1132
1133 if ( $conn instanceof IDatabase ) {
1134 // Final sanity check to make sure the right domain is selected
1135 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1136 throw new UnexpectedValueException(
1137 "Got connection to '{$conn->getDomainID()}', but expected '$domain'" );
1138 }
1139 // Increment reference count
1140 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1141 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
1142 }
1143
1144 return $conn;
1145 }
1146
1147 public function getServerAttributes( $i ) {
1148 return Database::attributesFromType(
1149 $this->getServerType( $i ),
1150 $this->servers[$i]['driver'] ?? null
1151 );
1152 }
1153
1154 /**
1155 * Test if the specified index represents an open connection
1156 *
1157 * @param int $index Server index
1158 * @private
1159 * @return bool
1160 */
1161 private function isOpen( $index ) {
1162 if ( !is_int( $index ) ) {
1163 return false;
1164 }
1165
1166 return (bool)$this->getAnyOpenConnection( $index );
1167 }
1168
1169 /**
1170 * Open a new network connection to a server (uncached)
1171 *
1172 * Returns a Database object whether or not the connection was successful.
1173 *
1174 * @param array $server
1175 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
1176 * @return Database
1177 * @throws DBAccessError
1178 * @throws InvalidArgumentException
1179 */
1180 protected function reallyOpenConnection( array $server, DatabaseDomain $domain ) {
1181 if ( $this->disabled ) {
1182 throw new DBAccessError();
1183 }
1184
1185 if ( $domain->getDatabase() === null ) {
1186 // The database domain does not specify a DB name and some database systems require a
1187 // valid DB specified on connection. The $server configuration array contains a default
1188 // DB name to use for connections in such cases.
1189 if ( $server['type'] === 'mysql' ) {
1190 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1191 // and the DB name in $server might not exist due to legacy reasons (the default
1192 // domain used to ignore the local LB domain, even when mismatched).
1193 $server['dbname'] = null;
1194 }
1195 } else {
1196 $server['dbname'] = $domain->getDatabase();
1197 }
1198
1199 if ( $domain->getSchema() !== null ) {
1200 $server['schema'] = $domain->getSchema();
1201 }
1202
1203 // It is always possible to connect with any prefix, even the empty string
1204 $server['tablePrefix'] = $domain->getTablePrefix();
1205
1206 // Let the handle know what the cluster master is (e.g. "db1052")
1207 $masterName = $this->getServerName( $this->getWriterIndex() );
1208 $server['clusterMasterHost'] = $masterName;
1209
1210 // Log when many connection are made on requests
1211 if ( ++$this->connsOpened >= self::CONN_HELD_WARN_THRESHOLD ) {
1212 $this->perfLogger->warning( __METHOD__ . ": " .
1213 "{$this->connsOpened}+ connections made (master=$masterName)" );
1214 }
1215
1216 $server['srvCache'] = $this->srvCache;
1217 // Set loggers and profilers
1218 $server['connLogger'] = $this->connLogger;
1219 $server['queryLogger'] = $this->queryLogger;
1220 $server['errorLogger'] = $this->errorLogger;
1221 $server['deprecationLogger'] = $this->deprecationLogger;
1222 $server['profiler'] = $this->profiler;
1223 $server['trxProfiler'] = $this->trxProfiler;
1224 // Use the same agent and PHP mode for all DB handles
1225 $server['cliMode'] = $this->cliMode;
1226 $server['agent'] = $this->agent;
1227 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1228 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1229 $server['flags'] = $server['flags'] ?? IDatabase::DBO_DEFAULT;
1230
1231 // Create a live connection object
1232 try {
1233 $db = Database::factory( $server['type'], $server );
1234 } catch ( DBConnectionError $e ) {
1235 // FIXME: This is probably the ugliest thing I have ever done to
1236 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1237 $db = $e->db;
1238 }
1239
1240 $db->setLBInfo( $server );
1241 $db->setLazyMasterHandle(
1242 $this->getLazyConnectionRef( self::DB_MASTER, [], $db->getDomainID() )
1243 );
1244 $db->setTableAliases( $this->tableAliases );
1245 $db->setIndexAliases( $this->indexAliases );
1246
1247 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1248 if ( $this->trxRoundId !== false ) {
1249 $this->applyTransactionRoundFlags( $db );
1250 }
1251 foreach ( $this->trxRecurringCallbacks as $name => $callback ) {
1252 $db->setTransactionListener( $name, $callback );
1253 }
1254 }
1255
1256 $this->lazyLoadReplicationPositions(); // session consistency
1257
1258 return $db;
1259 }
1260
1261 /**
1262 * Make sure that any "waitForPos" positions are loaded and available to doWait()
1263 */
1264 private function lazyLoadReplicationPositions() {
1265 if ( !$this->connectionAttempted && $this->chronologyCallback ) {
1266 $this->connectionAttempted = true;
1267 ( $this->chronologyCallback )( $this ); // generally calls waitFor()
1268 $this->connLogger->debug( __METHOD__ . ': executed chronology callback.' );
1269 }
1270 }
1271
1272 /**
1273 * @throws DBConnectionError
1274 */
1275 private function reportConnectionError() {
1276 $conn = $this->errorConnection; // the connection which caused the error
1277 $context = [
1278 'method' => __METHOD__,
1279 'last_error' => $this->lastError,
1280 ];
1281
1282 if ( $conn instanceof IDatabase ) {
1283 $context['db_server'] = $conn->getServer();
1284 $this->connLogger->warning(
1285 __METHOD__ . ": connection error: {last_error} ({db_server})",
1286 $context
1287 );
1288
1289 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1290 } else {
1291 // No last connection, probably due to all servers being too busy
1292 $this->connLogger->error(
1293 __METHOD__ .
1294 ": LB failure with no last connection. Connection error: {last_error}",
1295 $context
1296 );
1297
1298 // If all servers were busy, "lastError" will contain something sensible
1299 throw new DBConnectionError( null, $this->lastError );
1300 }
1301 }
1302
1303 public function getWriterIndex() {
1304 return 0;
1305 }
1306
1307 public function haveIndex( $i ) {
1308 return array_key_exists( $i, $this->servers );
1309 }
1310
1311 public function isNonZeroLoad( $i ) {
1312 return array_key_exists( $i, $this->servers ) && $this->genericLoads[$i] != 0;
1313 }
1314
1315 public function getServerCount() {
1316 return count( $this->servers );
1317 }
1318
1319 public function hasReplicaServers() {
1320 return ( $this->getServerCount() > 1 );
1321 }
1322
1323 public function hasStreamingReplicaServers() {
1324 foreach ( $this->servers as $i => $server ) {
1325 if ( $i !== $this->getWriterIndex() && empty( $server['is static'] ) ) {
1326 return true;
1327 }
1328 }
1329
1330 return false;
1331 }
1332
1333 public function getServerName( $i ) {
1334 $name = $this->servers[$i]['hostName'] ?? ( $this->servers[$i]['host'] ?? '' );
1335
1336 return ( $name != '' ) ? $name : 'localhost';
1337 }
1338
1339 public function getServerInfo( $i ) {
1340 return $this->servers[$i] ?? false;
1341 }
1342
1343 public function getServerType( $i ) {
1344 return $this->servers[$i]['type'] ?? 'unknown';
1345 }
1346
1347 public function getMasterPos() {
1348 # If this entire request was served from a replica DB without opening a connection to the
1349 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1350 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1351 if ( !$masterConn ) {
1352 $serverCount = $this->getServerCount();
1353 for ( $i = 1; $i < $serverCount; $i++ ) {
1354 $conn = $this->getAnyOpenConnection( $i );
1355 if ( $conn ) {
1356 return $conn->getReplicaPos();
1357 }
1358 }
1359 } else {
1360 return $masterConn->getMasterPos();
1361 }
1362
1363 return false;
1364 }
1365
1366 public function disable() {
1367 $this->closeAll();
1368 $this->disabled = true;
1369 }
1370
1371 public function closeAll() {
1372 $fname = __METHOD__;
1373 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( $fname ) {
1374 $host = $conn->getServer();
1375 $this->connLogger->debug(
1376 $fname . ": closing connection to database '$host'." );
1377 $conn->close();
1378 } );
1379
1380 $this->conns = self::newConnsArray();
1381 $this->connsOpened = 0;
1382 }
1383
1384 public function closeConnection( IDatabase $conn ) {
1385 if ( $conn instanceof DBConnRef ) {
1386 // Avoid calling close() but still leaving the handle in the pool
1387 throw new RuntimeException( 'Cannot close DBConnRef instance; it must be shareable' );
1388 }
1389
1390 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1391 foreach ( $this->conns as $type => $connsByServer ) {
1392 if ( !isset( $connsByServer[$serverIndex] ) ) {
1393 continue;
1394 }
1395
1396 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1397 if ( $conn === $trackedConn ) {
1398 $host = $this->getServerName( $i );
1399 $this->connLogger->debug(
1400 __METHOD__ . ": closing connection to database $i at '$host'." );
1401 unset( $this->conns[$type][$serverIndex][$i] );
1402 --$this->connsOpened;
1403 break 2;
1404 }
1405 }
1406 }
1407
1408 $conn->close();
1409 }
1410
1411 public function commitAll( $fname = __METHOD__, $owner = null ) {
1412 $this->commitMasterChanges( $fname, $owner );
1413 $this->flushMasterSnapshots( $fname );
1414 $this->flushReplicaSnapshots( $fname );
1415 }
1416
1417 public function finalizeMasterChanges( $fname = __METHOD__, $owner = null ) {
1418 $this->assertOwnership( $fname, $owner );
1419 $this->assertTransactionRoundStage( [ self::ROUND_CURSORY, self::ROUND_FINALIZED ] );
1420
1421 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1422 // Loop until callbacks stop adding callbacks on other connections
1423 $total = 0;
1424 do {
1425 $count = 0; // callbacks execution attempts
1426 $this->forEachOpenMasterConnection( function ( Database $conn ) use ( &$count ) {
1427 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1428 // Any error should cause all (peer) transactions to be rolled back together.
1429 $count += $conn->runOnTransactionPreCommitCallbacks();
1430 } );
1431 $total += $count;
1432 } while ( $count > 0 );
1433 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1434 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1435 $conn->setTrxEndCallbackSuppression( true );
1436 } );
1437 $this->trxRoundStage = self::ROUND_FINALIZED;
1438
1439 return $total;
1440 }
1441
1442 public function approveMasterChanges( array $options, $fname = __METHOD__, $owner = null ) {
1443 $this->assertOwnership( $fname, $owner );
1444 $this->assertTransactionRoundStage( self::ROUND_FINALIZED );
1445
1446 $limit = $options['maxWriteDuration'] ?? 0;
1447
1448 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1449 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $limit ) {
1450 // If atomic sections or explicit transactions are still open, some caller must have
1451 // caught an exception but failed to properly rollback any changes. Detect that and
1452 // throw and error (causing rollback).
1453 $conn->assertNoOpenTransactions();
1454 // Assert that the time to replicate the transaction will be sane.
1455 // If this fails, then all DB transactions will be rollback back together.
1456 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY );
1457 if ( $limit > 0 && $time > $limit ) {
1458 throw new DBTransactionSizeError(
1459 $conn,
1460 "Transaction spent $time second(s) in writes, exceeding the limit of $limit",
1461 [ $time, $limit ]
1462 );
1463 }
1464 // If a connection sits idle while slow queries execute on another, that connection
1465 // may end up dropped before the commit round is reached. Ping servers to detect this.
1466 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1467 throw new DBTransactionError(
1468 $conn,
1469 "A connection to the {$conn->getDBname()} database was lost before commit"
1470 );
1471 }
1472 } );
1473 $this->trxRoundStage = self::ROUND_APPROVED;
1474 }
1475
1476 public function beginMasterChanges( $fname = __METHOD__, $owner = null ) {
1477 $this->assertOwnership( $fname, $owner );
1478 if ( $this->trxRoundId !== false ) {
1479 throw new DBTransactionError(
1480 null,
1481 "$fname: Transaction round '{$this->trxRoundId}' already started"
1482 );
1483 }
1484 $this->assertTransactionRoundStage( self::ROUND_CURSORY );
1485
1486 // Clear any empty transactions (no writes/callbacks) from the implicit round
1487 $this->flushMasterSnapshots( $fname );
1488
1489 $this->trxRoundId = $fname;
1490 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1491 // Mark applicable handles as participating in this explicit transaction round.
1492 // For each of these handles, any writes and callbacks will be tied to a single
1493 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1494 // are part of an en masse commit or an en masse rollback.
1495 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1496 $this->applyTransactionRoundFlags( $conn );
1497 } );
1498 $this->trxRoundStage = self::ROUND_CURSORY;
1499 }
1500
1501 public function commitMasterChanges( $fname = __METHOD__, $owner = null ) {
1502 $this->assertOwnership( $fname, $owner );
1503 $this->assertTransactionRoundStage( self::ROUND_APPROVED );
1504
1505 $failures = [];
1506
1507 /** @noinspection PhpUnusedLocalVariableInspection */
1508 $scope = ScopedCallback::newScopedIgnoreUserAbort(); // try to ignore client aborts
1509
1510 $restore = ( $this->trxRoundId !== false );
1511 $this->trxRoundId = false;
1512 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1513 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1514 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1515 $this->forEachOpenMasterConnection(
1516 function ( IDatabase $conn ) use ( $fname, &$failures ) {
1517 try {
1518 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1519 } catch ( DBError $e ) {
1520 ( $this->errorLogger )( $e );
1521 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1522 }
1523 }
1524 );
1525 if ( $failures ) {
1526 throw new DBTransactionError(
1527 null,
1528 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1529 );
1530 }
1531 if ( $restore ) {
1532 // Unmark handles as participating in this explicit transaction round
1533 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1534 $this->undoTransactionRoundFlags( $conn );
1535 } );
1536 }
1537 $this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS;
1538 }
1539
1540 public function runMasterTransactionIdleCallbacks( $fname = __METHOD__, $owner = null ) {
1541 $this->assertOwnership( $fname, $owner );
1542 if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
1543 $type = IDatabase::TRIGGER_COMMIT;
1544 } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
1545 $type = IDatabase::TRIGGER_ROLLBACK;
1546 } else {
1547 throw new DBTransactionError(
1548 null,
1549 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1550 );
1551 }
1552
1553 $oldStage = $this->trxRoundStage;
1554 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1555
1556 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1557 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1558 $conn->setTrxEndCallbackSuppression( false );
1559 } );
1560
1561 $e = null; // first exception
1562 $fname = __METHOD__;
1563 // Loop until callbacks stop adding callbacks on other connections
1564 do {
1565 // Run any pending callbacks for each connection...
1566 $count = 0; // callback execution attempts
1567 $this->forEachOpenMasterConnection(
1568 function ( Database $conn ) use ( $type, &$e, &$count ) {
1569 if ( $conn->trxLevel() ) {
1570 return; // retry in the next iteration, after commit() is called
1571 }
1572 try {
1573 $count += $conn->runOnTransactionIdleCallbacks( $type );
1574 } catch ( Exception $ex ) {
1575 $e = $e ?: $ex;
1576 }
1577 }
1578 );
1579 // Clear out any active transactions left over from callbacks...
1580 $this->forEachOpenMasterConnection( function ( Database $conn ) use ( &$e, $fname ) {
1581 if ( $conn->writesPending() ) {
1582 // A callback from another handle wrote to this one and DBO_TRX is set
1583 $this->queryLogger->warning( $fname . ": found writes pending." );
1584 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1585 $this->queryLogger->warning(
1586 $fname . ": found writes pending ($fnames).",
1587 [
1588 'db_server' => $conn->getServer(),
1589 'db_name' => $conn->getDBname()
1590 ]
1591 );
1592 } elseif ( $conn->trxLevel() ) {
1593 // A callback from another handle read from this one and DBO_TRX is set,
1594 // which can easily happen if there is only one DB (no replicas)
1595 $this->queryLogger->debug( $fname . ": found empty transaction." );
1596 }
1597 try {
1598 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1599 } catch ( Exception $ex ) {
1600 $e = $e ?: $ex;
1601 }
1602 } );
1603 } while ( $count > 0 );
1604
1605 $this->trxRoundStage = $oldStage;
1606
1607 return $e;
1608 }
1609
1610 public function runMasterTransactionListenerCallbacks( $fname = __METHOD__, $owner = null ) {
1611 $this->assertOwnership( $fname, $owner );
1612 if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
1613 $type = IDatabase::TRIGGER_COMMIT;
1614 } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
1615 $type = IDatabase::TRIGGER_ROLLBACK;
1616 } else {
1617 throw new DBTransactionError(
1618 null,
1619 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1620 );
1621 }
1622
1623 $e = null;
1624
1625 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1626 $this->forEachOpenMasterConnection( function ( Database $conn ) use ( $type, &$e ) {
1627 try {
1628 $conn->runTransactionListenerCallbacks( $type );
1629 } catch ( Exception $ex ) {
1630 $e = $e ?: $ex;
1631 }
1632 } );
1633 $this->trxRoundStage = self::ROUND_CURSORY;
1634
1635 return $e;
1636 }
1637
1638 public function rollbackMasterChanges( $fname = __METHOD__, $owner = null ) {
1639 $this->assertOwnership( $fname, $owner );
1640
1641 $restore = ( $this->trxRoundId !== false );
1642 $this->trxRoundId = false;
1643 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1644 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $fname ) {
1645 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS );
1646 } );
1647 if ( $restore ) {
1648 // Unmark handles as participating in this explicit transaction round
1649 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1650 $this->undoTransactionRoundFlags( $conn );
1651 } );
1652 }
1653 $this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS;
1654 }
1655
1656 /**
1657 * @param string|string[] $stage
1658 * @throws DBTransactionError
1659 */
1660 private function assertTransactionRoundStage( $stage ) {
1661 $stages = (array)$stage;
1662
1663 if ( !in_array( $this->trxRoundStage, $stages, true ) ) {
1664 $stageList = implode(
1665 '/',
1666 array_map( function ( $v ) {
1667 return "'$v'";
1668 }, $stages )
1669 );
1670 throw new DBTransactionError(
1671 null,
1672 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1673 );
1674 }
1675 }
1676
1677 /**
1678 * @param string $fname
1679 * @param int|null $owner Owner ID of the caller
1680 * @throws DBTransactionError
1681 */
1682 private function assertOwnership( $fname, $owner ) {
1683 if ( $this->ownerId !== null && $owner !== $this->ownerId ) {
1684 throw new DBTransactionError(
1685 null,
1686 "$fname: LoadBalancer is owned by LBFactory #{$this->ownerId} (got '$owner')."
1687 );
1688 }
1689 }
1690
1691 /**
1692 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1693 *
1694 * Some servers may have neither flag enabled, meaning that they opt out of such
1695 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1696 * when a DB server is used for something like simple key/value storage.
1697 *
1698 * @param Database $conn
1699 */
1700 private function applyTransactionRoundFlags( Database $conn ) {
1701 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1702 return; // transaction rounds do not apply to these connections
1703 }
1704
1705 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1706 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1707 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1708 $conn->setFlag( $conn::DBO_TRX, $conn::REMEMBER_PRIOR );
1709 }
1710
1711 if ( $conn->getFlag( $conn::DBO_TRX ) ) {
1712 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId );
1713 }
1714 }
1715
1716 /**
1717 * @param Database $conn
1718 */
1719 private function undoTransactionRoundFlags( Database $conn ) {
1720 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1721 return; // transaction rounds do not apply to these connections
1722 }
1723
1724 if ( $conn->getFlag( $conn::DBO_TRX ) ) {
1725 $conn->setLBInfo( 'trxRoundId', false );
1726 }
1727
1728 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1729 $conn->restoreFlags( $conn::RESTORE_PRIOR );
1730 }
1731 }
1732
1733 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
1734 $this->forEachOpenReplicaConnection( function ( IDatabase $conn ) use ( $fname ) {
1735 $conn->flushSnapshot( $fname );
1736 } );
1737 }
1738
1739 public function flushMasterSnapshots( $fname = __METHOD__ ) {
1740 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $fname ) {
1741 $conn->flushSnapshot( $fname );
1742 } );
1743 }
1744
1745 /**
1746 * @return string
1747 * @since 1.32
1748 */
1749 public function getTransactionRoundStage() {
1750 return $this->trxRoundStage;
1751 }
1752
1753 public function hasMasterConnection() {
1754 return $this->isOpen( $this->getWriterIndex() );
1755 }
1756
1757 public function hasMasterChanges() {
1758 $pending = 0;
1759 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$pending ) {
1760 $pending |= $conn->writesOrCallbacksPending();
1761 } );
1762
1763 return (bool)$pending;
1764 }
1765
1766 public function lastMasterChangeTimestamp() {
1767 $lastTime = false;
1768 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$lastTime ) {
1769 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1770 } );
1771
1772 return $lastTime;
1773 }
1774
1775 public function hasOrMadeRecentMasterChanges( $age = null ) {
1776 $age = ( $age === null ) ? $this->waitTimeout : $age;
1777
1778 return ( $this->hasMasterChanges()
1779 || $this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1780 }
1781
1782 public function pendingMasterChangeCallers() {
1783 $fnames = [];
1784 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$fnames ) {
1785 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1786 } );
1787
1788 return $fnames;
1789 }
1790
1791 public function getLaggedReplicaMode( $domain = false ) {
1792 if (
1793 // Avoid recursion if there is only one DB
1794 $this->hasStreamingReplicaServers() &&
1795 // Avoid recursion if the (non-zero load) master DB was picked for generic reads
1796 $this->genericReadIndex !== $this->getWriterIndex() &&
1797 // Stay in lagged replica mode during the load balancer instance lifetime
1798 !$this->laggedReplicaMode
1799 ) {
1800 try {
1801 // Calling this method will set "laggedReplicaMode" as needed
1802 $this->getReaderIndex( false, $domain );
1803 } catch ( DBConnectionError $e ) {
1804 // Avoid expensive re-connect attempts and failures
1805 $this->allReplicasDownMode = true;
1806 $this->laggedReplicaMode = true;
1807 }
1808 }
1809
1810 return $this->laggedReplicaMode;
1811 }
1812
1813 public function laggedReplicaUsed() {
1814 return $this->laggedReplicaMode;
1815 }
1816
1817 /**
1818 * @return bool
1819 * @since 1.27
1820 * @deprecated Since 1.28; use laggedReplicaUsed()
1821 */
1822 public function laggedSlaveUsed() {
1823 return $this->laggedReplicaUsed();
1824 }
1825
1826 public function getReadOnlyReason( $domain = false, IDatabase $conn = null ) {
1827 if ( $this->readOnlyReason !== false ) {
1828 return $this->readOnlyReason;
1829 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1830 if ( $this->allReplicasDownMode ) {
1831 return 'The database has been automatically locked ' .
1832 'until the replica database servers become available';
1833 } else {
1834 return 'The database has been automatically locked ' .
1835 'while the replica database servers catch up to the master.';
1836 }
1837 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1838 return 'The database master is running in read-only mode.';
1839 }
1840
1841 return false;
1842 }
1843
1844 /**
1845 * @param string $domain Domain ID, or false for the current domain
1846 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1847 * @return bool
1848 */
1849 private function masterRunningReadOnly( $domain, IDatabase $conn = null ) {
1850 $cache = $this->wanCache;
1851 $masterServer = $this->getServerName( $this->getWriterIndex() );
1852
1853 return (bool)$cache->getWithSetCallback(
1854 $cache->makeGlobalKey( __CLASS__, 'server-read-only', $masterServer ),
1855 self::TTL_CACHE_READONLY,
1856 function () use ( $domain, $conn ) {
1857 $old = $this->trxProfiler->setSilenced( true );
1858 try {
1859 $dbw = $conn ?: $this->getConnection( self::DB_MASTER, [], $domain );
1860 $readOnly = (int)$dbw->serverIsReadOnly();
1861 if ( !$conn ) {
1862 $this->reuseConnection( $dbw );
1863 }
1864 } catch ( DBError $e ) {
1865 $readOnly = 0;
1866 }
1867 $this->trxProfiler->setSilenced( $old );
1868 return $readOnly;
1869 },
1870 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'busyValue' => 0 ]
1871 );
1872 }
1873
1874 public function allowLagged( $mode = null ) {
1875 if ( $mode === null ) {
1876 return $this->allowLagged;
1877 }
1878 $this->allowLagged = $mode;
1879
1880 return $this->allowLagged;
1881 }
1882
1883 public function pingAll() {
1884 $success = true;
1885 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$success ) {
1886 if ( !$conn->ping() ) {
1887 $success = false;
1888 }
1889 } );
1890
1891 return $success;
1892 }
1893
1894 public function forEachOpenConnection( $callback, array $params = [] ) {
1895 foreach ( $this->conns as $connsByServer ) {
1896 foreach ( $connsByServer as $serverConns ) {
1897 foreach ( $serverConns as $conn ) {
1898 $callback( $conn, ...$params );
1899 }
1900 }
1901 }
1902 }
1903
1904 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1905 $masterIndex = $this->getWriterIndex();
1906 foreach ( $this->conns as $connsByServer ) {
1907 if ( isset( $connsByServer[$masterIndex] ) ) {
1908 /** @var IDatabase $conn */
1909 foreach ( $connsByServer[$masterIndex] as $conn ) {
1910 $callback( $conn, ...$params );
1911 }
1912 }
1913 }
1914 }
1915
1916 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1917 foreach ( $this->conns as $connsByServer ) {
1918 foreach ( $connsByServer as $i => $serverConns ) {
1919 if ( $i === $this->getWriterIndex() ) {
1920 continue; // skip master
1921 }
1922 foreach ( $serverConns as $conn ) {
1923 $callback( $conn, ...$params );
1924 }
1925 }
1926 }
1927 }
1928
1929 public function getMaxLag( $domain = false ) {
1930 $host = '';
1931 $maxLag = -1;
1932 $maxIndex = 0;
1933
1934 if ( $this->hasReplicaServers() ) {
1935 $lagTimes = $this->getLagTimes( $domain );
1936 foreach ( $lagTimes as $i => $lag ) {
1937 if ( $this->genericLoads[$i] > 0 && $lag > $maxLag ) {
1938 $maxLag = $lag;
1939 $host = $this->getServerInfoStrict( $i, 'host' );
1940 $maxIndex = $i;
1941 }
1942 }
1943 }
1944
1945 return [ $host, $maxLag, $maxIndex ];
1946 }
1947
1948 public function getLagTimes( $domain = false ) {
1949 if ( !$this->hasReplicaServers() ) {
1950 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1951 }
1952
1953 $knownLagTimes = []; // map of (server index => 0 seconds)
1954 $indexesWithLag = [];
1955 foreach ( $this->servers as $i => $server ) {
1956 if ( empty( $server['is static'] ) ) {
1957 $indexesWithLag[] = $i; // DB server might have replication lag
1958 } else {
1959 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1960 }
1961 }
1962
1963 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) + $knownLagTimes;
1964 }
1965
1966 /**
1967 * Get the lag in seconds for a given connection, or zero if this load
1968 * balancer does not have replication enabled.
1969 *
1970 * This should be used in preference to Database::getLag() in cases where
1971 * replication may not be in use, since there is no way to determine if
1972 * replication is in use at the connection level without running
1973 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1974 * function instead of Database::getLag() avoids a fatal error in this
1975 * case on many installations.
1976 *
1977 * @param IDatabase $conn
1978 * @return int|bool Returns false on error
1979 * @deprecated Since 1.34 Use IDatabase::getLag() instead
1980 */
1981 public function safeGetLag( IDatabase $conn ) {
1982 if ( $conn->getLBInfo( 'is static' ) ) {
1983 return 0; // static dataset
1984 } elseif ( $conn->getLBInfo( 'serverIndex' ) == $this->getWriterIndex() ) {
1985 return 0; // this is the master
1986 }
1987
1988 return $conn->getLag();
1989 }
1990
1991 public function waitForMasterPos( IDatabase $conn, $pos = false, $timeout = null ) {
1992 $timeout = max( 1, $timeout ?: $this->waitTimeout );
1993
1994 if ( $this->getServerCount() <= 1 || !$conn->getLBInfo( 'replica' ) ) {
1995 return true; // server is not a replica DB
1996 }
1997
1998 if ( !$pos ) {
1999 // Get the current master position, opening a connection if needed
2000 $index = $this->getWriterIndex();
2001 $masterConn = $this->getAnyOpenConnection( $index );
2002 if ( $masterConn ) {
2003 $pos = $masterConn->getMasterPos();
2004 } else {
2005 $flags = self::CONN_SILENCE_ERRORS;
2006 $masterConn = $this->getConnection( $index, [], self::DOMAIN_ANY, $flags );
2007 if ( !$masterConn ) {
2008 throw new DBReplicationWaitError(
2009 null,
2010 "Could not obtain a master database connection to get the position"
2011 );
2012 }
2013 $pos = $masterConn->getMasterPos();
2014 $this->closeConnection( $masterConn );
2015 }
2016 }
2017
2018 if ( $pos instanceof DBMasterPos ) {
2019 $start = microtime( true );
2020 $result = $conn->masterPosWait( $pos, $timeout );
2021 $seconds = max( microtime( true ) - $start, 0 );
2022 if ( $result == -1 || is_null( $result ) ) {
2023 $msg = __METHOD__ . ': timed out waiting on {host} pos {pos} [{seconds}s]';
2024 $this->replLogger->warning( $msg, [
2025 'host' => $conn->getServer(),
2026 'pos' => $pos,
2027 'seconds' => round( $seconds, 6 ),
2028 'trace' => ( new RuntimeException() )->getTraceAsString()
2029 ] );
2030 $ok = false;
2031 } else {
2032 $this->replLogger->debug( __METHOD__ . ': done waiting' );
2033 $ok = true;
2034 }
2035 } else {
2036 $ok = false; // something is misconfigured
2037 $this->replLogger->error(
2038 __METHOD__ . ': could not get master pos for {host}',
2039 [
2040 'host' => $conn->getServer(),
2041 'trace' => ( new RuntimeException() )->getTraceAsString()
2042 ]
2043 );
2044 }
2045
2046 return $ok;
2047 }
2048
2049 /**
2050 * Wait for a replica DB to reach a specified master position
2051 *
2052 * This will connect to the master to get an accurate position if $pos is not given
2053 *
2054 * @param IDatabase $conn Replica DB
2055 * @param DBMasterPos|bool $pos Master position; default: current position
2056 * @param int $timeout Timeout in seconds [optional]
2057 * @return bool Success
2058 * @since 1.28
2059 * @deprecated Since 1.34 Use waitForMasterPos() instead
2060 */
2061 public function safeWaitForMasterPos( IDatabase $conn, $pos = false, $timeout = null ) {
2062 return $this->waitForMasterPos( $conn, $pos, $timeout );
2063 }
2064
2065 public function setTransactionListener( $name, callable $callback = null ) {
2066 if ( $callback ) {
2067 $this->trxRecurringCallbacks[$name] = $callback;
2068 } else {
2069 unset( $this->trxRecurringCallbacks[$name] );
2070 }
2071 $this->forEachOpenMasterConnection(
2072 function ( IDatabase $conn ) use ( $name, $callback ) {
2073 $conn->setTransactionListener( $name, $callback );
2074 }
2075 );
2076 }
2077
2078 public function setTableAliases( array $aliases ) {
2079 $this->tableAliases = $aliases;
2080 }
2081
2082 public function setIndexAliases( array $aliases ) {
2083 $this->indexAliases = $aliases;
2084 }
2085
2086 /**
2087 * @param string $prefix
2088 * @deprecated Since 1.33
2089 */
2090 public function setDomainPrefix( $prefix ) {
2091 $this->setLocalDomainPrefix( $prefix );
2092 }
2093
2094 public function setLocalDomainPrefix( $prefix ) {
2095 // Find connections to explicit foreign domains still marked as in-use...
2096 $domainsInUse = [];
2097 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$domainsInUse ) {
2098 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
2099 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
2100 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
2101 $domainsInUse[] = $conn->getDomainID();
2102 }
2103 } );
2104
2105 // Do not switch connections to explicit foreign domains unless marked as safe
2106 if ( $domainsInUse ) {
2107 $domains = implode( ', ', $domainsInUse );
2108 throw new DBUnexpectedError( null,
2109 "Foreign domain connections are still in use ($domains)" );
2110 }
2111
2112 $this->setLocalDomain( new DatabaseDomain(
2113 $this->localDomain->getDatabase(),
2114 $this->localDomain->getSchema(),
2115 $prefix
2116 ) );
2117
2118 // Update the prefix for all local connections...
2119 $this->forEachOpenConnection( function ( IDatabase $db ) use ( $prefix ) {
2120 if ( !$db->getLBInfo( 'foreign' ) ) {
2121 $db->tablePrefix( $prefix );
2122 }
2123 } );
2124 }
2125
2126 public function redefineLocalDomain( $domain ) {
2127 $this->closeAll();
2128
2129 $this->setLocalDomain( DatabaseDomain::newFromId( $domain ) );
2130 }
2131
2132 /**
2133 * @param DatabaseDomain $domain
2134 */
2135 private function setLocalDomain( DatabaseDomain $domain ) {
2136 $this->localDomain = $domain;
2137 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
2138 // always true, gracefully handle the case when they fail to account for escaping.
2139 if ( $this->localDomain->getTablePrefix() != '' ) {
2140 $this->localDomainIdAlias =
2141 $this->localDomain->getDatabase() . '-' . $this->localDomain->getTablePrefix();
2142 } else {
2143 $this->localDomainIdAlias = $this->localDomain->getDatabase();
2144 }
2145 }
2146
2147 /**
2148 * @param int $i Server index
2149 * @param string|null $field Server index field [optional]
2150 * @return array|mixed
2151 * @throws InvalidArgumentException
2152 */
2153 private function getServerInfoStrict( $i, $field = null ) {
2154 if ( !isset( $this->servers[$i] ) || !is_array( $this->servers[$i] ) ) {
2155 throw new InvalidArgumentException( "No server with index '$i'" );
2156 }
2157
2158 if ( $field !== null ) {
2159 if ( !array_key_exists( $field, $this->servers[$i] ) ) {
2160 throw new InvalidArgumentException( "No field '$field' in server index '$i'" );
2161 }
2162
2163 return $this->servers[$i][$field];
2164 }
2165
2166 return $this->servers[$i];
2167 }
2168
2169 function __destruct() {
2170 // Avoid connection leaks for sanity
2171 $this->disable();
2172 }
2173 }
2174
2175 /**
2176 * @deprecated since 1.29
2177 */
2178 class_alias( LoadBalancer::class, 'LoadBalancer' );