rdbms: fix connection reuse logic in LoadBalancer for postgres
[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->isCompatible( $conn->getDomainID() )
960 ) {
961 throw new UnexpectedValueException(
962 "Got connection to '{$conn->getDomainID()}', " .
963 "but expected local domain ('{$this->localDomain}')." );
964 }
965
966 return $conn;
967 }
968
969 /**
970 * Open a connection to a foreign DB, or return one if it is already open.
971 *
972 * Increments a reference count on the returned connection which locks the
973 * connection to the requested domain. This reference count can be
974 * decremented by calling reuseConnection().
975 *
976 * If a connection is open to the appropriate server already, but with the wrong
977 * database, it will be switched to the right database and returned, as long as
978 * it has been freed first with reuseConnection().
979 *
980 * On error, returns false, and the connection which caused the
981 * error will be available via $this->errorConnection.
982 *
983 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
984 *
985 * @param int $i Server index
986 * @param string $domain Domain ID to open
987 * @param int $flags Class CONN_* constant bitfield
988 * @return Database|bool Returns false on connection error
989 * @throws DBError When database selection fails
990 */
991 private function openForeignConnection( $i, $domain, $flags = 0 ) {
992 $domainInstance = DatabaseDomain::newFromId( $domain );
993 $autoCommit = ( ( $flags & self::CONN_TRX_AUTOCOMMIT ) == self::CONN_TRX_AUTOCOMMIT );
994
995 if ( $autoCommit ) {
996 $connFreeKey = self::KEY_FOREIGN_FREE_NOROUND;
997 $connInUseKey = self::KEY_FOREIGN_INUSE_NOROUND;
998 } else {
999 $connFreeKey = self::KEY_FOREIGN_FREE;
1000 $connInUseKey = self::KEY_FOREIGN_INUSE;
1001 }
1002
1003 /** @var Database $conn */
1004 $conn = null;
1005
1006 if ( isset( $this->conns[$connInUseKey][$i][$domain] ) ) {
1007 // Reuse an in-use connection for the same domain
1008 $conn = $this->conns[$connInUseKey][$i][$domain];
1009 $this->connLogger->debug( __METHOD__ . ": reusing connection $i/$domain" );
1010 } elseif ( isset( $this->conns[$connFreeKey][$i][$domain] ) ) {
1011 // Reuse a free connection for the same domain
1012 $conn = $this->conns[$connFreeKey][$i][$domain];
1013 unset( $this->conns[$connFreeKey][$i][$domain] );
1014 $this->conns[$connInUseKey][$i][$domain] = $conn;
1015 $this->connLogger->debug( __METHOD__ . ": reusing free connection $i/$domain" );
1016 } elseif ( !empty( $this->conns[$connFreeKey][$i] ) ) {
1017 // Reuse a free connection from another domain if possible
1018 foreach ( $this->conns[$connFreeKey][$i] as $oldDomain => $conn ) {
1019 if ( $domainInstance->getDatabase() !== null ) {
1020 // Check if changing the database will require a new connection.
1021 // In that case, leave the connection handle alone and keep looking.
1022 // This prevents connections from being closed mid-transaction and can
1023 // also avoid overhead if the same database will later be requested.
1024 if (
1025 $conn->databasesAreIndependent() &&
1026 $conn->getDBname() !== $domainInstance->getDatabase()
1027 ) {
1028 continue;
1029 }
1030 // Select the new database, schema, and prefix
1031 $conn->selectDomain( $domainInstance );
1032 } else {
1033 // Stay on the current database, but update the schema/prefix
1034 $conn->dbSchema( $domainInstance->getSchema() );
1035 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1036 }
1037 unset( $this->conns[$connFreeKey][$i][$oldDomain] );
1038 // Note that if $domain is an empty string, getDomainID() might not match it
1039 $this->conns[$connInUseKey][$i][$conn->getDomainId()] = $conn;
1040 $this->connLogger->debug( __METHOD__ .
1041 ": reusing free connection from $oldDomain for $domain" );
1042 break;
1043 }
1044 }
1045
1046 if ( !$conn ) {
1047 if ( !isset( $this->servers[$i] ) || !is_array( $this->servers[$i] ) ) {
1048 throw new InvalidArgumentException( "No server with index '$i'." );
1049 }
1050 // Open a new connection
1051 $server = $this->servers[$i];
1052 $server['serverIndex'] = $i;
1053 $server['foreignPoolRefCount'] = 0;
1054 $server['foreign'] = true;
1055 $server['autoCommitOnly'] = $autoCommit;
1056 $conn = $this->reallyOpenConnection( $server, $domainInstance );
1057 if ( !$conn->isOpen() ) {
1058 $this->connLogger->warning( __METHOD__ . ": connection error for $i/$domain" );
1059 $this->errorConnection = $conn;
1060 $conn = false;
1061 } else {
1062 // Note that if $domain is an empty string, getDomainID() might not match it
1063 $this->conns[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1064 $this->connLogger->debug( __METHOD__ . ": opened new connection for $i/$domain" );
1065 }
1066 }
1067
1068 if ( $conn instanceof IDatabase ) {
1069 // Final sanity check to make sure the right domain is selected
1070 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1071 throw new UnexpectedValueException(
1072 "Got connection to '{$conn->getDomainID()}', but expected '$domain'." );
1073 }
1074 // Increment reference count
1075 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1076 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
1077 }
1078
1079 return $conn;
1080 }
1081
1082 public function getServerAttributes( $i ) {
1083 return Database::attributesFromType(
1084 $this->getServerType( $i ),
1085 $this->servers[$i]['driver'] ?? null
1086 );
1087 }
1088
1089 /**
1090 * Test if the specified index represents an open connection
1091 *
1092 * @param int $index Server index
1093 * @access private
1094 * @return bool
1095 */
1096 private function isOpen( $index ) {
1097 if ( !is_int( $index ) ) {
1098 return false;
1099 }
1100
1101 return (bool)$this->getAnyOpenConnection( $index );
1102 }
1103
1104 /**
1105 * Open a new network connection to a server (uncached)
1106 *
1107 * Returns a Database object whether or not the connection was successful.
1108 *
1109 * @param array $server
1110 * @param DatabaseDomain $domain Domain the connection is for, possibly unspecified
1111 * @return Database
1112 * @throws DBAccessError
1113 * @throws InvalidArgumentException
1114 */
1115 protected function reallyOpenConnection( array $server, DatabaseDomain $domain ) {
1116 if ( $this->disabled ) {
1117 throw new DBAccessError();
1118 }
1119
1120 if ( $domain->getDatabase() === null ) {
1121 // The database domain does not specify a DB name and some database systems require a
1122 // valid DB specified on connection. The $server configuration array contains a default
1123 // DB name to use for connections in such cases.
1124 if ( $server['type'] === 'mysql' ) {
1125 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1126 // and the DB name in $server might not exist due to legacy reasons (the default
1127 // domain used to ignore the local LB domain, even when mismatched).
1128 $server['dbname'] = null;
1129 }
1130 } else {
1131 $server['dbname'] = $domain->getDatabase();
1132 }
1133
1134 if ( $domain->getSchema() !== null ) {
1135 $server['schema'] = $domain->getSchema();
1136 }
1137
1138 // It is always possible to connect with any prefix, even the empty string
1139 $server['tablePrefix'] = $domain->getTablePrefix();
1140
1141 // Let the handle know what the cluster master is (e.g. "db1052")
1142 $masterName = $this->getServerName( $this->getWriterIndex() );
1143 $server['clusterMasterHost'] = $masterName;
1144
1145 // Log when many connection are made on requests
1146 if ( ++$this->connsOpened >= self::CONN_HELD_WARN_THRESHOLD ) {
1147 $this->perfLogger->warning( __METHOD__ . ": " .
1148 "{$this->connsOpened}+ connections made (master=$masterName)" );
1149 }
1150
1151 $server['srvCache'] = $this->srvCache;
1152 // Set loggers and profilers
1153 $server['connLogger'] = $this->connLogger;
1154 $server['queryLogger'] = $this->queryLogger;
1155 $server['errorLogger'] = $this->errorLogger;
1156 $server['deprecationLogger'] = $this->deprecationLogger;
1157 $server['profiler'] = $this->profiler;
1158 $server['trxProfiler'] = $this->trxProfiler;
1159 // Use the same agent and PHP mode for all DB handles
1160 $server['cliMode'] = $this->cliMode;
1161 $server['agent'] = $this->agent;
1162 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1163 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1164 $server['flags'] = $server['flags'] ?? IDatabase::DBO_DEFAULT;
1165
1166 // Create a live connection object
1167 try {
1168 $db = Database::factory( $server['type'], $server );
1169 } catch ( DBConnectionError $e ) {
1170 // FIXME: This is probably the ugliest thing I have ever done to
1171 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1172 $db = $e->db;
1173 }
1174
1175 $db->setLBInfo( $server );
1176 $db->setLazyMasterHandle(
1177 $this->getLazyConnectionRef( self::DB_MASTER, [], $db->getDomainID() )
1178 );
1179 $db->setTableAliases( $this->tableAliases );
1180 $db->setIndexAliases( $this->indexAliases );
1181
1182 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1183 if ( $this->trxRoundId !== false ) {
1184 $this->applyTransactionRoundFlags( $db );
1185 }
1186 foreach ( $this->trxRecurringCallbacks as $name => $callback ) {
1187 $db->setTransactionListener( $name, $callback );
1188 }
1189 }
1190
1191 return $db;
1192 }
1193
1194 /**
1195 * @throws DBConnectionError
1196 */
1197 private function reportConnectionError() {
1198 $conn = $this->errorConnection; // the connection which caused the error
1199 $context = [
1200 'method' => __METHOD__,
1201 'last_error' => $this->lastError,
1202 ];
1203
1204 if ( $conn instanceof IDatabase ) {
1205 $context['db_server'] = $conn->getServer();
1206 $this->connLogger->warning(
1207 __METHOD__ . ": connection error: {last_error} ({db_server})",
1208 $context
1209 );
1210
1211 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1212 } else {
1213 // No last connection, probably due to all servers being too busy
1214 $this->connLogger->error(
1215 __METHOD__ .
1216 ": LB failure with no last connection. Connection error: {last_error}",
1217 $context
1218 );
1219
1220 // If all servers were busy, "lastError" will contain something sensible
1221 throw new DBConnectionError( null, $this->lastError );
1222 }
1223 }
1224
1225 public function getWriterIndex() {
1226 return 0;
1227 }
1228
1229 public function haveIndex( $i ) {
1230 return array_key_exists( $i, $this->servers );
1231 }
1232
1233 public function isNonZeroLoad( $i ) {
1234 return array_key_exists( $i, $this->servers ) && $this->loads[$i] != 0;
1235 }
1236
1237 public function getServerCount() {
1238 return count( $this->servers );
1239 }
1240
1241 public function getServerName( $i ) {
1242 if ( isset( $this->servers[$i]['hostName'] ) ) {
1243 $name = $this->servers[$i]['hostName'];
1244 } elseif ( isset( $this->servers[$i]['host'] ) ) {
1245 $name = $this->servers[$i]['host'];
1246 } else {
1247 $name = '';
1248 }
1249
1250 return ( $name != '' ) ? $name : 'localhost';
1251 }
1252
1253 public function getServerInfo( $i ) {
1254 if ( isset( $this->servers[$i] ) ) {
1255 return $this->servers[$i];
1256 } else {
1257 return false;
1258 }
1259 }
1260
1261 public function getServerType( $i ) {
1262 return $this->servers[$i]['type'] ?? 'unknown';
1263 }
1264
1265 public function getMasterPos() {
1266 # If this entire request was served from a replica DB without opening a connection to the
1267 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1268 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1269 if ( !$masterConn ) {
1270 $serverCount = count( $this->servers );
1271 for ( $i = 1; $i < $serverCount; $i++ ) {
1272 $conn = $this->getAnyOpenConnection( $i );
1273 if ( $conn ) {
1274 return $conn->getReplicaPos();
1275 }
1276 }
1277 } else {
1278 return $masterConn->getMasterPos();
1279 }
1280
1281 return false;
1282 }
1283
1284 public function disable() {
1285 $this->closeAll();
1286 $this->disabled = true;
1287 }
1288
1289 public function closeAll() {
1290 $fname = __METHOD__;
1291 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( $fname ) {
1292 $host = $conn->getServer();
1293 $this->connLogger->debug(
1294 $fname . ": closing connection to database '$host'." );
1295 $conn->close();
1296 } );
1297
1298 $this->conns = [
1299 self::KEY_LOCAL => [],
1300 self::KEY_FOREIGN_INUSE => [],
1301 self::KEY_FOREIGN_FREE => [],
1302 self::KEY_LOCAL_NOROUND => [],
1303 self::KEY_FOREIGN_INUSE_NOROUND => [],
1304 self::KEY_FOREIGN_FREE_NOROUND => []
1305 ];
1306 $this->connsOpened = 0;
1307 }
1308
1309 public function closeConnection( IDatabase $conn ) {
1310 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1311 foreach ( $this->conns as $type => $connsByServer ) {
1312 if ( !isset( $connsByServer[$serverIndex] ) ) {
1313 continue;
1314 }
1315
1316 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1317 if ( $conn === $trackedConn ) {
1318 $host = $this->getServerName( $i );
1319 $this->connLogger->debug(
1320 __METHOD__ . ": closing connection to database $i at '$host'." );
1321 unset( $this->conns[$type][$serverIndex][$i] );
1322 --$this->connsOpened;
1323 break 2;
1324 }
1325 }
1326 }
1327
1328 $conn->close();
1329 }
1330
1331 public function commitAll( $fname = __METHOD__ ) {
1332 $this->commitMasterChanges( $fname );
1333 $this->flushMasterSnapshots( $fname );
1334 $this->flushReplicaSnapshots( $fname );
1335 }
1336
1337 public function finalizeMasterChanges() {
1338 $this->assertTransactionRoundStage( [ self::ROUND_CURSORY, self::ROUND_FINALIZED ] );
1339
1340 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1341 // Loop until callbacks stop adding callbacks on other connections
1342 $total = 0;
1343 do {
1344 $count = 0; // callbacks execution attempts
1345 $this->forEachOpenMasterConnection( function ( Database $conn ) use ( &$count ) {
1346 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1347 // Any error should cause all (peer) transactions to be rolled back together.
1348 $count += $conn->runOnTransactionPreCommitCallbacks();
1349 } );
1350 $total += $count;
1351 } while ( $count > 0 );
1352 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1353 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1354 $conn->setTrxEndCallbackSuppression( true );
1355 } );
1356 $this->trxRoundStage = self::ROUND_FINALIZED;
1357
1358 return $total;
1359 }
1360
1361 public function approveMasterChanges( array $options ) {
1362 $this->assertTransactionRoundStage( self::ROUND_FINALIZED );
1363
1364 $limit = $options['maxWriteDuration'] ?? 0;
1365
1366 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1367 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $limit ) {
1368 // If atomic sections or explicit transactions are still open, some caller must have
1369 // caught an exception but failed to properly rollback any changes. Detect that and
1370 // throw and error (causing rollback).
1371 $conn->assertNoOpenTransactions();
1372 // Assert that the time to replicate the transaction will be sane.
1373 // If this fails, then all DB transactions will be rollback back together.
1374 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY );
1375 if ( $limit > 0 && $time > $limit ) {
1376 throw new DBTransactionSizeError(
1377 $conn,
1378 "Transaction spent $time second(s) in writes, exceeding the limit of $limit.",
1379 [ $time, $limit ]
1380 );
1381 }
1382 // If a connection sits idle while slow queries execute on another, that connection
1383 // may end up dropped before the commit round is reached. Ping servers to detect this.
1384 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1385 throw new DBTransactionError(
1386 $conn,
1387 "A connection to the {$conn->getDBname()} database was lost before commit."
1388 );
1389 }
1390 } );
1391 $this->trxRoundStage = self::ROUND_APPROVED;
1392 }
1393
1394 public function beginMasterChanges( $fname = __METHOD__ ) {
1395 if ( $this->trxRoundId !== false ) {
1396 throw new DBTransactionError(
1397 null,
1398 "$fname: Transaction round '{$this->trxRoundId}' already started."
1399 );
1400 }
1401 $this->assertTransactionRoundStage( self::ROUND_CURSORY );
1402
1403 // Clear any empty transactions (no writes/callbacks) from the implicit round
1404 $this->flushMasterSnapshots( $fname );
1405
1406 $this->trxRoundId = $fname;
1407 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1408 // Mark applicable handles as participating in this explicit transaction round.
1409 // For each of these handles, any writes and callbacks will be tied to a single
1410 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1411 // are part of an en masse commit or an en masse rollback.
1412 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1413 $this->applyTransactionRoundFlags( $conn );
1414 } );
1415 $this->trxRoundStage = self::ROUND_CURSORY;
1416 }
1417
1418 public function commitMasterChanges( $fname = __METHOD__ ) {
1419 $this->assertTransactionRoundStage( self::ROUND_APPROVED );
1420
1421 $failures = [];
1422
1423 /** @noinspection PhpUnusedLocalVariableInspection */
1424 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1425
1426 $restore = ( $this->trxRoundId !== false );
1427 $this->trxRoundId = false;
1428 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1429 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1430 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1431 $this->forEachOpenMasterConnection(
1432 function ( IDatabase $conn ) use ( $fname, &$failures ) {
1433 try {
1434 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1435 } catch ( DBError $e ) {
1436 ( $this->errorLogger )( $e );
1437 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1438 }
1439 }
1440 );
1441 if ( $failures ) {
1442 throw new DBTransactionError(
1443 null,
1444 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1445 );
1446 }
1447 if ( $restore ) {
1448 // Unmark handles as participating in this explicit transaction round
1449 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1450 $this->undoTransactionRoundFlags( $conn );
1451 } );
1452 }
1453 $this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS;
1454 }
1455
1456 public function runMasterTransactionIdleCallbacks() {
1457 if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
1458 $type = IDatabase::TRIGGER_COMMIT;
1459 } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
1460 $type = IDatabase::TRIGGER_ROLLBACK;
1461 } else {
1462 throw new DBTransactionError(
1463 null,
1464 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1465 );
1466 }
1467
1468 $oldStage = $this->trxRoundStage;
1469 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1470
1471 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1472 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1473 $conn->setTrxEndCallbackSuppression( false );
1474 } );
1475
1476 $e = null; // first exception
1477 $fname = __METHOD__;
1478 // Loop until callbacks stop adding callbacks on other connections
1479 do {
1480 // Run any pending callbacks for each connection...
1481 $count = 0; // callback execution attempts
1482 $this->forEachOpenMasterConnection(
1483 function ( Database $conn ) use ( $type, &$e, &$count ) {
1484 if ( $conn->trxLevel() ) {
1485 return; // retry in the next iteration, after commit() is called
1486 }
1487 try {
1488 $count += $conn->runOnTransactionIdleCallbacks( $type );
1489 } catch ( Exception $ex ) {
1490 $e = $e ?: $ex;
1491 }
1492 }
1493 );
1494 // Clear out any active transactions left over from callbacks...
1495 $this->forEachOpenMasterConnection( function ( Database $conn ) use ( &$e, $fname ) {
1496 if ( $conn->writesPending() ) {
1497 // A callback from another handle wrote to this one and DBO_TRX is set
1498 $this->queryLogger->warning( $fname . ": found writes pending." );
1499 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1500 $this->queryLogger->warning(
1501 $fname . ": found writes pending ($fnames).",
1502 [
1503 'db_server' => $conn->getServer(),
1504 'db_name' => $conn->getDBname()
1505 ]
1506 );
1507 } elseif ( $conn->trxLevel() ) {
1508 // A callback from another handle read from this one and DBO_TRX is set,
1509 // which can easily happen if there is only one DB (no replicas)
1510 $this->queryLogger->debug( $fname . ": found empty transaction." );
1511 }
1512 try {
1513 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1514 } catch ( Exception $ex ) {
1515 $e = $e ?: $ex;
1516 }
1517 } );
1518 } while ( $count > 0 );
1519
1520 $this->trxRoundStage = $oldStage;
1521
1522 return $e;
1523 }
1524
1525 public function runMasterTransactionListenerCallbacks() {
1526 if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
1527 $type = IDatabase::TRIGGER_COMMIT;
1528 } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
1529 $type = IDatabase::TRIGGER_ROLLBACK;
1530 } else {
1531 throw new DBTransactionError(
1532 null,
1533 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1534 );
1535 }
1536
1537 $e = null;
1538
1539 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1540 $this->forEachOpenMasterConnection( function ( Database $conn ) use ( $type, &$e ) {
1541 try {
1542 $conn->runTransactionListenerCallbacks( $type );
1543 } catch ( Exception $ex ) {
1544 $e = $e ?: $ex;
1545 }
1546 } );
1547 $this->trxRoundStage = self::ROUND_CURSORY;
1548
1549 return $e;
1550 }
1551
1552 public function rollbackMasterChanges( $fname = __METHOD__ ) {
1553 $restore = ( $this->trxRoundId !== false );
1554 $this->trxRoundId = false;
1555 $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1556 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $fname ) {
1557 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS );
1558 } );
1559 if ( $restore ) {
1560 // Unmark handles as participating in this explicit transaction round
1561 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1562 $this->undoTransactionRoundFlags( $conn );
1563 } );
1564 }
1565 $this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS;
1566 }
1567
1568 /**
1569 * @param string|string[] $stage
1570 */
1571 private function assertTransactionRoundStage( $stage ) {
1572 $stages = (array)$stage;
1573
1574 if ( !in_array( $this->trxRoundStage, $stages, true ) ) {
1575 $stageList = implode(
1576 '/',
1577 array_map( function ( $v ) {
1578 return "'$v'";
1579 }, $stages )
1580 );
1581 throw new DBTransactionError(
1582 null,
1583 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1584 );
1585 }
1586 }
1587
1588 /**
1589 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1590 *
1591 * Some servers may have neither flag enabled, meaning that they opt out of such
1592 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1593 * when a DB server is used for something like simple key/value storage.
1594 *
1595 * @param Database $conn
1596 */
1597 private function applyTransactionRoundFlags( Database $conn ) {
1598 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1599 return; // transaction rounds do not apply to these connections
1600 }
1601
1602 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1603 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1604 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1605 $conn->setFlag( $conn::DBO_TRX, $conn::REMEMBER_PRIOR );
1606 }
1607
1608 if ( $conn->getFlag( $conn::DBO_TRX ) ) {
1609 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId );
1610 }
1611 }
1612
1613 /**
1614 * @param Database $conn
1615 */
1616 private function undoTransactionRoundFlags( Database $conn ) {
1617 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1618 return; // transaction rounds do not apply to these connections
1619 }
1620
1621 if ( $conn->getFlag( $conn::DBO_TRX ) ) {
1622 $conn->setLBInfo( 'trxRoundId', false );
1623 }
1624
1625 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1626 $conn->restoreFlags( $conn::RESTORE_PRIOR );
1627 }
1628 }
1629
1630 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
1631 $this->forEachOpenReplicaConnection( function ( IDatabase $conn ) use ( $fname ) {
1632 $conn->flushSnapshot( $fname );
1633 } );
1634 }
1635
1636 public function flushMasterSnapshots( $fname = __METHOD__ ) {
1637 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $fname ) {
1638 $conn->flushSnapshot( $fname );
1639 } );
1640 }
1641
1642 /**
1643 * @return string
1644 * @since 1.32
1645 */
1646 public function getTransactionRoundStage() {
1647 return $this->trxRoundStage;
1648 }
1649
1650 public function hasMasterConnection() {
1651 return $this->isOpen( $this->getWriterIndex() );
1652 }
1653
1654 public function hasMasterChanges() {
1655 $pending = 0;
1656 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$pending ) {
1657 $pending |= $conn->writesOrCallbacksPending();
1658 } );
1659
1660 return (bool)$pending;
1661 }
1662
1663 public function lastMasterChangeTimestamp() {
1664 $lastTime = false;
1665 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$lastTime ) {
1666 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1667 } );
1668
1669 return $lastTime;
1670 }
1671
1672 public function hasOrMadeRecentMasterChanges( $age = null ) {
1673 $age = ( $age === null ) ? $this->waitTimeout : $age;
1674
1675 return ( $this->hasMasterChanges()
1676 || $this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1677 }
1678
1679 public function pendingMasterChangeCallers() {
1680 $fnames = [];
1681 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$fnames ) {
1682 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1683 } );
1684
1685 return $fnames;
1686 }
1687
1688 public function getLaggedReplicaMode( $domain = false ) {
1689 // No-op if there is only one DB (also avoids recursion)
1690 if ( !$this->laggedReplicaMode && $this->getServerCount() > 1 ) {
1691 try {
1692 // See if laggedReplicaMode gets set
1693 $conn = $this->getConnection( self::DB_REPLICA, false, $domain );
1694 $this->reuseConnection( $conn );
1695 } catch ( DBConnectionError $e ) {
1696 // Avoid expensive re-connect attempts and failures
1697 $this->allReplicasDownMode = true;
1698 $this->laggedReplicaMode = true;
1699 }
1700 }
1701
1702 return $this->laggedReplicaMode;
1703 }
1704
1705 public function laggedReplicaUsed() {
1706 return $this->laggedReplicaMode;
1707 }
1708
1709 /**
1710 * @return bool
1711 * @since 1.27
1712 * @deprecated Since 1.28; use laggedReplicaUsed()
1713 */
1714 public function laggedSlaveUsed() {
1715 return $this->laggedReplicaUsed();
1716 }
1717
1718 public function getReadOnlyReason( $domain = false, IDatabase $conn = null ) {
1719 if ( $this->readOnlyReason !== false ) {
1720 return $this->readOnlyReason;
1721 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1722 if ( $this->allReplicasDownMode ) {
1723 return 'The database has been automatically locked ' .
1724 'until the replica database servers become available';
1725 } else {
1726 return 'The database has been automatically locked ' .
1727 'while the replica database servers catch up to the master.';
1728 }
1729 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1730 return 'The database master is running in read-only mode.';
1731 }
1732
1733 return false;
1734 }
1735
1736 /**
1737 * @param string $domain Domain ID, or false for the current domain
1738 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1739 * @return bool
1740 */
1741 private function masterRunningReadOnly( $domain, IDatabase $conn = null ) {
1742 $cache = $this->wanCache;
1743 $masterServer = $this->getServerName( $this->getWriterIndex() );
1744
1745 return (bool)$cache->getWithSetCallback(
1746 $cache->makeGlobalKey( __CLASS__, 'server-read-only', $masterServer ),
1747 self::TTL_CACHE_READONLY,
1748 function () use ( $domain, $conn ) {
1749 $old = $this->trxProfiler->setSilenced( true );
1750 try {
1751 $dbw = $conn ?: $this->getConnection( self::DB_MASTER, [], $domain );
1752 $readOnly = (int)$dbw->serverIsReadOnly();
1753 if ( !$conn ) {
1754 $this->reuseConnection( $dbw );
1755 }
1756 } catch ( DBError $e ) {
1757 $readOnly = 0;
1758 }
1759 $this->trxProfiler->setSilenced( $old );
1760 return $readOnly;
1761 },
1762 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'busyValue' => 0 ]
1763 );
1764 }
1765
1766 public function allowLagged( $mode = null ) {
1767 if ( $mode === null ) {
1768 return $this->allowLagged;
1769 }
1770 $this->allowLagged = $mode;
1771
1772 return $this->allowLagged;
1773 }
1774
1775 public function pingAll() {
1776 $success = true;
1777 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$success ) {
1778 if ( !$conn->ping() ) {
1779 $success = false;
1780 }
1781 } );
1782
1783 return $success;
1784 }
1785
1786 public function forEachOpenConnection( $callback, array $params = [] ) {
1787 foreach ( $this->conns as $connsByServer ) {
1788 foreach ( $connsByServer as $serverConns ) {
1789 foreach ( $serverConns as $conn ) {
1790 $callback( $conn, ...$params );
1791 }
1792 }
1793 }
1794 }
1795
1796 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1797 $masterIndex = $this->getWriterIndex();
1798 foreach ( $this->conns as $connsByServer ) {
1799 if ( isset( $connsByServer[$masterIndex] ) ) {
1800 /** @var IDatabase $conn */
1801 foreach ( $connsByServer[$masterIndex] as $conn ) {
1802 $callback( $conn, ...$params );
1803 }
1804 }
1805 }
1806 }
1807
1808 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1809 foreach ( $this->conns as $connsByServer ) {
1810 foreach ( $connsByServer as $i => $serverConns ) {
1811 if ( $i === $this->getWriterIndex() ) {
1812 continue; // skip master
1813 }
1814 foreach ( $serverConns as $conn ) {
1815 $callback( $conn, ...$params );
1816 }
1817 }
1818 }
1819 }
1820
1821 public function getMaxLag( $domain = false ) {
1822 $maxLag = -1;
1823 $host = '';
1824 $maxIndex = 0;
1825
1826 if ( $this->getServerCount() <= 1 ) {
1827 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1828 }
1829
1830 $lagTimes = $this->getLagTimes( $domain );
1831 foreach ( $lagTimes as $i => $lag ) {
1832 if ( $this->loads[$i] > 0 && $lag > $maxLag ) {
1833 $maxLag = $lag;
1834 $host = $this->servers[$i]['host'];
1835 $maxIndex = $i;
1836 }
1837 }
1838
1839 return [ $host, $maxLag, $maxIndex ];
1840 }
1841
1842 public function getLagTimes( $domain = false ) {
1843 if ( $this->getServerCount() <= 1 ) {
1844 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1845 }
1846
1847 $knownLagTimes = []; // map of (server index => 0 seconds)
1848 $indexesWithLag = [];
1849 foreach ( $this->servers as $i => $server ) {
1850 if ( empty( $server['is static'] ) ) {
1851 $indexesWithLag[] = $i; // DB server might have replication lag
1852 } else {
1853 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1854 }
1855 }
1856
1857 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) + $knownLagTimes;
1858 }
1859
1860 public function safeGetLag( IDatabase $conn ) {
1861 if ( $this->getServerCount() <= 1 ) {
1862 return 0;
1863 } else {
1864 return $conn->getLag();
1865 }
1866 }
1867
1868 /**
1869 * @param IDatabase $conn
1870 * @param DBMasterPos|bool $pos
1871 * @param int|null $timeout
1872 * @return bool
1873 */
1874 public function safeWaitForMasterPos( IDatabase $conn, $pos = false, $timeout = null ) {
1875 $timeout = max( 1, $timeout ?: $this->waitTimeout );
1876
1877 if ( $this->getServerCount() <= 1 || !$conn->getLBInfo( 'replica' ) ) {
1878 return true; // server is not a replica DB
1879 }
1880
1881 if ( !$pos ) {
1882 // Get the current master position, opening a connection if needed
1883 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1884 if ( $masterConn ) {
1885 $pos = $masterConn->getMasterPos();
1886 } else {
1887 $masterConn = $this->openConnection( $this->getWriterIndex(), self::DOMAIN_ANY );
1888 $pos = $masterConn->getMasterPos();
1889 $this->closeConnection( $masterConn );
1890 }
1891 }
1892
1893 if ( $pos instanceof DBMasterPos ) {
1894 $result = $conn->masterPosWait( $pos, $timeout );
1895 if ( $result == -1 || is_null( $result ) ) {
1896 $msg = __METHOD__ . ': timed out waiting on {host} pos {pos}';
1897 $this->replLogger->warning( $msg, [
1898 'host' => $conn->getServer(),
1899 'pos' => $pos,
1900 'trace' => ( new RuntimeException() )->getTraceAsString()
1901 ] );
1902 $ok = false;
1903 } else {
1904 $this->replLogger->debug( __METHOD__ . ': done waiting' );
1905 $ok = true;
1906 }
1907 } else {
1908 $ok = false; // something is misconfigured
1909 $this->replLogger->error(
1910 __METHOD__ . ': could not get master pos for {host}',
1911 [
1912 'host' => $conn->getServer(),
1913 'trace' => ( new RuntimeException() )->getTraceAsString()
1914 ]
1915 );
1916 }
1917
1918 return $ok;
1919 }
1920
1921 public function setTransactionListener( $name, callable $callback = null ) {
1922 if ( $callback ) {
1923 $this->trxRecurringCallbacks[$name] = $callback;
1924 } else {
1925 unset( $this->trxRecurringCallbacks[$name] );
1926 }
1927 $this->forEachOpenMasterConnection(
1928 function ( IDatabase $conn ) use ( $name, $callback ) {
1929 $conn->setTransactionListener( $name, $callback );
1930 }
1931 );
1932 }
1933
1934 public function setTableAliases( array $aliases ) {
1935 $this->tableAliases = $aliases;
1936 }
1937
1938 public function setIndexAliases( array $aliases ) {
1939 $this->indexAliases = $aliases;
1940 }
1941
1942 public function setDomainPrefix( $prefix ) {
1943 // Find connections to explicit foreign domains still marked as in-use...
1944 $domainsInUse = [];
1945 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$domainsInUse ) {
1946 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1947 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1948 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1949 $domainsInUse[] = $conn->getDomainID();
1950 }
1951 } );
1952
1953 // Do not switch connections to explicit foreign domains unless marked as safe
1954 if ( $domainsInUse ) {
1955 $domains = implode( ', ', $domainsInUse );
1956 throw new DBUnexpectedError( null,
1957 "Foreign domain connections are still in use ($domains)." );
1958 }
1959
1960 $this->setLocalDomain( new DatabaseDomain(
1961 $this->localDomain->getDatabase(),
1962 $this->localDomain->getSchema(),
1963 $prefix
1964 ) );
1965
1966 // Update the prefix for all local connections...
1967 $this->forEachOpenConnection( function ( IDatabase $db ) use ( $prefix ) {
1968 if ( !$db->getLBInfo( 'foreign' ) ) {
1969 $db->tablePrefix( $prefix );
1970 }
1971 } );
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 /**
1990 * Make PHP ignore user aborts/disconnects until the returned
1991 * value leaves scope. This returns null and does nothing in CLI mode.
1992 *
1993 * @return ScopedCallback|null
1994 */
1995 final protected function getScopedPHPBehaviorForCommit() {
1996 if ( PHP_SAPI != 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1997 $old = ignore_user_abort( true ); // avoid half-finished operations
1998 return new ScopedCallback( function () use ( $old ) {
1999 ignore_user_abort( $old );
2000 } );
2001 }
2002
2003 return null;
2004 }
2005
2006 function __destruct() {
2007 // Avoid connection leaks for sanity
2008 $this->disable();
2009 }
2010 }
2011
2012 /**
2013 * @deprecated since 1.29
2014 */
2015 class_alias( LoadBalancer::class, 'LoadBalancer' );