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