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