MediaWiki  master
LoadBalancer.php
Go to the documentation of this file.
1 <?php
22 namespace Wikimedia\Rdbms;
23 
24 use ArrayUtils;
25 use BagOStuff;
26 use EmptyBagOStuff;
27 use InvalidArgumentException;
28 use LogicException;
29 use Psr\Log\LoggerInterface;
30 use Psr\Log\NullLogger;
31 use RuntimeException;
32 use Throwable;
33 use UnexpectedValueException;
34 use WANObjectCache;
35 use Wikimedia\RequestTimeout\CriticalSectionProvider;
36 use Wikimedia\ScopedCallback;
37 
43 class LoadBalancer implements ILoadBalancer {
45  private $loadMonitor;
47  private $csProvider;
51  private $srvCache;
53  private $wanCache;
58  private $profiler;
60  private $trxProfiler;
62  private $connLogger;
64  private $queryLogger;
66  private $replLogger;
68  private $perfLogger;
70  private $errorLogger;
73 
75  private $localDomain;
76 
78  private $conns;
79 
81  private $clusterName;
83  private $servers;
85  private $groupLoads;
87  private $maxLagByIndex;
89  private $waitTimeout;
93  private $maxLag;
95  private $defaultGroup;
96 
98  private $cliMode;
100  private $agent;
101 
103  private $tableAliases = [];
105  private $indexAliases = [];
107  private $domainAliases = [];
111  private $tempTablesOnlyMode = [];
112 
114  private $trxRoundId = false;
120  private $readIndexByGroup = [];
122  private $waitForPos;
124  private $laggedReplicaMode = false;
126  private $lastError = 'Unknown error';
128  private $readOnlyReason = false;
130  private $connectionCounter = 0;
132  private $disabled = false;
135 
137  private $id;
139  private $ownerId;
140 
142  private $nonLocalDomainCache = [];
143 
144  private const INFO_SERVER_INDEX = 'serverIndex';
145  private const INFO_AUTOCOMMIT_ONLY = 'autoCommitOnly';
146  private const INFO_FORIEGN = 'foreign';
147  private const INFO_FOREIGN_REF_COUNT = 'foreignPoolRefCount';
148 
153  public const MAX_LAG_DEFAULT = 6;
154 
156  private const CONN_HELD_WARN_THRESHOLD = 10;
157 
159  private const MAX_WAIT_DEFAULT = 10;
161  private const TTL_CACHE_READONLY = 5;
162 
163  private const KEY_LOCAL = 'local';
164  private const KEY_FOREIGN_FREE = 'foreignFree';
165  private const KEY_FOREIGN_INUSE = 'foreignInUse';
166 
167  private const KEY_LOCAL_NOROUND = 'localAutoCommit';
168  private const KEY_FOREIGN_FREE_NOROUND = 'foreignFreeAutoCommit';
169  private const KEY_FOREIGN_INUSE_NOROUND = 'foreignInUseAutoCommit';
170 
171  private const KEY_LOCAL_DOMAIN = '__local__';
172 
174  private const ROUND_CURSORY = 'cursory';
176  private const ROUND_FINALIZED = 'finalized';
178  private const ROUND_APPROVED = 'approved';
180  private const ROUND_COMMIT_CALLBACKS = 'commit-callbacks';
182  private const ROUND_ROLLBACK_CALLBACKS = 'rollback-callbacks';
184  private const ROUND_ERROR = 'error';
185 
187  private const READER_INDEX_NONE = -1;
188 
189  public function __construct( array $params ) {
190  if ( !isset( $params['servers'] ) || !count( $params['servers'] ) ) {
191  throw new InvalidArgumentException( 'Missing or empty "servers" parameter' );
192  }
193 
194  $localDomain = isset( $params['localDomain'] )
195  ? DatabaseDomain::newFromId( $params['localDomain'] )
197  $this->setLocalDomain( $localDomain );
198 
199  $this->maxLag = $params['maxLag'] ?? self::MAX_LAG_DEFAULT;
200 
201  $listKey = -1;
202  $this->servers = [];
203  $this->groupLoads = [ self::GROUP_GENERIC => [] ];
204  foreach ( $params['servers'] as $i => $server ) {
205  if ( ++$listKey !== $i ) {
206  throw new UnexpectedValueException( 'List expected for "servers" parameter' );
207  }
208  $this->servers[$i] = $server;
209  foreach ( ( $server['groupLoads'] ?? [] ) as $group => $ratio ) {
210  $this->groupLoads[$group][$i] = $ratio;
211  }
212  $this->groupLoads[self::GROUP_GENERIC][$i] = $server['load'];
213  $this->maxLagByIndex[$i] = $server['max lag'] ?? $this->maxLag;
214  }
215 
216  $this->waitTimeout = $params['waitTimeout'] ?? self::MAX_WAIT_DEFAULT;
217 
218  $this->conns = self::newTrackedConnectionsArray();
219 
220  if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
221  $this->readOnlyReason = $params['readOnlyReason'];
222  }
223 
224  $this->loadMonitorConfig = $params['loadMonitor'] ?? [ 'class' => 'LoadMonitorNull' ];
225  $this->loadMonitorConfig += [ 'lagWarnThreshold' => $this->maxLag ];
226 
227  $this->srvCache = $params['srvCache'] ?? new EmptyBagOStuff();
228  $this->wanCache = $params['wanCache'] ?? WANObjectCache::newEmpty();
229  $this->errorLogger = $params['errorLogger'] ?? static function ( Throwable $e ) {
230  trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
231  };
232  $this->deprecationLogger = $params['deprecationLogger'] ?? static function ( $msg ) {
233  trigger_error( $msg, E_USER_DEPRECATED );
234  };
235  $this->replLogger = $params['replLogger'] ?? new NullLogger();
236  $this->connLogger = $params['connLogger'] ?? new NullLogger();
237  $this->queryLogger = $params['queryLogger'] ?? new NullLogger();
238  $this->perfLogger = $params['perfLogger'] ?? new NullLogger();
239 
240  $this->clusterName = $params['clusterName'] ?? null;
241  $this->profiler = $params['profiler'] ?? null;
242  $this->trxProfiler = $params['trxProfiler'] ?? new TransactionProfiler();
243 
244  $this->csProvider = $params['criticalSectionProvider'] ?? null;
245 
246  $this->cliMode = $params['cliMode'] ?? ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' );
247  $this->agent = $params['agent'] ?? '';
248 
249  if ( isset( $params['chronologyCallback'] ) ) {
250  $this->chronologyCallback = $params['chronologyCallback'];
251  }
252 
253  if ( isset( $params['roundStage'] ) ) {
254  if ( $params['roundStage'] === self::STAGE_POSTCOMMIT_CALLBACKS ) {
255  $this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS;
256  } elseif ( $params['roundStage'] === self::STAGE_POSTROLLBACK_CALLBACKS ) {
257  $this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS;
258  }
259  }
260 
261  $group = $params['defaultGroup'] ?? self::GROUP_GENERIC;
262  $this->defaultGroup = isset( $this->groupLoads[$group] ) ? $group : self::GROUP_GENERIC;
263 
264  static $nextId;
265  $this->id = $nextId = ( is_int( $nextId ) ? $nextId++ : mt_rand() );
266  $this->ownerId = $params['ownerId'] ?? null;
267  }
268 
269  private static function newTrackedConnectionsArray() {
270  return [
271  // Connection were transaction rounds may be applied
272  self::KEY_LOCAL => [],
273  self::KEY_FOREIGN_INUSE => [],
274  self::KEY_FOREIGN_FREE => [],
275  // Auto-committing counterpart connections that ignore transaction rounds
276  self::KEY_LOCAL_NOROUND => [],
277  self::KEY_FOREIGN_INUSE_NOROUND => [],
278  self::KEY_FOREIGN_FREE_NOROUND => []
279  ];
280  }
281 
282  public function getClusterName(): string {
283  if ( $this->clusterName !== null ) {
284  $name = $this->clusterName;
285  } else {
286  // Fallback to the current primary name if not specified
287  $name = $this->getServerName( $this->getWriterIndex() );
288  }
289 
290  return $name;
291  }
292 
293  public function getLocalDomainID(): string {
294  return $this->localDomain->getId();
295  }
296 
297  public function resolveDomainID( $domain ): string {
298  return $this->resolveDomainInstance( $domain )->getId();
299  }
300 
305  final protected function resolveDomainInstance( $domain ): DatabaseDomain {
306  if ( $domain instanceof DatabaseDomain ) {
307  return $domain; // already a domain instance
308  } elseif ( $domain === false || $domain === $this->localDomain->getId() ) {
309  return $this->localDomain;
310  } elseif ( isset( $this->domainAliases[$domain] ) ) {
311  $this->domainAliases[$domain] =
312  DatabaseDomain::newFromId( $this->domainAliases[$domain] );
313 
314  return $this->domainAliases[$domain];
315  }
316 
317  $cachedDomain = $this->nonLocalDomainCache[$domain] ?? null;
318  if ( $cachedDomain === null ) {
319  $cachedDomain = DatabaseDomain::newFromId( $domain );
320  $this->nonLocalDomainCache = [ $domain => $cachedDomain ];
321  }
322 
323  return $cachedDomain;
324  }
325 
333  private function resolveGroups( $groups, $i ) {
334  // If a specific replica server was specified, then $groups makes no sense
335  if ( $i > 0 && $groups !== [] && $groups !== false ) {
336  $list = implode( ', ', (array)$groups );
337  throw new LogicException( "Query group(s) ($list) given with server index (#$i)" );
338  }
339 
340  if ( $groups === [] || $groups === false || $groups === $this->defaultGroup ) {
341  $resolvedGroups = [ $this->defaultGroup ]; // common case
342  } elseif ( is_string( $groups ) && isset( $this->groupLoads[$groups] ) ) {
343  $resolvedGroups = [ $groups, $this->defaultGroup ];
344  } elseif ( is_array( $groups ) ) {
345  $resolvedGroups = $groups;
346  if ( array_search( $this->defaultGroup, $resolvedGroups ) === false ) {
347  $resolvedGroups[] = $this->defaultGroup;
348  }
349  } else {
350  $resolvedGroups = [ $this->defaultGroup ];
351  }
352 
353  return $resolvedGroups;
354  }
355 
362  private function sanitizeConnectionFlags( $flags, $i, $domain ) {
363  // Whether an outside caller is explicitly requesting the primary database server
364  if ( $i === self::DB_PRIMARY || $i === $this->getWriterIndex() ) {
365  $flags |= self::CONN_INTENT_WRITABLE;
366  }
367 
368  if ( self::fieldHasBit( $flags, self::CONN_TRX_AUTOCOMMIT ) ) {
369  // Callers use CONN_TRX_AUTOCOMMIT to bypass REPEATABLE-READ staleness without
370  // resorting to row locks (e.g. FOR UPDATE) or to make small out-of-band commits
371  // during larger transactions. This is useful for avoiding lock contention.
372 
373  // Primary DB server attributes (should match those of the replica DB servers)
374  $attributes = $this->getServerAttributes( $this->getWriterIndex() );
375  if ( $attributes[Database::ATTR_DB_LEVEL_LOCKING] ) {
376  // The RDBMS does not support concurrent writes (e.g. SQLite), so attempts
377  // to use separate connections would just cause self-deadlocks. Note that
378  // REPEATABLE-READ staleness is not an issue since DB-level locking means
379  // that transactions are Strict Serializable anyway.
380  $flags &= ~self::CONN_TRX_AUTOCOMMIT;
381  $type = $this->getServerType( $this->getWriterIndex() );
382  $this->connLogger->info( __METHOD__ . ": CONN_TRX_AUTOCOMMIT disallowed ($type)" );
383  } elseif ( isset( $this->tempTablesOnlyMode[$domain] ) ) {
384  // T202116: integration tests are active and queries should be all be using
385  // temporary clone tables (via prefix). Such tables are not visible across
386  // different connections nor can there be REPEATABLE-READ snapshot staleness,
387  // so use the same connection for everything.
388  $flags &= ~self::CONN_TRX_AUTOCOMMIT;
389  }
390  }
391 
392  return $flags;
393  }
394 
400  private function enforceConnectionFlags( IDatabase $conn, $flags ) {
401  if ( self::fieldHasBit( $flags, self::CONN_TRX_AUTOCOMMIT ) ) {
402  if ( $conn->trxLevel() ) {
403  throw new DBUnexpectedError(
404  $conn,
405  'Handle requested with CONN_TRX_AUTOCOMMIT yet it has a transaction'
406  );
407  }
408 
409  $conn->clearFlag( $conn::DBO_TRX ); // auto-commit mode
410  }
411  }
412 
418  private function getLoadMonitor() {
419  if ( !isset( $this->loadMonitor ) ) {
420  $compat = [
421  'LoadMonitor' => LoadMonitor::class,
422  'LoadMonitorNull' => LoadMonitorNull::class,
423  'LoadMonitorMySQL' => LoadMonitorMySQL::class,
424  ];
425 
426  $class = $this->loadMonitorConfig['class'];
427  if ( isset( $compat[$class] ) ) {
428  $class = $compat[$class];
429  }
430 
431  $this->loadMonitor = new $class(
432  $this, $this->srvCache, $this->wanCache, $this->loadMonitorConfig );
433  $this->loadMonitor->setLogger( $this->replLogger );
434  }
435 
436  return $this->loadMonitor;
437  }
438 
445  private function getRandomNonLagged( array $loads, string $domain, $maxLag = INF ) {
446  $lags = $this->getLagTimes( $domain );
447 
448  # Unset excessively lagged servers
449  foreach ( $lags as $i => $lag ) {
450  if ( $i !== $this->getWriterIndex() ) {
451  # How much lag this server nominally is allowed to have
452  $maxServerLag = $this->servers[$i]['max lag'] ?? $this->maxLag; // default
453  # Constrain that further by $maxLag argument
454  $maxServerLag = min( $maxServerLag, $maxLag );
455 
456  $srvName = $this->getServerName( $i );
457  if ( $lag === false && !is_infinite( $maxServerLag ) ) {
458  $this->replLogger->debug(
459  __METHOD__ . ": server {db_server} is not replicating?",
460  [ 'db_server' => $srvName ]
461  );
462  unset( $loads[$i] );
463  } elseif ( $lag > $maxServerLag ) {
464  $this->replLogger->debug(
465  __METHOD__ .
466  ": server {db_server} has {lag} seconds of lag (>= {maxlag})",
467  [ 'db_server' => $srvName, 'lag' => $lag, 'maxlag' => $maxServerLag ]
468  );
469  unset( $loads[$i] );
470  }
471  }
472  }
473 
474  # Find out if all the replica DBs with non-zero load are lagged
475  $sum = 0;
476  foreach ( $loads as $load ) {
477  $sum += $load;
478  }
479  if ( $sum == 0 ) {
480  # No appropriate DB servers except maybe the primary and some replica DBs with zero load
481  # Do NOT use the primary DB
482  # Instead, this function will return false, triggering read-only mode,
483  # and a lagged replica DB will be used instead.
484  return false;
485  }
486 
487  if ( count( $loads ) == 0 ) {
488  return false;
489  }
490 
491  # Return a random representative of the remainder
492  return ArrayUtils::pickRandom( $loads );
493  }
494 
503  private function getConnectionIndex( $i, array $groups, $domain ) {
504  if ( $i === self::DB_PRIMARY ) {
505  $i = $this->getWriterIndex();
506  } elseif ( $i === self::DB_REPLICA ) {
507  foreach ( $groups as $group ) {
508  $groupIndex = $this->getReaderIndex( $group, $domain );
509  if ( $groupIndex !== false ) {
510  $i = $groupIndex; // group connection succeeded
511  break;
512  }
513  }
514  } elseif ( !isset( $this->servers[$i] ) ) {
515  throw new UnexpectedValueException( "Invalid server index index #$i" );
516  }
517 
518  if ( $i === self::DB_REPLICA ) {
519  $this->lastError = 'Unknown error'; // set here in case of worse failure
520  $this->lastError = 'No working replica DB server: ' . $this->lastError;
521  $this->reportConnectionError();
522  }
523 
524  return $i;
525  }
526 
527  public function getReaderIndex( $group = false, $domain = false ) {
528  $domain = $this->resolveDomainID( $domain );
529  $group = is_string( $group ) ? $group : self::GROUP_GENERIC;
530 
531  if ( $this->getServerCount() == 1 ) {
532  // Skip the load balancing if there's only one server
533  return $this->getWriterIndex();
534  }
535 
536  $index = $this->getExistingReaderIndex( $group );
537  if ( $index !== self::READER_INDEX_NONE ) {
538  // A reader index was already selected and "waitForPos" was handled
539  return $index;
540  }
541 
542  // Use the server weight array for this load group
543  if ( isset( $this->groupLoads[$group] ) ) {
544  $loads = $this->groupLoads[$group];
545  } else {
546  $this->connLogger->info( __METHOD__ . ": no loads for group $group" );
547 
548  return false;
549  }
550 
551  // Scale the configured load ratios according to each server's load and state
552  $this->getLoadMonitor()->scaleLoads( $loads, $domain );
553 
554  // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
555  $this->lazyLoadReplicationPositions(); // optimizes server candidate selection
556  list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
557  if ( $i === false ) {
558  // DB connection unsuccessful
559  return false;
560  }
561 
562  // If data seen by queries is expected to reflect the transactions committed as of
563  // or after a given replication position then wait for the DB to apply those changes
564  if ( $this->waitForPos && $i !== $this->getWriterIndex() && !$this->doWait( $i ) ) {
565  // Data will be outdated compared to what was expected
566  $laggedReplicaMode = true;
567  }
568 
569  // Cache the reader index for future DB_REPLICA handles
570  $this->setExistingReaderIndex( $group, $i );
571  // Record whether the generic reader index is in "lagged replica DB" mode
572  if ( $group === self::GROUP_GENERIC && $laggedReplicaMode ) {
573  $this->laggedReplicaMode = true;
574  $this->replLogger->debug( __METHOD__ . ": setting lagged replica mode" );
575  }
576 
577  $serverName = $this->getServerName( $i );
578  $this->connLogger->debug( __METHOD__ . ": using server $serverName for group '$group'" );
579 
580  return $i;
581  }
582 
589  protected function getExistingReaderIndex( $group ) {
590  return $this->readIndexByGroup[$group] ?? self::READER_INDEX_NONE;
591  }
592 
599  private function setExistingReaderIndex( $group, $index ) {
600  if ( $index < 0 ) {
601  throw new UnexpectedValueException( "Cannot set a negative read server index" );
602  }
603  $this->readIndexByGroup[$group] = $index;
604  }
605 
615  private function pickReaderIndex( array $loads, string $domain ) {
616  if ( $loads === [] ) {
617  throw new InvalidArgumentException( "Server configuration array is empty" );
618  }
619 
621  $i = false;
623  $laggedReplicaMode = false;
624 
625  // Quickly look through the available servers for a server that meets criteria...
626  $currentLoads = $loads;
627  while ( count( $currentLoads ) ) {
628  if ( $laggedReplicaMode ) {
629  $i = ArrayUtils::pickRandom( $currentLoads );
630  } else {
631  $i = false;
632  if ( $this->waitForPos && $this->waitForPos->asOfTime() ) {
633  $this->replLogger->debug( __METHOD__ . ": replication positions detected" );
634  // "chronologyCallback" sets "waitForPos" for session consistency.
635  // This triggers doWait() after connect, so it's especially good to
636  // avoid lagged servers so as to avoid excessive delay in that method.
637  $ago = microtime( true ) - $this->waitForPos->asOfTime();
638  // Aim for <= 1 second of waiting (being too picky can backfire)
639  $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago + 1 );
640  }
641  if ( $i === false ) {
642  // Any server with less lag than it's 'max lag' param is preferable
643  $i = $this->getRandomNonLagged( $currentLoads, $domain );
644  }
645  if ( $i === false && count( $currentLoads ) ) {
646  // All replica DBs lagged. Switch to read-only mode
647  $this->replLogger->error(
648  __METHOD__ . ": all replica DBs lagged. Switch to read-only mode",
649  [ 'db_domain' => $domain ]
650  );
651  $i = ArrayUtils::pickRandom( $currentLoads );
652  $laggedReplicaMode = true;
653  }
654  }
655 
656  if ( $i === false ) {
657  // pickRandom() returned false.
658  // This is permanent and means the configuration or the load monitor
659  // wants us to return false.
660  $this->connLogger->debug( __METHOD__ . ": pickRandom() returned false" );
661 
662  return [ false, false ];
663  }
664 
665  $serverName = $this->getServerName( $i );
666  $this->connLogger->debug( __METHOD__ . ": Using reader #$i: $serverName..." );
667 
668  // Get a connection to this server without triggering complementary connections
669  // to other servers (due to things like lag or read-only checks). We want to avoid
670  // the risk of overhead and recursion here.
671  $conn = $this->getServerConnection( $i, $domain, self::CONN_SILENCE_ERRORS );
672  if ( !$conn ) {
673  $this->connLogger->warning(
674  __METHOD__ . ": failed connecting to $i/{db_domain}",
675  [ 'db_domain' => $domain ]
676  );
677  unset( $currentLoads[$i] ); // avoid this server next iteration
678  $i = false;
679  continue;
680  }
681 
682  // Decrement reference counter, we are finished with this connection.
683  // It will be incremented for the caller later.
684  if ( !$this->localDomain->equals( $domain ) ) {
685  $this->reuseConnection( $conn );
686  }
687 
688  // Return this server
689  break;
690  }
691 
692  // If all servers were down, quit now
693  if ( $currentLoads === [] ) {
694  $this->connLogger->error(
695  __METHOD__ . ": all servers down",
696  [ 'db_domain' => $domain ]
697  );
698  }
699 
700  return [ $i, $laggedReplicaMode ];
701  }
702 
703  public function waitFor( $pos ) {
704  $oldPos = $this->waitForPos;
705  try {
706  $this->waitForPos = $pos;
707 
708  $genericIndex = $this->getExistingReaderIndex( self::GROUP_GENERIC );
709  // If a generic reader connection was already established, then wait now.
710  // Otherwise, wait until a connection is established in getReaderIndex().
711  if ( $genericIndex > $this->getWriterIndex() && !$this->doWait( $genericIndex ) ) {
712  $this->laggedReplicaMode = true;
713  $this->replLogger->debug( __METHOD__ . ": setting lagged replica mode" );
714  }
715  } finally {
716  // Restore the older position if it was higher since this is used for lag-protection
717  $this->setWaitForPositionIfHigher( $oldPos );
718  }
719  }
720 
721  public function waitForAll( $pos, $timeout = null ) {
722  $timeout = $timeout ?: $this->waitTimeout;
723 
724  $oldPos = $this->waitForPos;
725  try {
726  $this->waitForPos = $pos;
727 
728  $ok = true;
729  foreach ( $this->getStreamingReplicaIndexes() as $i ) {
730  if ( $this->serverHasLoadInAnyGroup( $i ) ) {
731  $start = microtime( true );
732  $ok = $this->doWait( $i, $timeout ) && $ok;
733  $timeout -= intval( microtime( true ) - $start );
734  if ( $timeout <= 0 ) {
735  break; // timeout reached
736  }
737  }
738  }
739 
740  return $ok;
741  } finally {
742  // Restore the old position; this is used for throttling, not lag-protection
743  $this->waitForPos = $oldPos;
744  }
745  }
746 
751  private function serverHasLoadInAnyGroup( $i ) {
752  foreach ( $this->groupLoads as $loadsByIndex ) {
753  if ( ( $loadsByIndex[$i] ?? 0 ) > 0 ) {
754  return true;
755  }
756  }
757 
758  return false;
759  }
760 
764  private function setWaitForPositionIfHigher( $pos ) {
765  if ( !$pos ) {
766  return;
767  }
768 
769  if ( !$this->waitForPos || $pos->hasReached( $this->waitForPos ) ) {
770  $this->waitForPos = $pos;
771  }
772  }
773 
774  public function getAnyOpenConnection( $i, $flags = 0 ) {
775  $i = ( $i === self::DB_PRIMARY ) ? $this->getWriterIndex() : $i;
776  // Connection handles required to be in auto-commit mode use a separate connection
777  // pool since the main pool is effected by implicit and explicit transaction rounds
778  $autoCommitOnly = self::fieldHasBit( $flags, self::CONN_TRX_AUTOCOMMIT );
779 
780  $conn = false;
781  foreach ( $this->conns as $type => $connsByServer ) {
782  if ( $i === self::DB_REPLICA ) {
783  // Consider all existing connections to any server
784  $applicableConnsByServer = $connsByServer;
785  } else {
786  // Consider all existing connections to a specific server
787  $applicableConnsByServer = isset( $connsByServer[$i] )
788  ? [ $i => $connsByServer[$i] ]
789  : [];
790  }
791 
792  $conn = $this->pickAnyOpenConnection( $applicableConnsByServer, $autoCommitOnly );
793  if ( $conn ) {
794  $this->connLogger->debug( __METHOD__ . ": found '$type' connection to #$i." );
795  break;
796  }
797  }
798 
799  if ( $conn ) {
800  $this->enforceConnectionFlags( $conn, $flags );
801  }
802 
803  return $conn;
804  }
805 
811  private function pickAnyOpenConnection( array $connsByServer, $autoCommitOnly ) {
812  foreach ( $connsByServer as $i => $conns ) {
813  foreach ( $conns as $conn ) {
814  if ( !$conn->isOpen() ) {
815  $this->connLogger->warning(
816  __METHOD__ .
817  ": pooled DB handle for {db_server} (#$i) has no open connection.",
818  $this->getConnLogContext( $conn )
819  );
820 
821  continue; // some sort of error occurred?
822  }
823 
824  if ( $autoCommitOnly ) {
825  // Only accept CONN_TRX_AUTOCOMMIT connections
826  if ( !$conn->getLBInfo( self::INFO_AUTOCOMMIT_ONLY ) ) {
827  // Connection is aware of transaction rounds
828  continue;
829  }
830 
831  if ( $conn->trxLevel() ) {
832  // Some sort of bug left a transaction open
833  $this->connLogger->warning(
834  __METHOD__ .
835  ": pooled DB handle for {db_server} (#$i) has a pending transaction.",
836  $this->getConnLogContext( $conn )
837  );
838 
839  continue;
840  }
841  }
842 
843  return $conn;
844  }
845  }
846 
847  return false;
848  }
849 
857  private function doWait( $index, $timeout = null ) {
858  $timeout = max( 1, intval( $timeout ?: $this->waitTimeout ) );
859 
860  // Check if we already know that the DB has reached this point
861  $srvName = $this->getServerName( $index );
862  $key = $this->srvCache->makeGlobalKey( __CLASS__, 'last-known-pos', $srvName, 'v1' );
864  $knownReachedPos = $this->srvCache->get( $key );
865  if (
866  $knownReachedPos instanceof DBPrimaryPos &&
867  $knownReachedPos->hasReached( $this->waitForPos )
868  ) {
869  $this->replLogger->debug(
870  __METHOD__ .
871  ": replica DB {db_server} known to be caught up (pos >= $knownReachedPos).",
872  [ 'db_server' => $srvName ]
873  );
874 
875  return true;
876  }
877 
878  $close = false; // close the connection afterwards
879  $flags = self::CONN_SILENCE_ERRORS;
880  // Check if there is an existing connection that can be used
881  $conn = $this->getAnyOpenConnection( $index, $flags );
882  if ( !$conn ) {
883  // Get a connection to this server without triggering complementary connections
884  // to other servers (due to things like lag or read-only checks). We want to avoid
885  // the risk of overhead and recursion here.
886  $conn = $this->getServerConnection( $index, self::DOMAIN_ANY, $flags );
887  if ( !$conn ) {
888  $this->replLogger->warning(
889  __METHOD__ . ': failed to connect to {db_server}',
890  [ 'db_server' => $srvName ]
891  );
892 
893  return false;
894  }
895  // Avoid connection spam in waitForAll() when connections
896  // are made just for the sake of doing this lag check.
897  $close = true;
898  }
899 
900  $this->replLogger->info(
901  __METHOD__ .
902  ': waiting for replica DB {db_server} to catch up...',
903  $this->getConnLogContext( $conn )
904  );
905 
906  $result = $conn->primaryPosWait( $this->waitForPos, $timeout );
907 
908  $ok = ( $result !== null && $result != -1 );
909  if ( $ok ) {
910  // Remember that the DB reached this point
911  $this->srvCache->set( $key, $this->waitForPos, BagOStuff::TTL_DAY );
912  }
913 
914  if ( $close ) {
915  $this->closeConnection( $conn );
916  }
917 
918  return $ok;
919  }
920 
921  public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
922  $domain = $this->resolveDomainID( $domain );
923  $groups = $this->resolveGroups( $groups, $i );
924  $flags = $this->sanitizeConnectionFlags( $flags, $i, $domain );
925  // If given DB_PRIMARY/DB_REPLICA, resolve it to a specific server index. Resolving
926  // DB_REPLICA might trigger getServerConnection() calls due to the getReaderIndex()
927  // connectivity checks or LoadMonitor::scaleLoads() server state cache regeneration.
928  // The use of getServerConnection() instead of getConnection() avoids infinite loops.
929  $serverIndex = $this->getConnectionIndex( $i, $groups, $domain );
930  // Get an open connection to that server (might trigger a new connection)
931  $conn = $this->getServerConnection( $serverIndex, $domain, $flags );
932  // Set primary DB handles as read-only if there is high replication lag
933  if (
934  $conn &&
935  $serverIndex === $this->getWriterIndex() &&
936  $this->getLaggedReplicaMode( $domain ) &&
937  !is_string( $conn->getLBInfo( $conn::LB_READ_ONLY_REASON ) )
938  ) {
939  $genericIndex = $this->getExistingReaderIndex( self::GROUP_GENERIC );
940  $reason = ( $genericIndex !== self::READER_INDEX_NONE )
941  ? 'The database is read-only until replication lag decreases.'
942  : 'The database is read-only until replica database servers becomes reachable.';
943  $conn->setLBInfo( $conn::LB_READ_ONLY_REASON, $reason );
944  }
945 
946  return $conn;
947  }
948 
949  public function getServerConnection( $i, $domain, $flags = 0 ) {
950  // Number of connections made before getting the server index and handle
951  $priorConnectionsMade = $this->connectionCounter;
952  // Get an open connection to this server (might trigger a new connection)
953  $conn = $this->localDomain->equals( $domain )
954  ? $this->getLocalConnection( $i, $flags )
955  : $this->getForeignConnection( $i, $domain, $flags );
956  // Throw an error or otherwise bail out if the connection attempt failed
957  if ( !( $conn instanceof IDatabase ) ) {
958  if ( !self::fieldHasBit( $flags, self::CONN_SILENCE_ERRORS ) ) {
959  $this->reportConnectionError();
960  }
961 
962  return false;
963  }
964 
965  // Profile any new connections caused by this method
966  if ( $this->connectionCounter > $priorConnectionsMade ) {
967  $this->trxProfiler->recordConnection(
968  $conn->getServerName(),
969  $conn->getDBname(),
970  self::fieldHasBit( $flags, self::CONN_INTENT_WRITABLE )
971  );
972  }
973 
974  if ( !$conn->isOpen() ) {
975  $this->errorConnection = $conn;
976  // Connection was made but later unrecoverably lost for some reason.
977  // Do not return a handle that will just throw exceptions on use, but
978  // let the calling code, e.g. getReaderIndex(), try another server.
979  // FIXME: report an error here unless CONN_SILENCE_ERRORS was set
980  return false;
981  }
982 
983  // Make sure that flags like CONN_TRX_AUTOCOMMIT are respected by this handle
984  $this->enforceConnectionFlags( $conn, $flags );
985  // Set primary DB handles as read-only if the load balancer is configured as read-only
986  // or the primary database server is running in server-side read-only mode. Note that
987  // replica DB handles are always read-only via Database::assertIsWritablePrimary().
988  // Read-only mode due to replication lag is *avoided* here to avoid recursion.
989  if ( $i === $this->getWriterIndex() ) {
990  if ( $this->readOnlyReason !== false ) {
992  } elseif ( $this->isPrimaryConnectionReadOnly( $conn, $flags ) ) {
993  $readOnlyReason = 'The primary database server is running in read-only mode.';
994  } else {
995  $readOnlyReason = false;
996  }
997  $conn->setLBInfo( $conn::LB_READ_ONLY_REASON, $readOnlyReason );
998  }
999 
1000  return $conn;
1001  }
1002 
1003  public function reuseConnection( IDatabase $conn ) {
1004  $serverIndex = $conn->getLBInfo( self::INFO_SERVER_INDEX );
1005  $refCount = $conn->getLBInfo( self::INFO_FOREIGN_REF_COUNT );
1006  if ( $serverIndex === null || $refCount === null ) {
1007  return; // non-foreign connection; no domain-use tracking to update
1008  } elseif ( $conn instanceof DBConnRef ) {
1009  // DBConnRef already handles calling reuseConnection() and only passes the live
1010  // Database instance to this method. Any caller passing in a DBConnRef is broken.
1011  $this->connLogger->error(
1012  __METHOD__ . ": got DBConnRef instance",
1013  [ 'db_domain' => $conn->getDomainID(), 'exception' => new RuntimeException() ]
1014  );
1015 
1016  return;
1017  }
1018 
1019  if ( $this->disabled ) {
1020  return; // DBConnRef handle probably survived longer than the LoadBalancer
1021  }
1022 
1023  if ( $conn->getLBInfo( self::INFO_AUTOCOMMIT_ONLY ) ) {
1024  $connFreeKey = self::KEY_FOREIGN_FREE_NOROUND;
1025  $connInUseKey = self::KEY_FOREIGN_INUSE_NOROUND;
1026  } else {
1027  $connFreeKey = self::KEY_FOREIGN_FREE;
1028  $connInUseKey = self::KEY_FOREIGN_INUSE;
1029  }
1030 
1031  $domain = $conn->getDomainID();
1032  $existingDomainConn = $this->conns[$connInUseKey][$serverIndex][$domain] ?? null;
1033  if ( !$existingDomainConn ) {
1034  throw new InvalidArgumentException(
1035  "Connection $serverIndex/$domain not found; it may have already been freed" );
1036  } elseif ( $existingDomainConn !== $conn ) {
1037  throw new InvalidArgumentException(
1038  "Connection $serverIndex/$domain mismatched; it may have already been freed" );
1039  }
1040 
1041  $existingDomainConn->setLBInfo( self::INFO_FOREIGN_REF_COUNT, --$refCount );
1042  if ( $refCount <= 0 ) {
1043  $this->conns[$connFreeKey][$serverIndex][$domain] = $existingDomainConn;
1044  unset( $this->conns[$connInUseKey][$serverIndex][$domain] );
1045  if ( !$this->conns[$connInUseKey][$serverIndex] ) {
1046  unset( $this->conns[$connInUseKey][$serverIndex] ); // clean up
1047  }
1048  $this->connLogger->debug( __METHOD__ . ": freed connection $serverIndex/$domain" );
1049  } else {
1050  $this->connLogger->debug( __METHOD__ .
1051  ": reference count for $serverIndex/$domain reduced to $refCount" );
1052  }
1053  }
1054 
1055  public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ): IDatabase {
1056  if ( self::fieldHasBit( $flags, self::CONN_SILENCE_ERRORS ) ) {
1057  throw new UnexpectedValueException(
1058  __METHOD__ . ' CONN_SILENCE_ERRORS is not supported'
1059  );
1060  }
1061 
1062  $domain = $this->resolveDomainID( $domain );
1063  $role = $this->getRoleFromIndex( $i );
1064  $conn = $this->getConnection( $i, $groups, $domain, $flags );
1065 
1066  return new DBConnRef( $this, $conn, $role );
1067  }
1068 
1069  public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ): DBConnRef {
1070  if ( self::fieldHasBit( $flags, self::CONN_SILENCE_ERRORS ) ) {
1071  throw new UnexpectedValueException(
1072  __METHOD__ . ' got CONN_SILENCE_ERRORS; connection is already deferred'
1073  );
1074  }
1075 
1076  $domain = $this->resolveDomainID( $domain );
1077  $role = $this->getRoleFromIndex( $i );
1078 
1079  return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role );
1080  }
1081 
1083  $i,
1084  $groups = [],
1085  $domain = false,
1086  $flags = 0
1088  if ( self::fieldHasBit( $flags, self::CONN_SILENCE_ERRORS ) ) {
1089  throw new UnexpectedValueException(
1090  __METHOD__ . ' CONN_SILENCE_ERRORS is not supported'
1091  );
1092  }
1093 
1094  $domain = $this->resolveDomainID( $domain );
1095  $role = $this->getRoleFromIndex( $i );
1096  $conn = $this->getConnection( $i, $groups, $domain, $flags );
1097 
1098  return new MaintainableDBConnRef( $this, $conn, $role );
1099  }
1100 
1105  private function getRoleFromIndex( $i ) {
1106  return ( $i === self::DB_PRIMARY || $i === $this->getWriterIndex() )
1108  : self::DB_REPLICA;
1109  }
1110 
1118  public function openConnection( $i, $domain = false, $flags = 0 ) {
1119  return $this->getConnection( $i, [], $domain, $flags | self::CONN_SILENCE_ERRORS );
1120  }
1121 
1136  private function getLocalConnection( $i, $flags = 0 ) {
1137  $autoCommit = self::fieldHasBit( $flags, self::CONN_TRX_AUTOCOMMIT );
1138  // Connection handles required to be in auto-commit mode use a separate connection
1139  // pool since the main pool is effected by implicit and explicit transaction rounds
1140  $connKey = $autoCommit ? self::KEY_LOCAL_NOROUND : self::KEY_LOCAL;
1141 
1142  if ( isset( $this->conns[$connKey][$i][self::KEY_LOCAL_DOMAIN] ) ) {
1143  $conn = $this->conns[$connKey][$i][self::KEY_LOCAL_DOMAIN];
1144  $this->connLogger->debug( __METHOD__ . ": reused a connection for $connKey/$i" );
1145  } else {
1146  $conn = $this->reallyOpenConnection(
1147  $i,
1148  $this->localDomain,
1149  [ self::INFO_AUTOCOMMIT_ONLY => $autoCommit ]
1150  );
1151  if ( $conn->isOpen() ) {
1152  $this->connLogger->debug( __METHOD__ . ": opened new connection for $connKey/$i" );
1153  $this->conns[$connKey][$i][self::KEY_LOCAL_DOMAIN] = $conn;
1154  } else {
1155  $this->connLogger->warning( __METHOD__ . ": connection error for $connKey/$i" );
1156  $this->errorConnection = $conn;
1157  $conn = false;
1158  }
1159  }
1160 
1161  // Check to make sure that the right domain is selected
1162  if (
1163  $conn instanceof IDatabase &&
1164  !$this->localDomain->isCompatible( $conn->getDomainID() )
1165  ) {
1166  throw new UnexpectedValueException(
1167  "Got connection to '{$conn->getDomainID()}', " .
1168  "but expected local domain ('{$this->localDomain}')"
1169  );
1170  }
1171 
1172  return $conn;
1173  }
1174 
1199  private function getForeignConnection( $i, $domain, $flags = 0 ) {
1200  $domainInstance = DatabaseDomain::newFromId( $domain );
1201  $autoCommit = self::fieldHasBit( $flags, self::CONN_TRX_AUTOCOMMIT );
1202  // Connection handles required to be in auto-commit mode use a separate connection
1203  // pool since the main pool is effected by implicit and explicit transaction rounds
1204  if ( $autoCommit ) {
1205  $connFreeKey = self::KEY_FOREIGN_FREE_NOROUND;
1206  $connInUseKey = self::KEY_FOREIGN_INUSE_NOROUND;
1207  } else {
1208  $connFreeKey = self::KEY_FOREIGN_FREE;
1209  $connInUseKey = self::KEY_FOREIGN_INUSE;
1210  }
1211 
1213  $conn = null;
1214 
1215  if ( isset( $this->conns[$connInUseKey][$i][$domain] ) ) {
1216  // Reuse an in-use connection for the same domain
1217  $conn = $this->conns[$connInUseKey][$i][$domain];
1218  $this->connLogger->debug( __METHOD__ . ": reusing connection $connInUseKey/$i/$domain" );
1219  } elseif ( isset( $this->conns[$connFreeKey][$i][$domain] ) ) {
1220  // Reuse a free connection for the same domain
1221  $conn = $this->conns[$connFreeKey][$i][$domain];
1222  unset( $this->conns[$connFreeKey][$i][$domain] );
1223  $this->conns[$connInUseKey][$i][$domain] = $conn;
1224  $this->connLogger->debug( __METHOD__ . ": reusing free connection $connInUseKey/$i/$domain" );
1225  } elseif ( !empty( $this->conns[$connFreeKey][$i] ) ) {
1226  // Reuse a free connection from another domain if possible
1227  foreach ( $this->conns[$connFreeKey][$i] as $oldDomain => $oldConn ) {
1228  if ( $domainInstance->getDatabase() !== null ) {
1229  // Check if changing the database will require a new connection.
1230  // In that case, leave the connection handle alone and keep looking.
1231  // This prevents connections from being closed mid-transaction and can
1232  // also avoid overhead if the same database will later be requested.
1233  if (
1234  $oldConn->databasesAreIndependent() &&
1235  $oldConn->getDBname() !== $domainInstance->getDatabase()
1236  ) {
1237  continue;
1238  }
1239  // Select the new database, schema, and prefix
1240  $conn = $oldConn;
1241  $conn->selectDomain( $domainInstance );
1242  } else {
1243  // Stay on the current database, but update the schema/prefix
1244  $conn = $oldConn;
1245  $conn->dbSchema( $domainInstance->getSchema() );
1246  $conn->tablePrefix( $domainInstance->getTablePrefix() );
1247  }
1248  unset( $this->conns[$connFreeKey][$i][$oldDomain] );
1249  // Note that if $domain is an empty string, getDomainID() might not match it
1250  $this->conns[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1251  $this->connLogger->debug( __METHOD__ .
1252  ": reusing free connection from $oldDomain for $domain" );
1253  break;
1254  }
1255  }
1256 
1257  if ( !$conn ) {
1258  $conn = $this->reallyOpenConnection(
1259  $i,
1260  $domainInstance,
1261  [
1262  self::INFO_AUTOCOMMIT_ONLY => $autoCommit,
1263  self::INFO_FORIEGN => true,
1264  self::INFO_FOREIGN_REF_COUNT => 0
1265  ]
1266  );
1267  if ( $conn->isOpen() ) {
1268  // Note that if $domain is an empty string, getDomainID() might not match it
1269  $this->conns[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1270  $this->connLogger->debug( __METHOD__ . ": opened new connection for $connInUseKey/$i/$domain" );
1271  } else {
1272  $this->connLogger->warning(
1273  __METHOD__ . ": connection error for $connInUseKey/$i/{db_domain}",
1274  [ 'db_domain' => $domain ]
1275  );
1276  $this->errorConnection = $conn;
1277  $conn = false;
1278  }
1279  }
1280 
1281  if ( $conn instanceof IDatabase ) {
1282  // Check to make sure that the right domain is selected
1283  if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1284  throw new UnexpectedValueException(
1285  "Got connection to '{$conn->getDomainID()}', but expected '$domain'" );
1286  }
1287  // Increment reference count
1288  $refCount = $conn->getLBInfo( self::INFO_FOREIGN_REF_COUNT );
1289  $conn->setLBInfo( self::INFO_FOREIGN_REF_COUNT, $refCount + 1 );
1290  }
1291 
1292  return $conn;
1293  }
1294 
1295  public function getServerAttributes( $i ) {
1297  $this->getServerType( $i ),
1298  $this->servers[$i]['driver'] ?? null
1299  );
1300  }
1301 
1308  private function isOpen( $index ) {
1309  return (bool)$this->getAnyOpenConnection( $index );
1310  }
1311 
1324  protected function reallyOpenConnection( $i, DatabaseDomain $domain, array $lbInfo ) {
1325  if ( $this->disabled ) {
1326  throw new DBAccessError();
1327  }
1328 
1329  $server = $this->getServerInfoStrict( $i );
1330 
1331  $conn = Database::factory(
1332  $server['type'],
1333  array_merge( $server, [
1334  // Basic replication role information
1335  'topologyRole' => $this->getTopologyRole( $i, $server ),
1336  'topologicalMaster' => $this->getPrimaryServerName(),
1337  // Use the database specified in $domain (null means "none or entrypoint DB");
1338  // fallback to the $server default if the RDBMs is an embedded library using a
1339  // file on disk since there would be nothing to access to without a DB/file name.
1340  'dbname' => $this->getServerAttributes( $i )[Database::ATTR_DB_IS_FILE]
1341  ? ( $domain->getDatabase() ?? $server['dbname'] ?? null )
1342  : $domain->getDatabase(),
1343  // Override the $server default schema with that of $domain if specified
1344  'schema' => $domain->getSchema() ?? $server['schema'] ?? null,
1345  // Use the table prefix specified in $domain
1346  'tablePrefix' => $domain->getTablePrefix(),
1347  // Participate in transaction rounds if $server does not specify otherwise
1348  'flags' => $this->initConnFlags( $server['flags'] ?? IDatabase::DBO_DEFAULT ),
1349  // Inject the PHP execution mode and the agent string
1350  'cliMode' => $this->cliMode,
1351  'agent' => $this->agent,
1352  'ownerId' => $this->id,
1353  // Inject object and callback dependencies
1354  'lazyMasterHandle' => $this->getLazyConnectionRef(
1356  [],
1357  $domain->getId()
1358  ),
1359  'srvCache' => $this->srvCache,
1360  'connLogger' => $this->connLogger,
1361  'queryLogger' => $this->queryLogger,
1362  'replLogger' => $this->replLogger,
1363  'errorLogger' => $this->errorLogger,
1364  'deprecationLogger' => $this->deprecationLogger,
1365  'profiler' => $this->profiler,
1366  'trxProfiler' => $this->trxProfiler,
1367  'criticalSectionProvider' => $this->csProvider
1368  ] ),
1369  Database::NEW_UNCONNECTED
1370  );
1371  // Attach load balancer information to the handle
1372  $conn->setLBInfo( [ self::INFO_SERVER_INDEX => $i ] + $lbInfo );
1373  // Set alternative table/index names before any queries can be issued
1374  $conn->setTableAliases( $this->tableAliases );
1375  $conn->setIndexAliases( $this->indexAliases );
1376  // Account for any active transaction round and listeners
1377  if ( $i === $this->getWriterIndex() ) {
1378  if ( $this->trxRoundId !== false ) {
1379  $this->applyTransactionRoundFlags( $conn );
1380  }
1381  foreach ( $this->trxRecurringCallbacks as $name => $callback ) {
1382  $conn->setTransactionListener( $name, $callback );
1383  }
1384  }
1385 
1386  // Make the connection handle live
1387  try {
1388  $conn->initConnection();
1390  } catch ( DBConnectionError $e ) {
1391  // ignore; let the DB handle the logging
1392  }
1393 
1394  // Try to maintain session consistency for clients that trigger write transactions
1395  // in a request or script and then return soon after in another request or script.
1396  // This requires cooperation with ChronologyProtector and the application wiring.
1397  if ( $conn->isOpen() ) {
1399  }
1400 
1401  // Log when many connection are made during a single request/script
1402  $count = $this->getCurrentConnectionCount();
1403  if ( $count >= self::CONN_HELD_WARN_THRESHOLD ) {
1404  $this->perfLogger->warning(
1405  __METHOD__ . ": {connections}+ connections made (primary={primarydb})",
1406  $this->getConnLogContext(
1407  $conn,
1408  [
1409  'connections' => $count,
1410  'primarydb' => $this->getPrimaryServerName(),
1411  'db_domain' => $domain->getId()
1412  ]
1413  )
1414  );
1415  }
1416 
1417  return $conn;
1418  }
1419 
1425  private function getTopologyRole( $i, array $server ) {
1426  if ( !empty( $server['is static'] ) ) {
1427  return IDatabase::ROLE_STATIC_CLONE;
1428  }
1429 
1430  return ( $i === $this->getWriterIndex() )
1431  ? IDatabase::ROLE_STREAMING_MASTER
1432  : IDatabase::ROLE_STREAMING_REPLICA;
1433  }
1434 
1440  private function initConnFlags( $flags ) {
1441  if ( self::fieldHasBit( $flags, IDatabase::DBO_DEFAULT ) ) {
1442  if ( $this->cliMode ) {
1443  $flags &= ~IDatabase::DBO_TRX;
1444  } else {
1445  $flags |= IDatabase::DBO_TRX;
1446  }
1447  }
1448 
1449  return $flags;
1450  }
1451 
1455  private function lazyLoadReplicationPositions() {
1456  if ( !$this->chronologyCallbackTriggered && $this->chronologyCallback ) {
1457  $this->chronologyCallbackTriggered = true;
1458  ( $this->chronologyCallback )( $this ); // generally calls waitFor()
1459  $this->connLogger->debug( __METHOD__ . ': executed chronology callback.' );
1460  }
1461  }
1462 
1467  private function reportConnectionError() {
1468  $conn = $this->errorConnection; // the connection which caused the error
1469  $context = [
1470  'method' => __METHOD__,
1471  'last_error' => $this->lastError,
1472  ];
1473 
1474  if ( $conn instanceof IDatabase ) {
1475  $srvName = $conn->getServerName();
1476  $this->connLogger->warning(
1477  __METHOD__ . ": connection error: {last_error} ({db_server})",
1478  $this->getConnLogContext( $conn, $context )
1479  );
1480  $error = $conn->lastError() ?: $this->lastError;
1481  throw new DBConnectionError( $conn, "{$error} ($srvName)" );
1482  } else {
1483  // No last connection, probably due to all servers being too busy
1484  $this->connLogger->error(
1485  __METHOD__ .
1486  ": LB failure with no last connection. Connection error: {last_error}",
1487  $context
1488  );
1489 
1490  // If all servers were busy, "lastError" will contain something sensible
1491  throw new DBConnectionError( null, $this->lastError );
1492  }
1493  }
1494 
1495  public function getWriterIndex() {
1496  return 0;
1497  }
1498 
1506  public function haveIndex( $i ) {
1507  return array_key_exists( $i, $this->servers );
1508  }
1509 
1517  public function isNonZeroLoad( $i ) {
1518  return ( isset( $this->servers[$i] ) && $this->groupLoads[self::GROUP_GENERIC][$i] > 0 );
1519  }
1520 
1521  public function getServerCount() {
1522  return count( $this->servers );
1523  }
1524 
1525  public function hasReplicaServers() {
1526  return ( $this->getServerCount() > 1 );
1527  }
1528 
1532  private function getStreamingReplicaIndexes() {
1533  $indexes = [];
1534  foreach ( $this->servers as $i => $server ) {
1535  if ( $i !== $this->getWriterIndex() && empty( $server['is static'] ) ) {
1536  $indexes[] = $i;
1537  }
1538  }
1539 
1540  return $indexes;
1541  }
1542 
1543  public function hasStreamingReplicaServers() {
1544  return (bool)$this->getStreamingReplicaIndexes();
1545  }
1546 
1547  public function getServerName( $i ): string {
1548  $name = $this->servers[$i]['serverName'] ?? ( $this->servers[$i]['host'] ?? '' );
1549 
1550  return ( $name !== '' ) ? $name : 'localhost';
1551  }
1552 
1553  public function getServerInfo( $i ) {
1554  return $this->servers[$i] ?? false;
1555  }
1556 
1557  public function getServerType( $i ) {
1558  return $this->servers[$i]['type'] ?? 'unknown';
1559  }
1560 
1561  public function getPrimaryPos() {
1562  $index = $this->getWriterIndex();
1563 
1564  $conn = $this->getAnyOpenConnection( $index );
1565  if ( $conn ) {
1566  return $conn->getPrimaryPos();
1567  }
1568 
1569  $conn = $this->getConnection( $index, self::CONN_SILENCE_ERRORS );
1570  if ( !$conn ) {
1571  $this->reportConnectionError();
1572  }
1573 
1574  try {
1575  return $conn->getPrimaryPos();
1576  } finally {
1577  $this->closeConnection( $conn );
1578  }
1579  }
1580 
1581  public function getMasterPos() {
1582  wfDeprecated( __METHOD__, '1.37' );
1583  return $this->getPrimaryPos();
1584  }
1585 
1586  public function getReplicaResumePos() {
1587  // Get the position of any existing primary DB server connection
1588  $primaryConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1589  if ( $primaryConn ) {
1590  return $primaryConn->getPrimaryPos();
1591  }
1592 
1593  // Get the highest position of any existing replica server connection
1594  $highestPos = false;
1595  foreach ( $this->getStreamingReplicaIndexes() as $i ) {
1596  $conn = $this->getAnyOpenConnection( $i );
1597  $pos = $conn ? $conn->getReplicaPos() : false;
1598  if ( !$pos ) {
1599  continue; // no open connection or could not get position
1600  }
1601 
1602  $highestPos = $highestPos ?: $pos;
1603  if ( $pos->hasReached( $highestPos ) ) {
1604  $highestPos = $pos;
1605  }
1606  }
1607 
1608  return $highestPos;
1609  }
1610 
1611  public function disable( $fname = __METHOD__, $owner = null ) {
1612  $this->assertOwnership( $fname, $owner );
1613  $this->closeAll( $fname, $owner );
1614  $this->disabled = true;
1615  }
1616 
1617  public function closeAll( $fname = __METHOD__, $owner = null ) {
1618  $this->assertOwnership( $fname, $owner );
1619  if ( $this->ownerId === null ) {
1621  $scope = ScopedCallback::newScopedIgnoreUserAbort();
1622  }
1623  $this->forEachOpenConnection( function ( IDatabase $conn ) use ( $fname ) {
1624  $srvName = $conn->getServerName();
1625  $this->connLogger->debug( "$fname: closing connection to database '$srvName'." );
1626  $conn->close( $fname, $this->id );
1627  } );
1628 
1629  $this->conns = self::newTrackedConnectionsArray();
1630  }
1631 
1632  public function closeConnection( IDatabase $conn ) {
1633  if ( $conn instanceof DBConnRef ) {
1634  // Avoid calling close() but still leaving the handle in the pool
1635  throw new RuntimeException( 'Cannot close DBConnRef instance; it must be shareable' );
1636  }
1637 
1638  $serverIndex = $conn->getLBInfo( self::INFO_SERVER_INDEX );
1639  if ( $serverIndex === null ) {
1640  throw new RuntimeException( 'Database handle is missing server index' );
1641  }
1642 
1643  $srvName = $this->getServerName( $serverIndex );
1644  $domain = $conn->getDomainID();
1645 
1646  $found = false;
1647  foreach ( $this->conns as $type => $connsByServer ) {
1648  $key = array_search( $conn, $connsByServer[$serverIndex] ?? [], true );
1649  if ( $key !== false ) {
1650  $found = true;
1651  unset( $this->conns[$type][$serverIndex][$key] );
1652  }
1653  }
1654 
1655  if ( !$found ) {
1656  $this->connLogger->warning(
1657  __METHOD__ .
1658  ": got orphaned connection to database $serverIndex/$domain at '$srvName'."
1659  );
1660  }
1661 
1662  $this->connLogger->debug(
1663  __METHOD__ .
1664  ": closing connection to database $serverIndex/$domain at '$srvName'."
1665  );
1666 
1667  $conn->close( __METHOD__ );
1668  }
1669 
1670  public function commitAll( $fname = __METHOD__, $owner = null ) {
1671  $this->commitPrimaryChanges( $fname, $owner );
1672  $this->flushPrimarySnapshots( $fname, $owner );
1673  $this->flushReplicaSnapshots( $fname, $owner );
1674  }
1675 
1676  public function finalizePrimaryChanges( $fname = __METHOD__, $owner = null ) {
1677  $this->assertOwnership( $fname, $owner );
1678  $this->assertTransactionRoundStage( [ self::ROUND_CURSORY, self::ROUND_FINALIZED ] );
1679  if ( $this->ownerId === null ) {
1681  $scope = ScopedCallback::newScopedIgnoreUserAbort();
1682  }
1683 
1684  $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1685  // Loop until callbacks stop adding callbacks on other connections
1686  $total = 0;
1687  do {
1688  $count = 0; // callbacks execution attempts
1689  $this->forEachOpenPrimaryConnection( static function ( Database $conn ) use ( &$count ) {
1690  // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1691  // Any error should cause all (peer) transactions to be rolled back together.
1692  $count += $conn->runOnTransactionPreCommitCallbacks();
1693  } );
1694  $total += $count;
1695  } while ( $count > 0 );
1696  // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1697  $this->forEachOpenPrimaryConnection( static function ( Database $conn ) {
1698  $conn->setTrxEndCallbackSuppression( true );
1699  } );
1700  $this->trxRoundStage = self::ROUND_FINALIZED;
1701 
1702  return $total;
1703  }
1704 
1705  public function finalizeMasterChanges( $fname = __METHOD__, $owner = null ) {
1706  wfDeprecated( __METHOD__, '1.37' );
1707  return $this->finalizePrimaryChanges( $fname, $owner );
1708  }
1709 
1710  public function approvePrimaryChanges( array $options, $fname = __METHOD__, $owner = null ) {
1711  $this->assertOwnership( $fname, $owner );
1712  $this->assertTransactionRoundStage( self::ROUND_FINALIZED );
1713  if ( $this->ownerId === null ) {
1715  $scope = ScopedCallback::newScopedIgnoreUserAbort();
1716  }
1717 
1718  $limit = $options['maxWriteDuration'] ?? 0;
1719 
1720  $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1721  $this->forEachOpenPrimaryConnection( function ( IDatabase $conn ) use ( $limit ) {
1722  // Any atomic sections should have been closed by now and there definitely should
1723  // not be any open transactions started by begin() from callers outside Database.
1724  if ( $conn->explicitTrxActive() ) {
1725  throw new DBTransactionError(
1726  $conn,
1727  "Explicit transaction still active; a caller might have failed to call " .
1728  "endAtomic() or cancelAtomic()."
1729  );
1730  }
1731  // Assert that the time to replicate the transaction will be reasonable.
1732  // If this fails, then all DB transactions will be rollback back together.
1733  $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY );
1734  if ( $limit > 0 ) {
1735  if ( $time > $limit ) {
1736  $humanTimeSec = round( $time, 3 );
1737  throw new DBTransactionSizeError(
1738  $conn,
1739  "Transaction spent {$humanTimeSec}s in writes, exceeding the {$limit}s limit",
1740  // Message parameters for: transaction-duration-limit-exceeded
1741  [ $time, $limit ]
1742  );
1743  } elseif ( $time > 0 ) {
1744  $timeMs = $time * 1000;
1745  $humanTimeMs = $timeMs > 1 ? round( $timeMs ) : round( $timeMs, 3 );
1746  $this->perfLogger->debug(
1747  "Transaction spent {time_ms}ms in writes, under the {$limit}s limit",
1748  [ 'time_ms' => $humanTimeMs ]
1749  );
1750  }
1751  }
1752  // If a connection sits idle while slow queries execute on another, that connection
1753  // may end up dropped before the commit round is reached. Ping servers to detect this.
1754  if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1755  throw new DBTransactionError(
1756  $conn,
1757  "A connection to the {$conn->getDBname()} database was lost before commit"
1758  );
1759  }
1760  } );
1761  $this->trxRoundStage = self::ROUND_APPROVED;
1762  }
1763 
1764  public function approveMasterChanges( array $options, $fname = __METHOD__, $owner = null ) {
1765  wfDeprecated( __METHOD__, '1.37' );
1766  $this->approvePrimaryChanges( $options, $fname, $owner );
1767  }
1768 
1769  public function beginPrimaryChanges( $fname = __METHOD__, $owner = null ) {
1770  $this->assertOwnership( $fname, $owner );
1771  if ( $this->trxRoundId !== false ) {
1772  throw new DBTransactionError(
1773  null,
1774  "$fname: Transaction round '{$this->trxRoundId}' already started"
1775  );
1776  }
1777  $this->assertTransactionRoundStage( self::ROUND_CURSORY );
1778  if ( $this->ownerId === null ) {
1780  $scope = ScopedCallback::newScopedIgnoreUserAbort();
1781  }
1782 
1783  // Clear any empty transactions (no writes/callbacks) from the implicit round
1784  $this->flushPrimarySnapshots( $fname, $owner );
1785 
1786  $this->trxRoundId = $fname;
1787  $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1788  // Mark applicable handles as participating in this explicit transaction round.
1789  // For each of these handles, any writes and callbacks will be tied to a single
1790  // transaction. The (peer) handles will reject begin()/commit() calls unless they
1791  // are part of an en masse commit or an en masse rollback.
1792  $this->forEachOpenPrimaryConnection( function ( Database $conn ) {
1793  $this->applyTransactionRoundFlags( $conn );
1794  } );
1795  $this->trxRoundStage = self::ROUND_CURSORY;
1796  }
1797 
1798  public function beginMasterChanges( $fname = __METHOD__, $owner = null ) {
1799  wfDeprecated( __METHOD__, '1.37' );
1800  $this->beginPrimaryChanges( $fname, $owner );
1801  }
1802 
1803  public function commitPrimaryChanges( $fname = __METHOD__, $owner = null ) {
1804  $this->assertOwnership( $fname, $owner );
1805  $this->assertTransactionRoundStage( self::ROUND_APPROVED );
1806  if ( $this->ownerId === null ) {
1808  $scope = ScopedCallback::newScopedIgnoreUserAbort();
1809  }
1810 
1811  $failures = [];
1812 
1813  $restore = ( $this->trxRoundId !== false );
1814  $this->trxRoundId = false;
1815  $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1816  // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1817  // Note that callbacks should already be suppressed due to finalizePrimaryChanges().
1819  function ( IDatabase $conn ) use ( $fname, &$failures ) {
1820  try {
1821  $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1822  } catch ( DBError $e ) {
1823  ( $this->errorLogger )( $e );
1824  $failures[] = "{$conn->getServerName()}: {$e->getMessage()}";
1825  }
1826  }
1827  );
1828  if ( $failures ) {
1829  throw new DBTransactionError(
1830  null,
1831  "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1832  );
1833  }
1834  if ( $restore ) {
1835  // Unmark handles as participating in this explicit transaction round
1836  $this->forEachOpenPrimaryConnection( function ( Database $conn ) {
1837  $this->undoTransactionRoundFlags( $conn );
1838  } );
1839  }
1840  $this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS;
1841  }
1842 
1843  public function commitMasterChanges( $fname = __METHOD__, $owner = null ) {
1844  wfDeprecated( __METHOD__, '1.37' );
1845  $this->commitPrimaryChanges( $fname, $owner );
1846  }
1847 
1848  public function runPrimaryTransactionIdleCallbacks( $fname = __METHOD__, $owner = null ) {
1849  $this->assertOwnership( $fname, $owner );
1850  if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
1851  $type = IDatabase::TRIGGER_COMMIT;
1852  } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
1853  $type = IDatabase::TRIGGER_ROLLBACK;
1854  } else {
1855  throw new DBTransactionError(
1856  null,
1857  "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1858  );
1859  }
1860  if ( $this->ownerId === null ) {
1862  $scope = ScopedCallback::newScopedIgnoreUserAbort();
1863  }
1864 
1865  $oldStage = $this->trxRoundStage;
1866  $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1867 
1868  // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1869  $this->forEachOpenPrimaryConnection( static function ( Database $conn ) {
1870  $conn->setTrxEndCallbackSuppression( false );
1871  } );
1872 
1873  $errors = [];
1874  $fname = __METHOD__;
1875  // Loop until callbacks stop adding callbacks on other connections
1876  do {
1877  // Run any pending callbacks for each connection...
1878  $count = 0; // callback execution attempts
1880  static function ( Database $conn ) use ( $type, &$errors, &$count ) {
1881  if ( $conn->trxLevel() ) {
1882  return; // retry in the next iteration, after commit() is called
1883  }
1884  $count += $conn->runOnTransactionIdleCallbacks( $type, $errors );
1885  }
1886  );
1887  // Clear out any active transactions left over from callbacks...
1889  function ( Database $conn ) use ( &$errors, $fname ) {
1890  if ( $conn->writesPending() ) {
1891  // A callback from another handle wrote to this one and DBO_TRX is set
1892  $this->queryLogger->warning( $fname . ": found writes pending." );
1893  $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1894  $this->queryLogger->warning(
1895  "$fname: found writes pending ($fnames).",
1896  $this->getConnLogContext(
1897  $conn,
1898  [ 'exception' => new RuntimeException() ]
1899  )
1900  );
1901  } elseif ( $conn->trxLevel() ) {
1902  // A callback from another handle read from this one and DBO_TRX is set,
1903  // which can easily happen if there is only one DB (no replicas)
1904  $this->queryLogger->debug( "$fname: found empty transaction." );
1905  }
1906  try {
1907  $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1908  } catch ( DBError $ex ) {
1909  $errors[] = $ex;
1910  }
1911  }
1912  );
1913  } while ( $count > 0 );
1914 
1915  $this->trxRoundStage = $oldStage;
1916 
1917  return $errors ? $errors[0] : null;
1918  }
1919 
1920  public function runMasterTransactionIdleCallbacks( $fname = __METHOD__, $owner = null ) {
1921  wfDeprecated( __METHOD__, '1.37' );
1922  $this->runPrimaryTransactionIdleCallbacks( $fname, $owner );
1923  }
1924 
1925  public function runPrimaryTransactionListenerCallbacks( $fname = __METHOD__, $owner = null ) {
1926  $this->assertOwnership( $fname, $owner );
1927  if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
1928  $type = IDatabase::TRIGGER_COMMIT;
1929  } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
1930  $type = IDatabase::TRIGGER_ROLLBACK;
1931  } else {
1932  throw new DBTransactionError(
1933  null,
1934  "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1935  );
1936  }
1937  if ( $this->ownerId === null ) {
1939  $scope = ScopedCallback::newScopedIgnoreUserAbort();
1940  }
1941 
1942  $errors = [];
1943  $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1945  static function ( Database $conn ) use ( $type, &$errors ) {
1946  $conn->runTransactionListenerCallbacks( $type, $errors );
1947  }
1948  );
1949  $this->trxRoundStage = self::ROUND_CURSORY;
1950 
1951  return $errors ? $errors[0] : null;
1952  }
1953 
1954  public function runMasterTransactionListenerCallbacks( $fname = __METHOD__, $owner = null ) {
1955  wfDeprecated( __METHOD__, '1.37' );
1956  $this->runPrimaryTransactionListenerCallbacks( $fname, $owner );
1957  }
1958 
1959  public function rollbackPrimaryChanges( $fname = __METHOD__, $owner = null ) {
1960  $this->assertOwnership( $fname, $owner );
1961  if ( $this->ownerId === null ) {
1963  $scope = ScopedCallback::newScopedIgnoreUserAbort();
1964  }
1965 
1966  $restore = ( $this->trxRoundId !== false );
1967  $this->trxRoundId = false;
1968  $this->trxRoundStage = self::ROUND_ERROR; // "failed" until proven otherwise
1969  $this->forEachOpenPrimaryConnection( static function ( IDatabase $conn ) use ( $fname ) {
1970  $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS );
1971  } );
1972  if ( $restore ) {
1973  // Unmark handles as participating in this explicit transaction round
1974  $this->forEachOpenPrimaryConnection( function ( Database $conn ) {
1975  $this->undoTransactionRoundFlags( $conn );
1976  } );
1977  }
1978  $this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS;
1979  }
1980 
1981  public function rollbackMasterChanges( $fname = __METHOD__, $owner = null ) {
1982  wfDeprecated( __METHOD__, '1.37' );
1983  $this->rollbackPrimaryChanges( $fname, $owner );
1984  }
1985 
1990  private function assertTransactionRoundStage( $stage ) {
1991  $stages = (array)$stage;
1992 
1993  if ( !in_array( $this->trxRoundStage, $stages, true ) ) {
1994  $stageList = implode(
1995  '/',
1996  array_map( static function ( $v ) {
1997  return "'$v'";
1998  }, $stages )
1999  );
2000  throw new DBTransactionError(
2001  null,
2002  "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
2003  );
2004  }
2005  }
2006 
2019  private function assertOwnership( $fname, $owner ) {
2020  if ( $this->ownerId !== null && $owner !== $this->ownerId && $owner !== $this->id ) {
2021  throw new DBTransactionError(
2022  null,
2023  "$fname: LoadBalancer is owned by ID '{$this->ownerId}' (got '$owner')."
2024  );
2025  }
2026  }
2027 
2037  private function applyTransactionRoundFlags( Database $conn ) {
2038  if ( $conn->getLBInfo( self::INFO_AUTOCOMMIT_ONLY ) ) {
2039  return; // transaction rounds do not apply to these connections
2040  }
2041 
2042  if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
2043  // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
2044  // Force DBO_TRX even in CLI mode since a commit round is expected soon.
2045  $conn->setFlag( $conn::DBO_TRX, $conn::REMEMBER_PRIOR );
2046  }
2047 
2048  if ( $conn->getFlag( $conn::DBO_TRX ) ) {
2049  $conn->setLBInfo( $conn::LB_TRX_ROUND_ID, $this->trxRoundId );
2050  }
2051  }
2052 
2056  private function undoTransactionRoundFlags( Database $conn ) {
2057  if ( $conn->getLBInfo( self::INFO_AUTOCOMMIT_ONLY ) ) {
2058  return; // transaction rounds do not apply to these connections
2059  }
2060 
2061  if ( $conn->getFlag( $conn::DBO_TRX ) ) {
2062  $conn->setLBInfo( $conn::LB_TRX_ROUND_ID, null ); // remove the round ID
2063  }
2064 
2065  if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
2066  $conn->restoreFlags( $conn::RESTORE_PRIOR );
2067  }
2068  }
2069 
2070  public function flushReplicaSnapshots( $fname = __METHOD__, $owner = null ) {
2071  $this->assertOwnership( $fname, $owner );
2072  $this->forEachOpenReplicaConnection( static function ( IDatabase $conn ) use ( $fname ) {
2073  $conn->flushSnapshot( $fname );
2074  } );
2075  }
2076 
2077  public function flushPrimarySnapshots( $fname = __METHOD__, $owner = null ) {
2078  $this->assertOwnership( $fname, $owner );
2079  $this->forEachOpenPrimaryConnection( static function ( IDatabase $conn ) use ( $fname ) {
2080  $conn->flushSnapshot( $fname );
2081  } );
2082  }
2083 
2084  public function flushMasterSnapshots( $fname = __METHOD__, $owner = null ) {
2085  wfDeprecated( __METHOD__, '1.37' );
2086  $this->flushPrimarySnapshots( $fname, $owner );
2087  }
2088 
2093  public function getTransactionRoundStage() {
2094  return $this->trxRoundStage;
2095  }
2096 
2097  public function hasPrimaryConnection() {
2098  return $this->isOpen( $this->getWriterIndex() );
2099  }
2100 
2101  public function hasMasterConnection() {
2102  wfDeprecated( __METHOD__, '1.37' );
2103  return $this->hasPrimaryConnection();
2104  }
2105 
2106  public function hasPrimaryChanges() {
2107  $pending = false;
2108  $this->forEachOpenPrimaryConnection( static function ( IDatabase $conn ) use ( &$pending ) {
2109  $pending = $pending || $conn->writesOrCallbacksPending();
2110  } );
2111 
2112  return $pending;
2113  }
2114 
2115  public function hasMasterChanges() {
2116  wfDeprecated( __METHOD__, '1.37' );
2117  return $this->hasPrimaryChanges();
2118  }
2119 
2120  public function lastPrimaryChangeTimestamp() {
2121  $lastTime = false;
2122  $this->forEachOpenPrimaryConnection( static function ( IDatabase $conn ) use ( &$lastTime ) {
2123  $lastTime = max( $lastTime, $conn->lastDoneWrites() );
2124  } );
2125 
2126  return $lastTime;
2127  }
2128 
2129  public function lastMasterChangeTimestamp() {
2130  wfDeprecated( __METHOD__, '1.37' );
2131  return $this->lastPrimaryChangeTimestamp();
2132  }
2133 
2134  public function hasOrMadeRecentPrimaryChanges( $age = null ) {
2135  $age = $age ?? $this->waitTimeout;
2136 
2137  return ( $this->hasPrimaryChanges()
2138  || $this->lastPrimaryChangeTimestamp() > microtime( true ) - $age );
2139  }
2140 
2141  public function hasOrMadeRecentMasterChanges( $age = null ) {
2142  wfDeprecated( __METHOD__, '1.37' );
2143  return $this->hasOrMadeRecentPrimaryChanges( $age );
2144  }
2145 
2146  public function pendingPrimaryChangeCallers() {
2147  $fnames = [];
2148  $this->forEachOpenPrimaryConnection( static function ( IDatabase $conn ) use ( &$fnames ) {
2149  $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
2150  } );
2151 
2152  return $fnames;
2153  }
2154 
2155  public function pendingMasterChangeCallers() {
2156  wfDeprecated( __METHOD__, '1.37' );
2157  return $this->pendingPrimaryChangeCallers();
2158  }
2159 
2160  public function getLaggedReplicaMode( $domain = false ) {
2161  $domain = $this->resolveDomainID( $domain );
2162 
2163  if ( $this->laggedReplicaMode ) {
2164  // Stay in lagged replica mode once it is observed on any domain
2165  return true;
2166  }
2167 
2168  if ( $this->hasStreamingReplicaServers() ) {
2169  // This will set "laggedReplicaMode" as needed
2170  $this->getReaderIndex( self::GROUP_GENERIC, $domain );
2171  }
2172 
2173  return $this->laggedReplicaMode;
2174  }
2175 
2176  public function laggedReplicaUsed() {
2177  return $this->laggedReplicaMode;
2178  }
2179 
2180  public function getReadOnlyReason( $domain = false ) {
2181  $domainInstance = DatabaseDomain::newFromId( $this->resolveDomainID( $domain ) );
2182 
2183  if ( $this->readOnlyReason !== false ) {
2184  return $this->readOnlyReason;
2185  } elseif ( $this->isPrimaryRunningReadOnly( $domainInstance ) ) {
2186  return 'The primary database server is running in read-only mode.';
2187  } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
2188  $genericIndex = $this->getExistingReaderIndex( self::GROUP_GENERIC );
2189 
2190  return ( $genericIndex !== self::READER_INDEX_NONE )
2191  ? 'The database is read-only until replication lag decreases.'
2192  : 'The database is read-only until a replica database server becomes reachable.';
2193  }
2194 
2195  return false;
2196  }
2197 
2204  private function isPrimaryConnectionReadOnly( IDatabase $conn, $flags = 0 ) {
2205  // Note that table prefixes are not related to server-side read-only mode
2206  $key = $this->srvCache->makeGlobalKey(
2207  'rdbms-server-readonly',
2208  $conn->getServerName(),
2209  $conn->getDBname(),
2210  (string)$conn->dbSchema()
2211  );
2212 
2213  if ( self::fieldHasBit( $flags, self::CONN_REFRESH_READ_ONLY ) ) {
2214  // Refresh the local server cache. This is useful when the caller is
2215  // currently in the process of updating a corresponding WANCache key.
2216  try {
2217  $readOnly = (int)$conn->serverIsReadOnly();
2218  } catch ( DBError $e ) {
2219  $readOnly = 0;
2220  }
2221  $this->srvCache->set( $key, $readOnly, BagOStuff::TTL_PROC_SHORT );
2222  } else {
2223  $readOnly = $this->srvCache->getWithSetCallback(
2224  $key,
2225  BagOStuff::TTL_PROC_SHORT,
2226  static function () use ( $conn ) {
2227  try {
2228  $readOnly = (int)$conn->serverIsReadOnly();
2229  } catch ( DBError $e ) {
2230  $readOnly = 0;
2231  }
2232 
2233  return $readOnly;
2234  }
2235  );
2236  }
2237 
2238  return (bool)$readOnly;
2239  }
2240 
2246  private function isPrimaryRunningReadOnly( DatabaseDomain $domain ) {
2247  // Context will often be HTTP GET/HEAD; heavily cache the results
2248  return (bool)$this->wanCache->getWithSetCallback(
2249  // Note that table prefixes are not related to server-side read-only mode
2250  $this->wanCache->makeGlobalKey(
2251  'rdbms-server-readonly',
2252  $this->getPrimaryServerName(),
2253  $domain->getDatabase(),
2254  (string)$domain->getSchema()
2255  ),
2256  self::TTL_CACHE_READONLY,
2257  function () use ( $domain ) {
2258  $scope = $this->trxProfiler->silenceForScope();
2259 
2260  $index = $this->getWriterIndex();
2261  // Refresh the local server cache as well. This is done in order to avoid
2262  // backfilling the WANCache with data that is already significantly stale
2263  $flags = self::CONN_SILENCE_ERRORS | self::CONN_REFRESH_READ_ONLY;
2264  $conn = $this->getServerConnection( $index, $domain->getId(), $flags );
2265  if ( $conn ) {
2266  try {
2267  $readOnly = (int)$this->isPrimaryConnectionReadOnly( $conn );
2268  } catch ( DBError $e ) {
2269  $readOnly = 0;
2270  }
2271  $this->reuseConnection( $conn );
2272  } else {
2273  $readOnly = 0;
2274  }
2275 
2276  ScopedCallback::consume( $scope );
2277 
2278  return $readOnly;
2279  },
2280  [
2281  'busyValue' => 0,
2282  'pcTTL' => WANObjectCache::TTL_PROC_LONG
2283  ]
2284  );
2285  }
2286 
2287  public function pingAll() {
2288  $success = true;
2289  $this->forEachOpenConnection( static function ( IDatabase $conn ) use ( &$success ) {
2290  if ( !$conn->ping() ) {
2291  $success = false;
2292  }
2293  } );
2294 
2295  return $success;
2296  }
2297 
2298  public function forEachOpenConnection( $callback, array $params = [] ) {
2299  foreach ( $this->conns as $connsByServer ) {
2300  foreach ( $connsByServer as $serverConns ) {
2301  foreach ( $serverConns as $conn ) {
2302  $callback( $conn, ...$params );
2303  }
2304  }
2305  }
2306  }
2307 
2308  public function forEachOpenPrimaryConnection( $callback, array $params = [] ) {
2309  $primaryIndex = $this->getWriterIndex();
2310  foreach ( $this->conns as $connsByServer ) {
2311  if ( isset( $connsByServer[$primaryIndex] ) ) {
2313  foreach ( $connsByServer[$primaryIndex] as $conn ) {
2314  $callback( $conn, ...$params );
2315  }
2316  }
2317  }
2318  }
2319 
2320  public function forEachOpenMasterConnection( $callback, array $params = [] ) {
2321  wfDeprecated( __METHOD__, '1.37' );
2322  $this->forEachOpenPrimaryConnection( $callback, $params );
2323  }
2324 
2325  private function forEachOpenReplicaConnection( $callback ) {
2326  foreach ( $this->conns as $connsByServer ) {
2327  foreach ( $connsByServer as $i => $serverConns ) {
2328  if ( $i === $this->getWriterIndex() ) {
2329  continue; // skip primary DB
2330  }
2331  foreach ( $serverConns as $conn ) {
2332  $callback( $conn );
2333  }
2334  }
2335  }
2336  }
2337 
2341  private function getCurrentConnectionCount() {
2342  $count = 0;
2343  foreach ( $this->conns as $connsByServer ) {
2344  foreach ( $connsByServer as $serverConns ) {
2345  $count += count( $serverConns );
2346  }
2347  }
2348 
2349  return $count;
2350  }
2351 
2352  public function getMaxLag( $domain = false ) {
2353  $domain = $this->resolveDomainID( $domain );
2354 
2355  $host = '';
2356  $maxLag = -1;
2357  $maxIndex = 0;
2358 
2359  if ( $this->hasReplicaServers() ) {
2360  $lagTimes = $this->getLagTimes( $domain );
2361  foreach ( $lagTimes as $i => $lag ) {
2362  if ( $this->groupLoads[self::GROUP_GENERIC][$i] > 0 && $lag > $maxLag ) {
2363  $maxLag = $lag;
2364  $host = $this->getServerInfoStrict( $i, 'host' );
2365  $maxIndex = $i;
2366  }
2367  }
2368  }
2369 
2370  return [ $host, $maxLag, $maxIndex ];
2371  }
2372 
2373  public function getLagTimes( $domain = false ) {
2374  $domain = $this->resolveDomainID( $domain );
2375 
2376  if ( !$this->hasReplicaServers() ) {
2377  return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
2378  }
2379 
2380  $knownLagTimes = []; // map of (server index => 0 seconds)
2381  $indexesWithLag = [];
2382  foreach ( $this->servers as $i => $server ) {
2383  if ( empty( $server['is static'] ) ) {
2384  $indexesWithLag[] = $i; // DB server might have replication lag
2385  } else {
2386  $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
2387  }
2388  }
2389 
2390  return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) + $knownLagTimes;
2391  }
2392 
2408  public function safeGetLag( IDatabase $conn ) {
2409  return $conn->getLag();
2410  }
2411 
2412  public function waitForPrimaryPos( IDatabase $conn, $pos = false, $timeout = null ) {
2413  $timeout = max( 1, $timeout ?: $this->waitTimeout );
2414 
2415  if ( $conn->getLBInfo( self::INFO_SERVER_INDEX ) === $this->getWriterIndex() ) {
2416  return true; // not a replica DB server
2417  }
2418 
2419  if ( !$pos ) {
2420  // Get the current primary DB position, opening a connection only if needed
2421  $this->replLogger->debug( __METHOD__ . ': no position passed; using current' );
2422  $index = $this->getWriterIndex();
2423  $flags = self::CONN_SILENCE_ERRORS;
2424  $primaryConn = $this->getAnyOpenConnection( $index, $flags );
2425  if ( $primaryConn ) {
2426  $pos = $primaryConn->getPrimaryPos();
2427  } else {
2428  $primaryConn = $this->getServerConnection( $index, self::DOMAIN_ANY, $flags );
2429  if ( !$primaryConn ) {
2430  throw new DBReplicationWaitError(
2431  null,
2432  "Could not obtain a primary database connection to get the position"
2433  );
2434  }
2435  $pos = $primaryConn->getPrimaryPos();
2436  $this->closeConnection( $primaryConn );
2437  }
2438  }
2439 
2440  if ( $pos instanceof DBPrimaryPos ) {
2441  $this->replLogger->debug( __METHOD__ . ': waiting' );
2442  $result = $conn->primaryPosWait( $pos, $timeout );
2443  $ok = ( $result !== null && $result != -1 );
2444  if ( $ok ) {
2445  $this->replLogger->debug( __METHOD__ . ': done waiting (success)' );
2446  } else {
2447  $this->replLogger->debug( __METHOD__ . ': done waiting (failure)' );
2448  }
2449  } else {
2450  $ok = false; // something is misconfigured
2451  $this->replLogger->error(
2452  __METHOD__ . ': could not get primary pos for {db_server}',
2453  $this->getConnLogContext( $conn, [ 'exception' => new RuntimeException() ] )
2454  );
2455  }
2456 
2457  return $ok;
2458  }
2459 
2460  public function waitForMasterPos( IDatabase $conn, $pos = false, $timeout = null ) {
2461  wfDeprecated( __METHOD__, '1.37' );
2462  return $this->waitForPrimaryPos( $conn, $pos, $timeout );
2463  }
2464 
2465  public function setTransactionListener( $name, callable $callback = null ) {
2466  if ( $callback ) {
2467  $this->trxRecurringCallbacks[$name] = $callback;
2468  } else {
2469  unset( $this->trxRecurringCallbacks[$name] );
2470  }
2472  static function ( IDatabase $conn ) use ( $name, $callback ) {
2473  $conn->setTransactionListener( $name, $callback );
2474  }
2475  );
2476  }
2477 
2478  public function setTableAliases( array $aliases ) {
2479  $this->tableAliases = $aliases;
2480  }
2481 
2482  public function setIndexAliases( array $aliases ) {
2483  $this->indexAliases = $aliases;
2484  }
2485 
2486  public function setDomainAliases( array $aliases ) {
2487  $this->domainAliases = $aliases;
2488  }
2489 
2490  public function setLocalDomainPrefix( $prefix ) {
2491  // Find connections to explicit foreign domains still marked as in-use...
2492  $domainsInUse = [];
2493  $this->forEachOpenConnection( static function ( IDatabase $conn ) use ( &$domainsInUse ) {
2494  // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
2495  // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
2496  if ( $conn->getLBInfo( self::INFO_FOREIGN_REF_COUNT ) > 0 ) {
2497  $domainsInUse[] = $conn->getDomainID();
2498  }
2499  } );
2500 
2501  // Do not switch connections to explicit foreign domains unless marked as safe
2502  if ( $domainsInUse ) {
2503  $domains = implode( ', ', $domainsInUse );
2504  throw new DBUnexpectedError( null,
2505  "Foreign domain connections are still in use ($domains)" );
2506  }
2507 
2508  $this->setLocalDomain( new DatabaseDomain(
2509  $this->localDomain->getDatabase(),
2510  $this->localDomain->getSchema(),
2511  $prefix
2512  ) );
2513 
2514  // Update the prefix for all local connections...
2515  $this->forEachOpenConnection( static function ( IDatabase $conn ) use ( $prefix ) {
2516  if ( !$conn->getLBInfo( self::INFO_FORIEGN ) ) {
2517  $conn->tablePrefix( $prefix );
2518  }
2519  } );
2520  }
2521 
2522  public function redefineLocalDomain( $domain ) {
2523  $this->closeAll( __METHOD__, $this->id );
2524 
2525  $this->setLocalDomain( DatabaseDomain::newFromId( $domain ) );
2526  }
2527 
2528  public function setTempTablesOnlyMode( $value, $domain ) {
2529  $old = $this->tempTablesOnlyMode[$domain] ?? false;
2530  if ( $value ) {
2531  $this->tempTablesOnlyMode[$domain] = true;
2532  } else {
2533  unset( $this->tempTablesOnlyMode[$domain] );
2534  }
2535 
2536  return $old;
2537  }
2538 
2542  private function setLocalDomain( DatabaseDomain $domain ) {
2543  $this->localDomain = $domain;
2544  }
2545 
2552  private function getServerInfoStrict( $i, $field = null ) {
2553  if ( !isset( $this->servers[$i] ) || !is_array( $this->servers[$i] ) ) {
2554  throw new InvalidArgumentException( "No server with index '$i'" );
2555  }
2556 
2557  if ( $field !== null ) {
2558  if ( !array_key_exists( $field, $this->servers[$i] ) ) {
2559  throw new InvalidArgumentException( "No field '$field' in server index '$i'" );
2560  }
2561 
2562  return $this->servers[$i][$field];
2563  }
2564 
2565  return $this->servers[$i];
2566  }
2567 
2571  private function getPrimaryServerName() {
2572  return $this->getServerName( $this->getWriterIndex() );
2573  }
2574 
2580  private function fieldHasBit( int $flags, int $bit ) {
2581  return ( ( $flags & $bit ) === $bit );
2582  }
2583 
2591  protected function getConnLogContext( IDatabase $conn, array $extras = [] ) {
2592  return array_merge(
2593  [
2594  'db_server' => $conn->getServerName(),
2595  'db_domain' => $conn->getDomainID()
2596  ],
2597  $extras
2598  );
2599  }
2600 
2601  public function __destruct() {
2602  // Avoid connection leaks
2603  $this->disable( __METHOD__, $this->ownerId );
2604  }
2605 }
2606 
2610 class_alias( LoadBalancer::class, 'LoadBalancer' );
Wikimedia\Rdbms\LoadBalancer\getServerType
getServerType( $i)
Get the RDBMS type of the server with the specified index (e.g.
Definition: LoadBalancer.php:1557
Wikimedia\Rdbms\LoadBalancer\getExistingReaderIndex
getExistingReaderIndex( $group)
Get the server index chosen by the load balancer for use with the given query group.
Definition: LoadBalancer.php:589
Wikimedia\Rdbms\LoadBalancer\setWaitForPositionIfHigher
setWaitForPositionIfHigher( $pos)
Definition: LoadBalancer.php:764
Wikimedia\Rdbms\LoadBalancer\$profiler
callable null $profiler
An optional callback that returns a ScopedCallback instance, meant to profile the actual query execut...
Definition: LoadBalancer.php:58
Wikimedia\Rdbms\LoadBalancer\waitForMasterPos
waitForMasterPos(IDatabase $conn, $pos=false, $timeout=null)
Definition: LoadBalancer.php:2460
Wikimedia\Rdbms\DBTransactionSizeError
Definition: DBTransactionSizeError.php:28
Wikimedia\Rdbms\IDatabase\getServerName
getServerName()
Get the readable name for the server.
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:52
Wikimedia\Rdbms\LoadBalancer\INFO_SERVER_INDEX
const INFO_SERVER_INDEX
Definition: LoadBalancer.php:144
Wikimedia\Rdbms\LoadBalancer\getClusterName
getClusterName()
Get the logical name of the database cluster.
Definition: LoadBalancer.php:282
Wikimedia\Rdbms\LoadBalancer\getServerInfo
getServerInfo( $i)
Return the server configuration map for the server with the specified index.
Definition: LoadBalancer.php:1553
Wikimedia\Rdbms\LoadBalancer\INFO_FORIEGN
const INFO_FORIEGN
Definition: LoadBalancer.php:146
Wikimedia\Rdbms\LoadBalancer\newTrackedConnectionsArray
static newTrackedConnectionsArray()
Definition: LoadBalancer.php:269
Wikimedia\Rdbms\LoadBalancer\$trxProfiler
TransactionProfiler $trxProfiler
Definition: LoadBalancer.php:60
Wikimedia\Rdbms\LoadBalancer\isOpen
isOpen( $index)
Test if the specified index represents an open connection.
Definition: LoadBalancer.php:1308
Wikimedia\Rdbms\ILoadBalancer\GROUP_GENERIC
const GROUP_GENERIC
The generic query group.
Definition: ILoadBalancer.php:101
Wikimedia\Rdbms\LoadBalancer\$trxRoundId
string bool $trxRoundId
Explicit DBO_TRX transaction round active or false if none.
Definition: LoadBalancer.php:114
Wikimedia\Rdbms\LoadBalancer\hasOrMadeRecentMasterChanges
hasOrMadeRecentMasterChanges( $age=null)
Definition: LoadBalancer.php:2141
Wikimedia\Rdbms\LoadBalancer\assertOwnership
assertOwnership( $fname, $owner)
Assure that if this instance is owned, the caller is either the owner or is internal.
Definition: LoadBalancer.php:2019
Wikimedia\Rdbms\LoadBalancer\MAX_WAIT_DEFAULT
const MAX_WAIT_DEFAULT
Default 'waitTimeout' when unspecified.
Definition: LoadBalancer.php:159
Wikimedia\Rdbms\DatabaseDomain\getId
getId()
Definition: DatabaseDomain.php:200
Wikimedia\Rdbms\IDatabase\pendingWriteQueryDuration
pendingWriteQueryDuration( $type=self::ESTIMATE_TOTAL)
Get the time spend running write queries for this transaction.
Wikimedia\Rdbms\DatabaseDomain\newFromId
static newFromId( $domain)
Definition: DatabaseDomain.php:77
Wikimedia\Rdbms\LoadBalancer\getWriterIndex
getWriterIndex()
Get the specific server index of the primary server.
Definition: LoadBalancer.php:1495
EmptyBagOStuff
A BagOStuff object with no objects in it.
Definition: EmptyBagOStuff.php:29
Wikimedia\Rdbms\LoadBalancer\serverHasLoadInAnyGroup
serverHasLoadInAnyGroup( $i)
Definition: LoadBalancer.php:751
Wikimedia\Rdbms\LoadBalancer\$chronologyCallbackTriggered
bool $chronologyCallbackTriggered
Whether the session consistency callback already executed.
Definition: LoadBalancer.php:134
Wikimedia\Rdbms\IDatabase\rollback
rollback( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Rollback a transaction previously started using begin()
Wikimedia\Rdbms\LoadBalancer\forEachOpenPrimaryConnection
forEachOpenPrimaryConnection( $callback, array $params=[])
Call a function with each open connection object to a primary.
Definition: LoadBalancer.php:2308
Wikimedia\Rdbms\DBAccessError
Exception class for attempted DB access.
Definition: DBAccessError.php:29
Wikimedia\Rdbms\LoadBalancer\lazyLoadReplicationPositions
lazyLoadReplicationPositions()
Make sure that any "waitForPos" positions are loaded and available to doWait()
Definition: LoadBalancer.php:1455
Wikimedia\Rdbms\LoadBalancer\$waitTimeout
int $waitTimeout
Seconds to spend waiting on replica DB lag to resolve.
Definition: LoadBalancer.php:89
if
if(ini_get( 'mbstring.func_overload')) if(!defined('MW_ENTRY_POINT'))
Pre-config setup: Before loading LocalSettings.php.
Definition: Setup.php:92
Wikimedia\Rdbms\LoadBalancer\doWait
doWait( $index, $timeout=null)
Wait for a given replica DB to catch up to the primary DB pos stored in "waitForPos".
Definition: LoadBalancer.php:857
Wikimedia\Rdbms\LoadBalancer\getConnectionIndex
getConnectionIndex( $i, array $groups, $domain)
Get the server index to use for a specified server index and query group list.
Definition: LoadBalancer.php:503
Wikimedia\Rdbms\ILoadMonitor
An interface for database load monitoring.
Definition: ILoadMonitor.php:35
Wikimedia\Rdbms\LoadBalancer\getCurrentConnectionCount
getCurrentConnectionCount()
Definition: LoadBalancer.php:2341
Wikimedia\Rdbms\LoadBalancer\getMasterPos
getMasterPos()
Definition: LoadBalancer.php:1581
Wikimedia\Rdbms\IDatabase\ping
ping(&$rtt=null)
Ping the server and try to reconnect if it there is no connection.
Wikimedia\Rdbms\Database\factory
static factory( $type, $params=[], $connect=self::NEW_CONNECTED)
Construct a Database subclass instance given a database type and parameters.
Definition: Database.php:436
Wikimedia\Rdbms\LoadBalancer\flushPrimarySnapshots
flushPrimarySnapshots( $fname=__METHOD__, $owner=null)
Commit all primary DB transactions so as to flush any REPEATABLE-READ or SSI snapshots.
Definition: LoadBalancer.php:2077
Wikimedia\Rdbms\LoadBalancer\safeGetLag
safeGetLag(IDatabase $conn)
Get the lag in seconds for a given connection, or zero if this load balancer does not have replicatio...
Definition: LoadBalancer.php:2408
Wikimedia\Rdbms\DBReplicationWaitError
Exception class for replica DB wait errors.
Definition: DBReplicationWaitError.php:29
Wikimedia\Rdbms\ILoadBalancer\DB_PRIMARY
const DB_PRIMARY
Request a primary, write-enabled DB connection.
Definition: ILoadBalancer.php:88
Wikimedia\Rdbms\LoadBalancer\CONN_HELD_WARN_THRESHOLD
const CONN_HELD_WARN_THRESHOLD
Warn when this many connection are held.
Definition: LoadBalancer.php:156
Wikimedia\Rdbms\LoadBalancer\getServerInfoStrict
getServerInfoStrict( $i, $field=null)
Definition: LoadBalancer.php:2552
Wikimedia\Rdbms\LoadBalancer\INFO_FOREIGN_REF_COUNT
const INFO_FOREIGN_REF_COUNT
Definition: LoadBalancer.php:147
Wikimedia\Rdbms\LoadBalancer\ROUND_APPROVED
const ROUND_APPROVED
Transaction round passed final pre-commit checks.
Definition: LoadBalancer.php:178
Wikimedia\Rdbms\DatabaseDomain\getTablePrefix
getTablePrefix()
Definition: DatabaseDomain.php:193
Wikimedia\Rdbms\LoadBalancer\approveMasterChanges
approveMasterChanges(array $options, $fname=__METHOD__, $owner=null)
Definition: LoadBalancer.php:1764
Wikimedia\Rdbms\LoadBalancer\$domainAliases
DatabaseDomain[] string[] $domainAliases
Map of (domain alias => DB domain)
Definition: LoadBalancer.php:107
Wikimedia\Rdbms\IDatabase\trxLevel
trxLevel()
Gets the current transaction level.
Wikimedia\Rdbms\LoadBalancer\setLocalDomainPrefix
setLocalDomainPrefix( $prefix)
Set a new table prefix for the existing local domain ID for testing.
Definition: LoadBalancer.php:2490
Wikimedia\Rdbms\LoadBalancer\$nonLocalDomainCache
DatabaseDomain[] $nonLocalDomainCache
Map of (domain ID => domain instance)
Definition: LoadBalancer.php:142
Wikimedia\Rdbms\LoadBalancer\$clusterName
string null $clusterName
The name of the DB cluster.
Definition: LoadBalancer.php:81
Wikimedia\Rdbms
Definition: ChronologyProtector.php:24
Wikimedia\Rdbms\LoadBalancer\$loadMonitorConfig
array $loadMonitorConfig
The LoadMonitor configuration.
Definition: LoadBalancer.php:91
Wikimedia\Rdbms\LoadBalancer\getServerName
getServerName( $i)
Get the readable name of the server with the specified index.
Definition: LoadBalancer.php:1547
Wikimedia\Rdbms\DBPrimaryPos\hasReached
hasReached(DBPrimaryPos $pos)
Wikimedia\Rdbms\LoadBalancer\initConnFlags
initConnFlags( $flags)
Definition: LoadBalancer.php:1440
Wikimedia\Rdbms\LoadBalancer\forEachOpenMasterConnection
forEachOpenMasterConnection( $callback, array $params=[])
Definition: LoadBalancer.php:2320
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:86
Wikimedia\Rdbms\LoadBalancer\getConnectionRef
getConnectionRef( $i, $groups=[], $domain=false, $flags=0)
Get a live database handle reference for a server index.
Definition: LoadBalancer.php:1055
Wikimedia\Rdbms\LoadBalancer\$maxLag
int $maxLag
Definition: LoadBalancer.php:93
Wikimedia\Rdbms\LoadBalancer\sanitizeConnectionFlags
sanitizeConnectionFlags( $flags, $i, $domain)
Definition: LoadBalancer.php:362
Wikimedia\Rdbms\LoadBalancer\getConnection
getConnection( $i, $groups=[], $domain=false, $flags=0)
Get a live handle for a specific or virtual (DB_PRIMARY/DB_REPLICA) server index.
Definition: LoadBalancer.php:921
Wikimedia\Rdbms\DatabaseDomain\getDatabase
getDatabase()
Definition: DatabaseDomain.php:179
Wikimedia\Rdbms\LoadBalancer\enforceConnectionFlags
enforceConnectionFlags(IDatabase $conn, $flags)
Definition: LoadBalancer.php:400
Wikimedia\Rdbms\LoadBalancer\setExistingReaderIndex
setExistingReaderIndex( $group, $index)
Set the server index chosen by the load balancer for use with the given query group.
Definition: LoadBalancer.php:599
Wikimedia\Rdbms\LoadBalancer\getLagTimes
getLagTimes( $domain=false)
Get an estimate of replication lag (in seconds) for each server.
Definition: LoadBalancer.php:2373
Wikimedia\Rdbms\LoadBalancer\$waitForPos
bool DBPrimaryPos $waitForPos
Replication sync position or false if not set.
Definition: LoadBalancer.php:122
Wikimedia\Rdbms\LoadBalancer\getPrimaryPos
getPrimaryPos()
Get the current primary replication position.
Definition: LoadBalancer.php:1561
$success
$success
Definition: NoLocalSettings.php:42
Wikimedia\Rdbms\IDatabase\getLag
getLag()
Get the amount of replication lag for this database server.
Wikimedia\Rdbms\LoadBalancer\$perfLogger
LoggerInterface $perfLogger
Definition: LoadBalancer.php:68
Wikimedia\Rdbms\LoadBalancer\$ownerId
int null $ownerId
Integer ID of the managing LBFactory instance or null if none.
Definition: LoadBalancer.php:139
Wikimedia\Rdbms\LoadBalancer\KEY_FOREIGN_INUSE
const KEY_FOREIGN_INUSE
Definition: LoadBalancer.php:165
Wikimedia\Rdbms\LoadBalancer\finalizeMasterChanges
finalizeMasterChanges( $fname=__METHOD__, $owner=null)
Definition: LoadBalancer.php:1705
Wikimedia\Rdbms\LoadBalancer\MAX_LAG_DEFAULT
const MAX_LAG_DEFAULT
Default 'maxLag' when unspecified.
Definition: LoadBalancer.php:153
Wikimedia\Rdbms\LoadBalancer\getPrimaryServerName
getPrimaryServerName()
Definition: LoadBalancer.php:2571
Wikimedia\Rdbms\LoadBalancer\$replLogger
LoggerInterface $replLogger
Definition: LoadBalancer.php:66
Wikimedia\Rdbms\Database\getFlag
getFlag( $flag)
Returns a boolean whether the flag $flag is set for this connection.
Definition: Database.php:851
Wikimedia\Rdbms\LoadBalancer\flushMasterSnapshots
flushMasterSnapshots( $fname=__METHOD__, $owner=null)
Definition: LoadBalancer.php:2084
Wikimedia\Rdbms\DBError
Database error base class.
Definition: DBError.php:32
Wikimedia\Rdbms\LoadBalancer\isPrimaryRunningReadOnly
isPrimaryRunningReadOnly(DatabaseDomain $domain)
Definition: LoadBalancer.php:2246
Wikimedia\Rdbms\LoadBalancer\hasMasterChanges
hasMasterChanges()
Definition: LoadBalancer.php:2115
Wikimedia\Rdbms\LoadBalancer\ROUND_ERROR
const ROUND_ERROR
Transaction round encountered an error.
Definition: LoadBalancer.php:184
Wikimedia\Rdbms\LoadBalancer\getServerAttributes
getServerAttributes( $i)
Get basic attributes of the server with the specified index without connecting.
Definition: LoadBalancer.php:1295
Wikimedia\Rdbms\LoadBalancer\KEY_LOCAL_DOMAIN
const KEY_LOCAL_DOMAIN
Definition: LoadBalancer.php:171
Wikimedia\Rdbms\LoadBalancer\resolveDomainID
resolveDomainID( $domain)
Definition: LoadBalancer.php:297
DBO_TRX
const DBO_TRX
Definition: defines.php:12
Wikimedia\Rdbms\LoadBalancer\KEY_FOREIGN_INUSE_NOROUND
const KEY_FOREIGN_INUSE_NOROUND
Definition: LoadBalancer.php:169
Wikimedia\Rdbms\IDatabase\dbSchema
dbSchema( $schema=null)
Get/set the db schema.
Wikimedia\Rdbms\LoadBalancer\commitMasterChanges
commitMasterChanges( $fname=__METHOD__, $owner=null)
Definition: LoadBalancer.php:1843
Wikimedia\Rdbms\LoadBalancer\getMaxLag
getMaxLag( $domain=false)
Get the name and lag time of the most-lagged replica server.
Definition: LoadBalancer.php:2352
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
Wikimedia\Rdbms\IDatabase\lastDoneWrites
lastDoneWrites()
Get the last time the connection may have been used for a write query.
Wikimedia\Rdbms\DBPrimaryPos
An object representing a primary or replica DB position in a replicated setup.
Definition: DBPrimaryPos.php:15
Wikimedia\Rdbms\LoadBalancer\hasPrimaryConnection
hasPrimaryConnection()
Definition: LoadBalancer.php:2097
Wikimedia\Rdbms\LoadBalancer\$deprecationLogger
callable $deprecationLogger
Deprecation logger.
Definition: LoadBalancer.php:72
Wikimedia\Rdbms\DatabaseDomain\newUnspecified
static newUnspecified()
Definition: DatabaseDomain.php:118
WANObjectCache\newEmpty
static newEmpty()
Get an instance that wraps EmptyBagOStuff.
Definition: WANObjectCache.php:388
Wikimedia\Rdbms\MaintainableDBConnRef
Helper class to handle automatically marking connections as reusable (via RAII pattern) as well handl...
Definition: MaintainableDBConnRef.php:13
Wikimedia\Rdbms\LoadBalancer\TTL_CACHE_READONLY
const TTL_CACHE_READONLY
Seconds to cache primary DB server read-only status.
Definition: LoadBalancer.php:161
Wikimedia\Rdbms\LoadBalancer\setLocalDomain
setLocalDomain(DatabaseDomain $domain)
Definition: LoadBalancer.php:2542
Wikimedia\Rdbms\LoadBalancer\getReaderIndex
getReaderIndex( $group=false, $domain=false)
Get the specific server index of the reader connection for a given group.
Definition: LoadBalancer.php:527
Wikimedia\Rdbms\LoadBalancer\KEY_LOCAL_NOROUND
const KEY_LOCAL_NOROUND
Definition: LoadBalancer.php:167
Wikimedia\Rdbms\Database\runOnTransactionPreCommitCallbacks
runOnTransactionPreCommitCallbacks()
Consume and run any "on transaction pre-commit" callbacks.
Definition: Database.php:4456
Wikimedia\Rdbms\LoadBalancer\KEY_LOCAL
const KEY_LOCAL
Definition: LoadBalancer.php:163
Wikimedia\Rdbms\LoadBalancer\$tempTablesOnlyMode
bool[] $tempTablesOnlyMode
Map of (domain => whether to use "temp tables only" mode)
Definition: LoadBalancer.php:111
Wikimedia\Rdbms\LoadBalancer\$groupLoads
array[] $groupLoads
Map of (group => server index => weight)
Definition: LoadBalancer.php:85
Wikimedia\Rdbms\LoadBalancer\KEY_FOREIGN_FREE
const KEY_FOREIGN_FREE
Definition: LoadBalancer.php:164
Wikimedia\Rdbms\LoadBalancer\INFO_AUTOCOMMIT_ONLY
const INFO_AUTOCOMMIT_ONLY
Definition: LoadBalancer.php:145
Wikimedia\Rdbms\LoadBalancer\$csProvider
CriticalSectionProvider null $csProvider
Definition: LoadBalancer.php:47
Wikimedia\Rdbms\LoadBalancer\$id
$id
var int An identifier for this class instance
Definition: LoadBalancer.php:137
Wikimedia\Rdbms\LoadBalancer\$maxLagByIndex
int[] $maxLagByIndex
Map of (server index => seconds of lag considered "high")
Definition: LoadBalancer.php:87
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
Definition: GlobalFunctions.php:997
Wikimedia\Rdbms\LoadBalancer\rollbackPrimaryChanges
rollbackPrimaryChanges( $fname=__METHOD__, $owner=null)
Issue ROLLBACK only on primary, only if queries were done on connection.
Definition: LoadBalancer.php:1959
Wikimedia\Rdbms\LoadBalancer\pendingMasterChangeCallers
pendingMasterChangeCallers()
Definition: LoadBalancer.php:2155
Wikimedia\Rdbms\LoadBalancer\flushReplicaSnapshots
flushReplicaSnapshots( $fname=__METHOD__, $owner=null)
Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshots.
Definition: LoadBalancer.php:2070
Wikimedia\Rdbms\LoadBalancer\closeAll
closeAll( $fname=__METHOD__, $owner=null)
Close all open connections.
Definition: LoadBalancer.php:1617
Wikimedia\Rdbms\Database\trxLevel
trxLevel()
Gets the current transaction level.
Definition: Database.php:594
Wikimedia\Rdbms\Database\setFlag
setFlag( $flag, $remember=self::REMEMBER_NOTHING)
Set a flag for this connection.
Definition: Database.php:808
Wikimedia\Rdbms\LoadBalancer\finalizePrimaryChanges
finalizePrimaryChanges( $fname=__METHOD__, $owner=null)
Run pre-commit callbacks and defer execution of post-commit callbacks.
Definition: LoadBalancer.php:1676
Wikimedia\Rdbms\LoadBalancer\setTempTablesOnlyMode
setTempTablesOnlyMode( $value, $domain)
Indicate whether the tables on this domain are only temporary tables for testing.
Definition: LoadBalancer.php:2528
Wikimedia\Rdbms\LoadBalancer\__destruct
__destruct()
Definition: LoadBalancer.php:2601
Wikimedia\Rdbms\LoadBalancer\reallyOpenConnection
reallyOpenConnection( $i, DatabaseDomain $domain, array $lbInfo)
Open a new network connection to a server (uncached)
Definition: LoadBalancer.php:1324
Wikimedia\Rdbms\LoadBalancer\hasPrimaryChanges
hasPrimaryChanges()
Whether there are pending changes or callbacks in a transaction by this thread.
Definition: LoadBalancer.php:2106
Wikimedia\Rdbms\LoadBalancer\hasMasterConnection
hasMasterConnection()
Definition: LoadBalancer.php:2101
Wikimedia\Rdbms\IDatabase\primaryPosWait
primaryPosWait(DBPrimaryPos $pos, $timeout)
Wait for the replica DB to catch up to a given primary DB position.
Wikimedia\Rdbms\ILoadBalancer\CONN_SILENCE_ERRORS
const CONN_SILENCE_ERRORS
Return null on connection failure instead of throwing an exception.
Definition: ILoadBalancer.php:106
Wikimedia\Rdbms\LoadBalancer\disable
disable( $fname=__METHOD__, $owner=null)
Close all connections and disable this load balancer.
Definition: LoadBalancer.php:1611
Wikimedia\Rdbms\LoadBalancer\applyTransactionRoundFlags
applyTransactionRoundFlags(Database $conn)
Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round.
Definition: LoadBalancer.php:2037
Wikimedia\Rdbms\LoadBalancer\forEachOpenConnection
forEachOpenConnection( $callback, array $params=[])
Call a function with each open connection object.
Definition: LoadBalancer.php:2298
Wikimedia\Rdbms\LoadBalancer\$srvCache
BagOStuff $srvCache
Definition: LoadBalancer.php:51
Wikimedia\Rdbms\LoadBalancer\isNonZeroLoad
isNonZeroLoad( $i)
Returns true if the specified index is valid and has non-zero load.
Definition: LoadBalancer.php:1517
Wikimedia\Rdbms\LoadBalancer\__construct
__construct(array $params)
Construct a manager of IDatabase connection objects.
Definition: LoadBalancer.php:189
Wikimedia\Rdbms\IDatabase\close
close( $fname=__METHOD__, $owner=null)
Close the database connection.
Wikimedia\Rdbms\LoadBalancer\getStreamingReplicaIndexes
getStreamingReplicaIndexes()
Definition: LoadBalancer.php:1532
Wikimedia\Rdbms\LoadBalancer\$errorLogger
callable $errorLogger
Exception logger.
Definition: LoadBalancer.php:70
Wikimedia\Rdbms\LoadBalancer\pingAll
pingAll()
Definition: LoadBalancer.php:2287
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
Wikimedia\Rdbms\LoadBalancer\$lastError
string $lastError
The last DB selection or connection error.
Definition: LoadBalancer.php:126
Wikimedia\Rdbms\Database\runTransactionListenerCallbacks
runTransactionListenerCallbacks( $trigger, array &$errors=[])
Actually run any "transaction listener" callbacks.
Definition: Database.php:4521
Wikimedia\Rdbms\Database\restoreFlags
restoreFlags( $state=self::RESTORE_PRIOR)
Restore the flags to their prior state before the last setFlag/clearFlag call.
Definition: Database.php:838
Wikimedia\Rdbms\Database\setLBInfo
setLBInfo( $nameOrArray, $value=null)
Set the entire array or a particular key of the managing load balancer info array.
Definition: Database.php:666
Wikimedia\Rdbms\Database\getLBInfo
getLBInfo( $name=null)
Get properties passed down from the server info array of the load balancer.
Definition: Database.php:654
Wikimedia\Rdbms\LoadBalancer
Database connection, tracking, load balancing, and transaction manager for a cluster.
Definition: LoadBalancer.php:43
Wikimedia\Rdbms\LoadBalancer\resolveGroups
resolveGroups( $groups, $i)
Resolve $groups into a list of query groups defining as having database servers.
Definition: LoadBalancer.php:333
Wikimedia\Rdbms\LoadBalancer\getMaintenanceConnectionRef
getMaintenanceConnectionRef( $i, $groups=[], $domain=false, $flags=0)
Get a live database handle, suitable for migrations and schema changes, for a server index.
Definition: LoadBalancer.php:1082
Wikimedia\Rdbms\LoadBalancer\redefineLocalDomain
redefineLocalDomain( $domain)
Close all connection and redefine the local domain for testing or schema creation.
Definition: LoadBalancer.php:2522
Wikimedia\Rdbms\LoadBalancer\runMasterTransactionIdleCallbacks
runMasterTransactionIdleCallbacks( $fname=__METHOD__, $owner=null)
Definition: LoadBalancer.php:1920
Wikimedia\Rdbms\LoadBalancer\$chronologyCallback
callable null $chronologyCallback
Callback to run before the first connection attempt.
Definition: LoadBalancer.php:49
Wikimedia\Rdbms\LoadBalancer\waitForPrimaryPos
waitForPrimaryPos(IDatabase $conn, $pos=false, $timeout=null)
Wait for a replica DB to reach a specified primary position.
Definition: LoadBalancer.php:2412
Wikimedia\Rdbms\LoadBalancer\getLoadMonitor
getLoadMonitor()
Get a LoadMonitor instance.
Definition: LoadBalancer.php:418
Wikimedia\Rdbms\LoadBalancer\$servers
array[] $servers
Map of (server index => server config array)
Definition: LoadBalancer.php:83
Wikimedia\Rdbms\LoadBalancer\lastPrimaryChangeTimestamp
lastPrimaryChangeTimestamp()
Get the timestamp of the latest write query done by this thread.
Definition: LoadBalancer.php:2120
Wikimedia\Rdbms\LoadBalancer\setTransactionListener
setTransactionListener( $name, callable $callback=null)
Set a callback via IDatabase::setTransactionListener() on all current and future primary connections ...
Definition: LoadBalancer.php:2465
DB_PRIMARY
const DB_PRIMARY
Definition: defines.php:27
Wikimedia\Rdbms\IDatabase\explicitTrxActive
explicitTrxActive()
Check whether there is a transaction open at the specific request of a caller.
Wikimedia\Rdbms\LoadBalancer\pendingPrimaryChangeCallers
pendingPrimaryChangeCallers()
Get the list of callers that have pending primary changes.
Definition: LoadBalancer.php:2146
Wikimedia\Rdbms\ILoadBalancer\CONN_INTENT_WRITABLE
const CONN_INTENT_WRITABLE
Caller is requesting the primary DB server for possibly writes.
Definition: ILoadBalancer.php:108
Wikimedia\Rdbms\IDatabase\getDomainID
getDomainID()
Return the currently selected domain ID.
Wikimedia\Rdbms\IDatabase\setTransactionListener
setTransactionListener( $name, callable $callback=null)
Run a callback after each time any transaction commits or rolls back.
Wikimedia\Rdbms\IDatabase\getDBname
getDBname()
Get the current database name; null if there isn't one.
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:131
Wikimedia\Rdbms\LoadBalancer\getLocalDomainID
getLocalDomainID()
Get the local (and default) database domain ID of connection handles.
Definition: LoadBalancer.php:293
Wikimedia\Rdbms\Database\setTrxEndCallbackSuppression
setTrxEndCallbackSuppression( $suppress)
Whether to disable running of post-COMMIT/ROLLBACK callbacks.
Definition: Database.php:4375
Wikimedia\Rdbms\LoadBalancer\getLocalConnection
getLocalConnection( $i, $flags=0)
Open a connection to a local DB, or return one if it is already open.
Definition: LoadBalancer.php:1136
Wikimedia\Rdbms\IDatabase\pendingWriteCallers
pendingWriteCallers()
Get the list of method names that did write queries for this transaction.
Wikimedia\Rdbms\LoadBalancer\setDomainAliases
setDomainAliases(array $aliases)
Convert certain database domains to alternative ones.
Definition: LoadBalancer.php:2486
Wikimedia\Rdbms\LoadBalancer\$connectionCounter
int $connectionCounter
Total number of new connections ever made with this instance.
Definition: LoadBalancer.php:130
Wikimedia\Rdbms\LoadBalancer\rollbackMasterChanges
rollbackMasterChanges( $fname=__METHOD__, $owner=null)
Definition: LoadBalancer.php:1981
Wikimedia\Rdbms\LoadBalancer\getServerConnection
getServerConnection( $i, $domain, $flags=0)
Get a live handle for a specific server index.
Definition: LoadBalancer.php:949
Wikimedia\Rdbms\DBUnexpectedError
Definition: DBUnexpectedError.php:29
Wikimedia\Rdbms\LoadBalancer\getLazyConnectionRef
getLazyConnectionRef( $i, $groups=[], $domain=false, $flags=0)
Get a lazy-connecting database handle reference for a server index.
Definition: LoadBalancer.php:1069
Wikimedia\Rdbms\LoadBalancer\$trxRoundStage
string $trxRoundStage
Stage of the current transaction round in the transaction round life-cycle.
Definition: LoadBalancer.php:116
Wikimedia\Rdbms\LoadBalancer\$indexAliases
string[] $indexAliases
Map of (index alias => index)
Definition: LoadBalancer.php:105
Wikimedia\Rdbms\LoadBalancer\beginMasterChanges
beginMasterChanges( $fname=__METHOD__, $owner=null)
Definition: LoadBalancer.php:1798
Wikimedia\Rdbms\ILoadBalancer\CONN_TRX_AUTOCOMMIT
const CONN_TRX_AUTOCOMMIT
DB handle should have DBO_TRX disabled and the caller will leave it as such.
Definition: ILoadBalancer.php:104
Wikimedia\Rdbms\LoadBalancer\$readOnlyReason
string bool $readOnlyReason
Reason this instance is read-only or false if not.
Definition: LoadBalancer.php:128
Wikimedia\Rdbms\LoadBalancer\getTransactionRoundStage
getTransactionRoundStage()
Definition: LoadBalancer.php:2093
Wikimedia\Rdbms\LoadBalancer\hasStreamingReplicaServers
hasStreamingReplicaServers()
Whether any replica servers use streaming replication from the primary server.
Definition: LoadBalancer.php:1543
Wikimedia\Rdbms\LoadBalancer\getConnLogContext
getConnLogContext(IDatabase $conn, array $extras=[])
Create a log context to pass to PSR-3 logger functions.
Definition: LoadBalancer.php:2591
Wikimedia\Rdbms\LoadBalancer\getForeignConnection
getForeignConnection( $i, $domain, $flags=0)
Open a connection to a foreign DB, or return one if it is already open.
Definition: LoadBalancer.php:1199
Wikimedia\Rdbms\LoadBalancer\$conns
IDatabase[][][] $conns
Map of (pool category => server index => domain => IDatabase)
Definition: LoadBalancer.php:78
Wikimedia\Rdbms\LoadBalancer\$defaultGroup
string null $defaultGroup
Default query group to use with getConnection()
Definition: LoadBalancer.php:95
Wikimedia\Rdbms\DBConnRef
Helper class used for automatically marking an IDatabase connection as reusable (once it no longer ma...
Definition: DBConnRef.php:30
Wikimedia\Rdbms\LoadBalancer\setTableAliases
setTableAliases(array $aliases)
Make certain table names use their own database, schema, and table prefix when passed into SQL querie...
Definition: LoadBalancer.php:2478
Wikimedia\Rdbms\LoadBalancer\beginPrimaryChanges
beginPrimaryChanges( $fname=__METHOD__, $owner=null)
Flush any primary transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
Definition: LoadBalancer.php:1769
Wikimedia\Rdbms\DBTransactionError
Definition: DBTransactionError.php:29
Wikimedia\Rdbms\LoadBalancer\assertTransactionRoundStage
assertTransactionRoundStage( $stage)
Definition: LoadBalancer.php:1990
Wikimedia\Rdbms\LoadBalancer\$localDomain
DatabaseDomain $localDomain
Local DB domain ID and default for selectDB() calls.
Definition: LoadBalancer.php:75
Wikimedia\Rdbms\ILoadBalancer\CONN_REFRESH_READ_ONLY
const CONN_REFRESH_READ_ONLY
Bypass and update any server-side read-only mode state cache.
Definition: ILoadBalancer.php:110
ArrayUtils\pickRandom
static pickRandom( $weights)
Given an array of non-normalised probabilities, this function will select an element and return the a...
Definition: ArrayUtils.php:66
Wikimedia\Rdbms\LoadBalancer\getAnyOpenConnection
getAnyOpenConnection( $i, $flags=0)
Get an existing live handle to the given server index (on any domain)
Definition: LoadBalancer.php:774
ArrayUtils
A collection of static methods to play with arrays.
Definition: ArrayUtils.php:28
Wikimedia\Rdbms\LoadBalancer\$disabled
bool $disabled
Definition: LoadBalancer.php:132
Wikimedia\Rdbms\LoadBalancer\getLaggedReplicaMode
getLaggedReplicaMode( $domain=false)
Definition: LoadBalancer.php:2160
Wikimedia\Rdbms\LoadBalancer\commitAll
commitAll( $fname=__METHOD__, $owner=null)
Commit transactions on all open connections.
Definition: LoadBalancer.php:1670
Wikimedia\Rdbms\LoadBalancer\runPrimaryTransactionListenerCallbacks
runPrimaryTransactionListenerCallbacks( $fname=__METHOD__, $owner=null)
Run all recurring post-COMMIT/ROLLBACK listener callbacks.
Definition: LoadBalancer.php:1925
Wikimedia\Rdbms\Database\writesPending
writesPending()
Definition: Database.php:706
Wikimedia\Rdbms\LoadBalancer\hasReplicaServers
hasReplicaServers()
Whether there are any replica servers configured.
Definition: LoadBalancer.php:1525
Wikimedia\Rdbms\DatabaseDomain\getSchema
getSchema()
Definition: DatabaseDomain.php:186
Wikimedia\Rdbms\LoadBalancer\runMasterTransactionListenerCallbacks
runMasterTransactionListenerCallbacks( $fname=__METHOD__, $owner=null)
Definition: LoadBalancer.php:1954
Wikimedia\Rdbms\LoadBalancer\isPrimaryConnectionReadOnly
isPrimaryConnectionReadOnly(IDatabase $conn, $flags=0)
Definition: LoadBalancer.php:2204
Wikimedia\Rdbms\LoadBalancer\$errorConnection
Database $errorConnection
Connection handle that caused a problem.
Definition: LoadBalancer.php:118
Wikimedia\Rdbms\DBConnectionError
Definition: DBConnectionError.php:27
Wikimedia\Rdbms\Database\getServerName
getServerName()
Get the readable name for the server.
Definition: Database.php:3079
Wikimedia\Rdbms\IDatabase\getLBInfo
getLBInfo( $name=null)
Get properties passed down from the server info array of the load balancer.
Wikimedia\Rdbms\Database\runOnTransactionIdleCallbacks
runOnTransactionIdleCallbacks( $trigger, array &$errors=[])
Consume and run any "on transaction idle/resolution" callbacks.
Definition: Database.php:4391
Wikimedia\Rdbms\LoadBalancer\getTopologyRole
getTopologyRole( $i, array $server)
Definition: LoadBalancer.php:1425
Wikimedia\Rdbms\LoadBalancer\ROUND_COMMIT_CALLBACKS
const ROUND_COMMIT_CALLBACKS
Transaction round was committed and post-commit callbacks must be run.
Definition: LoadBalancer.php:180
Wikimedia\Rdbms\LoadBalancer\resolveDomainInstance
resolveDomainInstance( $domain)
Definition: LoadBalancer.php:305
Wikimedia\Rdbms\LoadBalancer\haveIndex
haveIndex( $i)
Returns true if the specified index is a valid server index.
Definition: LoadBalancer.php:1506
Wikimedia\Rdbms\LoadBalancer\getReplicaResumePos
getReplicaResumePos()
Get the highest DB replication position for chronology control purposes.
Definition: LoadBalancer.php:1586
Wikimedia\Rdbms\LoadBalancer\$trxRecurringCallbacks
callable[] $trxRecurringCallbacks
Map of (name => callable)
Definition: LoadBalancer.php:109
Wikimedia\Rdbms\LoadBalancer\getReadOnlyReason
getReadOnlyReason( $domain=false)
Definition: LoadBalancer.php:2180
Wikimedia\Rdbms\Database\attributesFromType
static attributesFromType( $dbType, $driver=null)
Definition: Database.php:492
Wikimedia\Rdbms\LoadBalancer\runPrimaryTransactionIdleCallbacks
runPrimaryTransactionIdleCallbacks( $fname=__METHOD__, $owner=null)
Consume and run all pending post-COMMIT/ROLLBACK callbacks and commit dangling transactions.
Definition: LoadBalancer.php:1848
Wikimedia\Rdbms\LoadBalancer\hasOrMadeRecentPrimaryChanges
hasOrMadeRecentPrimaryChanges( $age=null)
Check if this load balancer object had any recent or still pending writes issued against it by this P...
Definition: LoadBalancer.php:2134
Wikimedia\Rdbms\LoadBalancer\pickReaderIndex
pickReaderIndex(array $loads, string $domain)
Pick a server that is reachable, preferably non-lagged, and return its server index.
Definition: LoadBalancer.php:615
Wikimedia\Rdbms\IDatabase\serverIsReadOnly
serverIsReadOnly()
Wikimedia\Rdbms\LoadBalancer\reuseConnection
reuseConnection(IDatabase $conn)
Mark a live handle as being available for reuse under a different database domain.
Definition: LoadBalancer.php:1003
Wikimedia\Rdbms\LoadBalancer\$readIndexByGroup
int[] $readIndexByGroup
The group replica server indexes keyed by group.
Definition: LoadBalancer.php:120
Wikimedia\Rdbms\LoadBalancer\setIndexAliases
setIndexAliases(array $aliases)
Convert certain index names to alternative names before querying the DB.
Definition: LoadBalancer.php:2482
Wikimedia\Rdbms\LoadBalancer\commitPrimaryChanges
commitPrimaryChanges( $fname=__METHOD__, $owner=null)
Issue COMMIT on all open primary connections to flush changes and view snapshots.
Definition: LoadBalancer.php:1803
Wikimedia\Rdbms\LoadBalancer\laggedReplicaUsed
laggedReplicaUsed()
Checks whether the database for generic connections this request was both:
Definition: LoadBalancer.php:2176
Wikimedia\Rdbms\LoadBalancer\$wanCache
WANObjectCache $wanCache
Definition: LoadBalancer.php:53
Wikimedia\Rdbms\LoadBalancer\undoTransactionRoundFlags
undoTransactionRoundFlags(Database $conn)
Definition: LoadBalancer.php:2056
Wikimedia\Rdbms\LoadBalancer\$agent
string $agent
Agent name for query profiling.
Definition: LoadBalancer.php:100
Wikimedia\Rdbms\DatabaseDomain
Class to handle database/schema/prefix specifications for IDatabase.
Definition: DatabaseDomain.php:40
Wikimedia\Rdbms\LoadBalancer\fieldHasBit
fieldHasBit(int $flags, int $bit)
Definition: LoadBalancer.php:2580
Wikimedia\Rdbms\TransactionProfiler
Detect high-contention DB queries via profiling calls.
Definition: TransactionProfiler.php:40
Wikimedia\Rdbms\LoadBalancer\$laggedReplicaMode
bool $laggedReplicaMode
Whether the generic reader fell back to a lagged replica DB.
Definition: LoadBalancer.php:124
Wikimedia\Rdbms\LoadBalancer\$queryLogger
LoggerInterface $queryLogger
Definition: LoadBalancer.php:64
Wikimedia\Rdbms\LoadBalancer\$loadMonitor
ILoadMonitor $loadMonitor
Definition: LoadBalancer.php:45
Wikimedia\Rdbms\LoadBalancer\openConnection
openConnection( $i, $domain=false, $flags=0)
Definition: LoadBalancer.php:1118
DBO_DEFAULT
const DBO_DEFAULT
Definition: defines.php:13
Wikimedia\Rdbms\LoadBalancer\waitForAll
waitForAll( $pos, $timeout=null)
Set the primary wait position and wait for ALL replica DBs to catch up to it.
Definition: LoadBalancer.php:721
Wikimedia\Rdbms\LoadBalancer\forEachOpenReplicaConnection
forEachOpenReplicaConnection( $callback)
Definition: LoadBalancer.php:2325
Wikimedia\Rdbms\LoadBalancer\$connLogger
LoggerInterface $connLogger
Definition: LoadBalancer.php:62
Wikimedia\Rdbms\LoadBalancer\waitFor
waitFor( $pos)
Set the primary position to reach before the next generic group DB handle query.
Definition: LoadBalancer.php:703
Wikimedia\Rdbms\LoadBalancer\ROUND_CURSORY
const ROUND_CURSORY
Transaction round, explicit or implicit, has not finished writing.
Definition: LoadBalancer.php:174
Wikimedia\Rdbms\ILoadBalancer\DB_REPLICA
const DB_REPLICA
Request a replica DB connection.
Definition: ILoadBalancer.php:83
Wikimedia\Rdbms\LoadBalancer\getRandomNonLagged
getRandomNonLagged(array $loads, string $domain, $maxLag=INF)
Definition: LoadBalancer.php:445
Wikimedia\Rdbms\LoadBalancer\lastMasterChangeTimestamp
lastMasterChangeTimestamp()
Definition: LoadBalancer.php:2129
Wikimedia\Rdbms\LoadBalancer\$cliMode
bool $cliMode
Whether this PHP instance is for a CLI script.
Definition: LoadBalancer.php:98
Wikimedia\Rdbms\LoadBalancer\ROUND_ROLLBACK_CALLBACKS
const ROUND_ROLLBACK_CALLBACKS
Transaction round was rolled back and post-rollback callbacks must be run.
Definition: LoadBalancer.php:182
Wikimedia\Rdbms\LoadBalancer\pickAnyOpenConnection
pickAnyOpenConnection(array $connsByServer, $autoCommitOnly)
Definition: LoadBalancer.php:811
Wikimedia\Rdbms\ILoadBalancer
Database cluster connection, tracking, load balancing, and transaction manager interface.
Definition: ILoadBalancer.php:81
Wikimedia\Rdbms\LoadBalancer\getServerCount
getServerCount()
Get the number of servers defined in configuration.
Definition: LoadBalancer.php:1521
Wikimedia\Rdbms\IDatabase\commit
commit( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Commits a transaction previously started using begin()
Wikimedia\Rdbms\LoadBalancer\closeConnection
closeConnection(IDatabase $conn)
Close a connection.
Definition: LoadBalancer.php:1632
Wikimedia\Rdbms\LoadBalancer\KEY_FOREIGN_FREE_NOROUND
const KEY_FOREIGN_FREE_NOROUND
Definition: LoadBalancer.php:168
Wikimedia\Rdbms\IDatabase\flushSnapshot
flushSnapshot( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Commit any transaction but error out if writes or callbacks are pending.
Wikimedia\Rdbms\LoadBalancer\reportConnectionError
reportConnectionError()
Definition: LoadBalancer.php:1467
Wikimedia\Rdbms\LoadBalancer\ROUND_FINALIZED
const ROUND_FINALIZED
Transaction round writes are complete and ready for pre-commit checks.
Definition: LoadBalancer.php:176
Wikimedia\Rdbms\LoadBalancer\approvePrimaryChanges
approvePrimaryChanges(array $options, $fname=__METHOD__, $owner=null)
Perform all pre-commit checks for things like replication safety.
Definition: LoadBalancer.php:1710
Wikimedia\Rdbms\IDatabase\clearFlag
clearFlag( $flag, $remember=self::REMEMBER_NOTHING)
Clear a flag for this connection.
Wikimedia\Rdbms\LoadBalancer\$tableAliases
array[] $tableAliases
$aliases Map of (table => (dbname, schema, prefix) map)
Definition: LoadBalancer.php:103
$type
$type
Definition: testCompression.php:52
Wikimedia\Rdbms\LoadBalancer\getRoleFromIndex
getRoleFromIndex( $i)
Definition: LoadBalancer.php:1105
Wikimedia\Rdbms\IDatabase\writesOrCallbacksPending
writesOrCallbacksPending()
Whether there is a transaction open with either possible write queries or unresolved pre-commit/commi...