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