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