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