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