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