rdbms: rename setDomainPrefix to setLocalDomainPrefix in ILoadBalancer
[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 if ( $conn instanceof DBConnRef ) {
1285 // Avoid calling close() but still leaving the handle in the pool
1286 throw new RuntimeException( __METHOD__ . ': got DBConnRef instance.' );
1287 }
1288
1289 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1290 foreach ( $this->conns as $type => $connsByServer ) {
1291 if ( !isset( $connsByServer[$serverIndex] ) ) {
1292 continue;
1293 }
1294
1295 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1296 if ( $conn === $trackedConn ) {
1297 $host = $this->getServerName( $i );
1298 $this->connLogger->debug(
1299 __METHOD__ . ": closing connection to database $i at '$host'." );
1300 unset( $this->conns[$type][$serverIndex][$i] );
1301 --$this->connsOpened;
1302 break 2;
1303 }
1304 }
1305 }
1306
1307 $conn->close();
1308 }
1309
1310 public function commitAll( $fname = __METHOD__ ) {
1311 $this->commitMasterChanges( $fname );
1312 $this->flushMasterSnapshots( $fname );
1313 $this->flushReplicaSnapshots( $fname );
1314 }
1315
1316 public function finalizeMasterChanges() {
1317 $this->assertTransactionRoundStage( [ self::ROUND_CURSORY, self::ROUND_FINALIZED ] );
1318
1319 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1320 // Loop until callbacks stop adding callbacks on other connections
1321 $total = 0;
1322 do {
1323 $count = 0; // callbacks execution attempts
1324 $this->forEachOpenMasterConnection( function ( Database $conn ) use ( &$count ) {
1325 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1326 // Any error should cause all (peer) transactions to be rolled back together.
1327 $count += $conn->runOnTransactionPreCommitCallbacks();
1328 } );
1329 $total += $count;
1330 } while ( $count > 0 );
1331 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1332 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1333 $conn->setTrxEndCallbackSuppression( true );
1334 } );
1335 $this->trxRoundStage = self::ROUND_FINALIZED;
1336
1337 return $total;
1338 }
1339
1340 public function approveMasterChanges( array $options ) {
1341 $this->assertTransactionRoundStage( self::ROUND_FINALIZED );
1342
1343 $limit = $options['maxWriteDuration'] ?? 0;
1344
1345 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1346 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $limit ) {
1347 // If atomic sections or explicit transactions are still open, some caller must have
1348 // caught an exception but failed to properly rollback any changes. Detect that and
1349 // throw and error (causing rollback).
1350 $conn->assertNoOpenTransactions();
1351 // Assert that the time to replicate the transaction will be sane.
1352 // If this fails, then all DB transactions will be rollback back together.
1353 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY );
1354 if ( $limit > 0 && $time > $limit ) {
1355 throw new DBTransactionSizeError(
1356 $conn,
1357 "Transaction spent $time second(s) in writes, exceeding the limit of $limit.",
1358 [ $time, $limit ]
1359 );
1360 }
1361 // If a connection sits idle while slow queries execute on another, that connection
1362 // may end up dropped before the commit round is reached. Ping servers to detect this.
1363 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1364 throw new DBTransactionError(
1365 $conn,
1366 "A connection to the {$conn->getDBname()} database was lost before commit."
1367 );
1368 }
1369 } );
1370 $this->trxRoundStage = self::ROUND_APPROVED;
1371 }
1372
1373 public function beginMasterChanges( $fname = __METHOD__ ) {
1374 if ( $this->trxRoundId !== false ) {
1375 throw new DBTransactionError(
1376 null,
1377 "$fname: Transaction round '{$this->trxRoundId}' already started."
1378 );
1379 }
1380 $this->assertTransactionRoundStage( self::ROUND_CURSORY );
1381
1382 // Clear any empty transactions (no writes/callbacks) from the implicit round
1383 $this->flushMasterSnapshots( $fname );
1384
1385 $this->trxRoundId = $fname;
1386 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1387 // Mark applicable handles as participating in this explicit transaction round.
1388 // For each of these handles, any writes and callbacks will be tied to a single
1389 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1390 // are part of an en masse commit or an en masse rollback.
1391 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1392 $this->applyTransactionRoundFlags( $conn );
1393 } );
1394 $this->trxRoundStage = self::ROUND_CURSORY;
1395 }
1396
1397 public function commitMasterChanges( $fname = __METHOD__ ) {
1398 $this->assertTransactionRoundStage( self::ROUND_APPROVED );
1399
1400 $failures = [];
1401
1402 /** @noinspection PhpUnusedLocalVariableInspection */
1403 $scope = ScopedCallback::newScopedIgnoreUserAbort(); // try to ignore client aborts
1404
1405 $restore = ( $this->trxRoundId !== false );
1406 $this->trxRoundId = false;
1407 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1408 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1409 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1410 $this->forEachOpenMasterConnection(
1411 function ( IDatabase $conn ) use ( $fname, &$failures ) {
1412 try {
1413 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1414 } catch ( DBError $e ) {
1415 ( $this->errorLogger )( $e );
1416 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1417 }
1418 }
1419 );
1420 if ( $failures ) {
1421 throw new DBTransactionError(
1422 null,
1423 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1424 );
1425 }
1426 if ( $restore ) {
1427 // Unmark handles as participating in this explicit transaction round
1428 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1429 $this->undoTransactionRoundFlags( $conn );
1430 } );
1431 }
1432 $this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS;
1433 }
1434
1435 public function runMasterTransactionIdleCallbacks() {
1436 if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
1437 $type = IDatabase::TRIGGER_COMMIT;
1438 } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
1439 $type = IDatabase::TRIGGER_ROLLBACK;
1440 } else {
1441 throw new DBTransactionError(
1442 null,
1443 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1444 );
1445 }
1446
1447 $oldStage = $this->trxRoundStage;
1448 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1449
1450 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1451 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1452 $conn->setTrxEndCallbackSuppression( false );
1453 } );
1454
1455 $e = null; // first exception
1456 $fname = __METHOD__;
1457 // Loop until callbacks stop adding callbacks on other connections
1458 do {
1459 // Run any pending callbacks for each connection...
1460 $count = 0; // callback execution attempts
1461 $this->forEachOpenMasterConnection(
1462 function ( Database $conn ) use ( $type, &$e, &$count ) {
1463 if ( $conn->trxLevel() ) {
1464 return; // retry in the next iteration, after commit() is called
1465 }
1466 try {
1467 $count += $conn->runOnTransactionIdleCallbacks( $type );
1468 } catch ( Exception $ex ) {
1469 $e = $e ?: $ex;
1470 }
1471 }
1472 );
1473 // Clear out any active transactions left over from callbacks...
1474 $this->forEachOpenMasterConnection( function ( Database $conn ) use ( &$e, $fname ) {
1475 if ( $conn->writesPending() ) {
1476 // A callback from another handle wrote to this one and DBO_TRX is set
1477 $this->queryLogger->warning( $fname . ": found writes pending." );
1478 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1479 $this->queryLogger->warning(
1480 $fname . ": found writes pending ($fnames).",
1481 [
1482 'db_server' => $conn->getServer(),
1483 'db_name' => $conn->getDBname()
1484 ]
1485 );
1486 } elseif ( $conn->trxLevel() ) {
1487 // A callback from another handle read from this one and DBO_TRX is set,
1488 // which can easily happen if there is only one DB (no replicas)
1489 $this->queryLogger->debug( $fname . ": found empty transaction." );
1490 }
1491 try {
1492 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1493 } catch ( Exception $ex ) {
1494 $e = $e ?: $ex;
1495 }
1496 } );
1497 } while ( $count > 0 );
1498
1499 $this->trxRoundStage = $oldStage;
1500
1501 return $e;
1502 }
1503
1504 public function runMasterTransactionListenerCallbacks() {
1505 if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
1506 $type = IDatabase::TRIGGER_COMMIT;
1507 } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
1508 $type = IDatabase::TRIGGER_ROLLBACK;
1509 } else {
1510 throw new DBTransactionError(
1511 null,
1512 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1513 );
1514 }
1515
1516 $e = null;
1517
1518 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1519 $this->forEachOpenMasterConnection( function ( Database $conn ) use ( $type, &$e ) {
1520 try {
1521 $conn->runTransactionListenerCallbacks( $type );
1522 } catch ( Exception $ex ) {
1523 $e = $e ?: $ex;
1524 }
1525 } );
1526 $this->trxRoundStage = self::ROUND_CURSORY;
1527
1528 return $e;
1529 }
1530
1531 public function rollbackMasterChanges( $fname = __METHOD__ ) {
1532 $restore = ( $this->trxRoundId !== false );
1533 $this->trxRoundId = false;
1534 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1535 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $fname ) {
1536 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS );
1537 } );
1538 if ( $restore ) {
1539 // Unmark handles as participating in this explicit transaction round
1540 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1541 $this->undoTransactionRoundFlags( $conn );
1542 } );
1543 }
1544 $this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS;
1545 }
1546
1547 /**
1548 * @param string|string[] $stage
1549 */
1550 private function assertTransactionRoundStage( $stage ) {
1551 $stages = (array)$stage;
1552
1553 if ( !in_array( $this->trxRoundStage, $stages, true ) ) {
1554 $stageList = implode(
1555 '/',
1556 array_map( function ( $v ) {
1557 return "'$v'";
1558 }, $stages )
1559 );
1560 throw new DBTransactionError(
1561 null,
1562 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1563 );
1564 }
1565 }
1566
1567 /**
1568 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1569 *
1570 * Some servers may have neither flag enabled, meaning that they opt out of such
1571 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1572 * when a DB server is used for something like simple key/value storage.
1573 *
1574 * @param Database $conn
1575 */
1576 private function applyTransactionRoundFlags( Database $conn ) {
1577 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1578 return; // transaction rounds do not apply to these connections
1579 }
1580
1581 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1582 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1583 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1584 $conn->setFlag( $conn::DBO_TRX, $conn::REMEMBER_PRIOR );
1585 }
1586
1587 if ( $conn->getFlag( $conn::DBO_TRX ) ) {
1588 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId );
1589 }
1590 }
1591
1592 /**
1593 * @param Database $conn
1594 */
1595 private function undoTransactionRoundFlags( Database $conn ) {
1596 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1597 return; // transaction rounds do not apply to these connections
1598 }
1599
1600 if ( $conn->getFlag( $conn::DBO_TRX ) ) {
1601 $conn->setLBInfo( 'trxRoundId', false );
1602 }
1603
1604 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1605 $conn->restoreFlags( $conn::RESTORE_PRIOR );
1606 }
1607 }
1608
1609 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
1610 $this->forEachOpenReplicaConnection( function ( IDatabase $conn ) use ( $fname ) {
1611 $conn->flushSnapshot( $fname );
1612 } );
1613 }
1614
1615 public function flushMasterSnapshots( $fname = __METHOD__ ) {
1616 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $fname ) {
1617 $conn->flushSnapshot( $fname );
1618 } );
1619 }
1620
1621 /**
1622 * @return string
1623 * @since 1.32
1624 */
1625 public function getTransactionRoundStage() {
1626 return $this->trxRoundStage;
1627 }
1628
1629 public function hasMasterConnection() {
1630 return $this->isOpen( $this->getWriterIndex() );
1631 }
1632
1633 public function hasMasterChanges() {
1634 $pending = 0;
1635 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$pending ) {
1636 $pending |= $conn->writesOrCallbacksPending();
1637 } );
1638
1639 return (bool)$pending;
1640 }
1641
1642 public function lastMasterChangeTimestamp() {
1643 $lastTime = false;
1644 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$lastTime ) {
1645 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1646 } );
1647
1648 return $lastTime;
1649 }
1650
1651 public function hasOrMadeRecentMasterChanges( $age = null ) {
1652 $age = ( $age === null ) ? $this->waitTimeout : $age;
1653
1654 return ( $this->hasMasterChanges()
1655 || $this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1656 }
1657
1658 public function pendingMasterChangeCallers() {
1659 $fnames = [];
1660 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$fnames ) {
1661 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1662 } );
1663
1664 return $fnames;
1665 }
1666
1667 public function getLaggedReplicaMode( $domain = false ) {
1668 // No-op if there is only one DB (also avoids recursion)
1669 if ( !$this->laggedReplicaMode && $this->getServerCount() > 1 ) {
1670 try {
1671 // See if laggedReplicaMode gets set
1672 $conn = $this->getConnection( self::DB_REPLICA, false, $domain );
1673 $this->reuseConnection( $conn );
1674 } catch ( DBConnectionError $e ) {
1675 // Avoid expensive re-connect attempts and failures
1676 $this->allReplicasDownMode = true;
1677 $this->laggedReplicaMode = true;
1678 }
1679 }
1680
1681 return $this->laggedReplicaMode;
1682 }
1683
1684 public function laggedReplicaUsed() {
1685 return $this->laggedReplicaMode;
1686 }
1687
1688 /**
1689 * @return bool
1690 * @since 1.27
1691 * @deprecated Since 1.28; use laggedReplicaUsed()
1692 */
1693 public function laggedSlaveUsed() {
1694 return $this->laggedReplicaUsed();
1695 }
1696
1697 public function getReadOnlyReason( $domain = false, IDatabase $conn = null ) {
1698 if ( $this->readOnlyReason !== false ) {
1699 return $this->readOnlyReason;
1700 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1701 if ( $this->allReplicasDownMode ) {
1702 return 'The database has been automatically locked ' .
1703 'until the replica database servers become available';
1704 } else {
1705 return 'The database has been automatically locked ' .
1706 'while the replica database servers catch up to the master.';
1707 }
1708 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1709 return 'The database master is running in read-only mode.';
1710 }
1711
1712 return false;
1713 }
1714
1715 /**
1716 * @param string $domain Domain ID, or false for the current domain
1717 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1718 * @return bool
1719 */
1720 private function masterRunningReadOnly( $domain, IDatabase $conn = null ) {
1721 $cache = $this->wanCache;
1722 $masterServer = $this->getServerName( $this->getWriterIndex() );
1723
1724 return (bool)$cache->getWithSetCallback(
1725 $cache->makeGlobalKey( __CLASS__, 'server-read-only', $masterServer ),
1726 self::TTL_CACHE_READONLY,
1727 function () use ( $domain, $conn ) {
1728 $old = $this->trxProfiler->setSilenced( true );
1729 try {
1730 $dbw = $conn ?: $this->getConnection( self::DB_MASTER, [], $domain );
1731 $readOnly = (int)$dbw->serverIsReadOnly();
1732 if ( !$conn ) {
1733 $this->reuseConnection( $dbw );
1734 }
1735 } catch ( DBError $e ) {
1736 $readOnly = 0;
1737 }
1738 $this->trxProfiler->setSilenced( $old );
1739 return $readOnly;
1740 },
1741 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'busyValue' => 0 ]
1742 );
1743 }
1744
1745 public function allowLagged( $mode = null ) {
1746 if ( $mode === null ) {
1747 return $this->allowLagged;
1748 }
1749 $this->allowLagged = $mode;
1750
1751 return $this->allowLagged;
1752 }
1753
1754 public function pingAll() {
1755 $success = true;
1756 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$success ) {
1757 if ( !$conn->ping() ) {
1758 $success = false;
1759 }
1760 } );
1761
1762 return $success;
1763 }
1764
1765 public function forEachOpenConnection( $callback, array $params = [] ) {
1766 foreach ( $this->conns as $connsByServer ) {
1767 foreach ( $connsByServer as $serverConns ) {
1768 foreach ( $serverConns as $conn ) {
1769 $callback( $conn, ...$params );
1770 }
1771 }
1772 }
1773 }
1774
1775 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1776 $masterIndex = $this->getWriterIndex();
1777 foreach ( $this->conns as $connsByServer ) {
1778 if ( isset( $connsByServer[$masterIndex] ) ) {
1779 /** @var IDatabase $conn */
1780 foreach ( $connsByServer[$masterIndex] as $conn ) {
1781 $callback( $conn, ...$params );
1782 }
1783 }
1784 }
1785 }
1786
1787 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1788 foreach ( $this->conns as $connsByServer ) {
1789 foreach ( $connsByServer as $i => $serverConns ) {
1790 if ( $i === $this->getWriterIndex() ) {
1791 continue; // skip master
1792 }
1793 foreach ( $serverConns as $conn ) {
1794 $callback( $conn, ...$params );
1795 }
1796 }
1797 }
1798 }
1799
1800 public function getMaxLag( $domain = false ) {
1801 $maxLag = -1;
1802 $host = '';
1803 $maxIndex = 0;
1804
1805 if ( $this->getServerCount() <= 1 ) {
1806 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1807 }
1808
1809 $lagTimes = $this->getLagTimes( $domain );
1810 foreach ( $lagTimes as $i => $lag ) {
1811 if ( $this->loads[$i] > 0 && $lag > $maxLag ) {
1812 $maxLag = $lag;
1813 $host = $this->servers[$i]['host'];
1814 $maxIndex = $i;
1815 }
1816 }
1817
1818 return [ $host, $maxLag, $maxIndex ];
1819 }
1820
1821 public function getLagTimes( $domain = false ) {
1822 if ( $this->getServerCount() <= 1 ) {
1823 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1824 }
1825
1826 $knownLagTimes = []; // map of (server index => 0 seconds)
1827 $indexesWithLag = [];
1828 foreach ( $this->servers as $i => $server ) {
1829 if ( empty( $server['is static'] ) ) {
1830 $indexesWithLag[] = $i; // DB server might have replication lag
1831 } else {
1832 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1833 }
1834 }
1835
1836 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) + $knownLagTimes;
1837 }
1838
1839 public function safeGetLag( IDatabase $conn ) {
1840 if ( $this->getServerCount() <= 1 ) {
1841 return 0;
1842 } else {
1843 return $conn->getLag();
1844 }
1845 }
1846
1847 /**
1848 * @param IDatabase $conn
1849 * @param DBMasterPos|bool $pos
1850 * @param int|null $timeout
1851 * @return bool
1852 */
1853 public function safeWaitForMasterPos( IDatabase $conn, $pos = false, $timeout = null ) {
1854 $timeout = max( 1, $timeout ?: $this->waitTimeout );
1855
1856 if ( $this->getServerCount() <= 1 || !$conn->getLBInfo( 'replica' ) ) {
1857 return true; // server is not a replica DB
1858 }
1859
1860 if ( !$pos ) {
1861 // Get the current master position, opening a connection if needed
1862 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1863 if ( $masterConn ) {
1864 $pos = $masterConn->getMasterPos();
1865 } else {
1866 $masterConn = $this->openConnection( $this->getWriterIndex(), self::DOMAIN_ANY );
1867 $pos = $masterConn->getMasterPos();
1868 $this->closeConnection( $masterConn );
1869 }
1870 }
1871
1872 if ( $pos instanceof DBMasterPos ) {
1873 $result = $conn->masterPosWait( $pos, $timeout );
1874 if ( $result == -1 || is_null( $result ) ) {
1875 $msg = __METHOD__ . ': timed out waiting on {host} pos {pos}';
1876 $this->replLogger->warning( $msg, [
1877 'host' => $conn->getServer(),
1878 'pos' => $pos,
1879 'trace' => ( new RuntimeException() )->getTraceAsString()
1880 ] );
1881 $ok = false;
1882 } else {
1883 $this->replLogger->debug( __METHOD__ . ': done waiting' );
1884 $ok = true;
1885 }
1886 } else {
1887 $ok = false; // something is misconfigured
1888 $this->replLogger->error(
1889 __METHOD__ . ': could not get master pos for {host}',
1890 [
1891 'host' => $conn->getServer(),
1892 'trace' => ( new RuntimeException() )->getTraceAsString()
1893 ]
1894 );
1895 }
1896
1897 return $ok;
1898 }
1899
1900 public function setTransactionListener( $name, callable $callback = null ) {
1901 if ( $callback ) {
1902 $this->trxRecurringCallbacks[$name] = $callback;
1903 } else {
1904 unset( $this->trxRecurringCallbacks[$name] );
1905 }
1906 $this->forEachOpenMasterConnection(
1907 function ( IDatabase $conn ) use ( $name, $callback ) {
1908 $conn->setTransactionListener( $name, $callback );
1909 }
1910 );
1911 }
1912
1913 public function setTableAliases( array $aliases ) {
1914 $this->tableAliases = $aliases;
1915 }
1916
1917 public function setIndexAliases( array $aliases ) {
1918 $this->indexAliases = $aliases;
1919 }
1920
1921 /**
1922 * @param string $prefix
1923 * @deprecated Since 1.33
1924 */
1925 public function setDomainPrefix( $prefix ) {
1926 $this->setLocalDomainPrefix( $prefix );
1927 }
1928
1929 public function setLocalDomainPrefix( $prefix ) {
1930 // Find connections to explicit foreign domains still marked as in-use...
1931 $domainsInUse = [];
1932 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$domainsInUse ) {
1933 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1934 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1935 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1936 $domainsInUse[] = $conn->getDomainID();
1937 }
1938 } );
1939
1940 // Do not switch connections to explicit foreign domains unless marked as safe
1941 if ( $domainsInUse ) {
1942 $domains = implode( ', ', $domainsInUse );
1943 throw new DBUnexpectedError( null,
1944 "Foreign domain connections are still in use ($domains)." );
1945 }
1946
1947 $this->setLocalDomain( new DatabaseDomain(
1948 $this->localDomain->getDatabase(),
1949 $this->localDomain->getSchema(),
1950 $prefix
1951 ) );
1952
1953 // Update the prefix for all local connections...
1954 $this->forEachOpenConnection( function ( IDatabase $db ) use ( $prefix ) {
1955 if ( !$db->getLBInfo( 'foreign' ) ) {
1956 $db->tablePrefix( $prefix );
1957 }
1958 } );
1959 }
1960
1961 public function redefineLocalDomain( $domain ) {
1962 $this->closeAll();
1963
1964 $this->setLocalDomain( DatabaseDomain::newFromId( $domain ) );
1965 }
1966
1967 /**
1968 * @param DatabaseDomain $domain
1969 */
1970 private function setLocalDomain( DatabaseDomain $domain ) {
1971 $this->localDomain = $domain;
1972 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
1973 // always true, gracefully handle the case when they fail to account for escaping.
1974 if ( $this->localDomain->getTablePrefix() != '' ) {
1975 $this->localDomainIdAlias =
1976 $this->localDomain->getDatabase() . '-' . $this->localDomain->getTablePrefix();
1977 } else {
1978 $this->localDomainIdAlias = $this->localDomain->getDatabase();
1979 }
1980 }
1981
1982 function __destruct() {
1983 // Avoid connection leaks for sanity
1984 $this->disable();
1985 }
1986 }
1987
1988 /**
1989 * @deprecated since 1.29
1990 */
1991 class_alias( LoadBalancer::class, 'LoadBalancer' );