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