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