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