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