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