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