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