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