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