MediaWiki REL1_40
Wikimedia\Rdbms\LoadBalancer Class Reference

Inherits Wikimedia\Rdbms\ILoadBalancerForOwner.

Inherited by Wikimedia\Rdbms\LoadBalancerDisabled, and Wikimedia\Rdbms\LoadBalancerSingle.

Collaboration diagram for Wikimedia\Rdbms\LoadBalancer:

Public Member Functions

 __construct (array $params)
 
 approvePrimaryChanges (int $maxWriteDuration, $fname=__METHOD__)
 Perform all pre-commit checks for things like replication safety.
 
 beginPrimaryChanges ( $fname=__METHOD__)
 Flush any primary transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
 
 closeAll ( $fname=__METHOD__)
 Close all open connections.
 
 closeConnection (IDatabase $conn)
 Close a connection.
 
 commitPrimaryChanges ( $fname=__METHOD__)
 Issue COMMIT on all open primary connections to flush changes and view snapshots.
 
 disable ( $fname=__METHOD__)
 Close all connections and disable this load balancer.
 
 explicitTrxActive ()
 Determine whether an explicit transaction is active on any open primary connection.
 
 finalizePrimaryChanges ( $fname=__METHOD__)
 Run pre-commit callbacks and defer execution of post-commit callbacks.
 
 flushPrimarySessions ( $fname=__METHOD__)
 Release/destroy session-level named locks, table locks, and temp tables.
 
 flushPrimarySnapshots ( $fname=__METHOD__)
 Commit all primary DB transactions so as to flush any REPEATABLE-READ or SSI snapshots.
 
 flushReplicaSnapshots ( $fname=__METHOD__)
 Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshots.
 
 getAnyOpenConnection ( $i, $flags=0)
 Get an existing DB handle to the given server index (on any domain)
 
 getClusterName ()
 Get the name of the overall cluster of database servers managing the dataset.
 
 getConnection ( $i, $groups=[], $domain=false, $flags=0)
 Get a lazy-connecting database handle for a specific or virtual (DB_PRIMARY/DB_REPLICA) server index.
 
 getConnectionInternal ( $i, $groups=[], $domain=false, $flags=0)
 
 getConnectionRef ( $i, $groups=[], $domain=false, $flags=0)
 
 getLagTimes ()
 Get an estimate of replication lag (in seconds) for each server.
 
 getLocalDomainID ()
 Get the local (and default) database domain ID of connection handles.
 
 getMaintenanceConnectionRef ( $i, $groups=[], $domain=false, $flags=0)
 Get a DB handle, suitable for migrations and schema changes, for a server index.
 
 getMaxLag ()
 Get the name and lag time of the most-lagged replica server.
 
 getPrimaryPos ()
 Get the current primary replication position.
 
 getReaderIndex ( $group=false)
 Get the specific server index of the reader connection for a given group.
 
 getReadOnlyReason ( $domain=false)
 
 getReplicaResumePos ()
 Get the highest DB replication position for chronology control purposes.
 
 getServerAttributes ( $i)
 Get basic attributes of the server with the specified index without connecting.
 
 getServerConnection ( $i, $domain, $flags=0)
 Get a DB handle for a specific server index.
 
 getServerCount ()
 Get the number of servers defined in configuration.
 
 getServerInfo ( $i)
 Return the server configuration map for the server with the specified index.
 
 getServerName ( $i)
 Get the readable name of the server with the specified index.
 
 getServerType ( $i)
 Get the RDBMS type of the server with the specified index (e.g.
 
 getWriterIndex ()
 Get the specific server index of the "writer server".
 
 hasOrMadeRecentPrimaryChanges ( $age=null)
 Check if this load balancer object had any recent or still pending writes issued against it by this PHP thread.
 
 hasPrimaryChanges ()
 Whether there are pending changes or callbacks in a transaction by this thread.
 
 hasPrimaryConnection ()
 
 hasReplicaServers ()
 Whether there are any replica servers configured.
 
 hasStreamingReplicaServers ()
 Whether any replica servers use streaming replication from the primary server.
 
 laggedReplicaUsed ()
 Whether a highly "lagged" replica database connection was queried.
 
 lastPrimaryChangeTimestamp ()
 Get the timestamp of the latest write query done by this thread.
 
 pendingPrimaryChangeCallers ()
 Get the list of callers that have pending primary changes.
 
 pingAll ()
 
 reconfigure (array $params)
 Apply updated configuration.
 
 redefineLocalDomain ( $domain)
 Close all connection and redefine the local domain for testing or schema creation.
 
 resolveDomainID ( $domain)
 
 reuseConnection (IDatabase $conn)
 
 rollbackPrimaryChanges ( $fname=__METHOD__)
 Issue ROLLBACK only on primary, only if queries were done on connection.
 
 runPrimaryTransactionIdleCallbacks ( $fname=__METHOD__)
 Consume and run all pending post-COMMIT/ROLLBACK callbacks and commit dangling transactions.
 
 runPrimaryTransactionListenerCallbacks ( $fname=__METHOD__)
 Run all recurring post-COMMIT/ROLLBACK listener callbacks.
 
 setDomainAliases (array $aliases)
 Convert certain database domains to alternative ones.
 
 setIndexAliases (array $aliases)
 Convert certain index names to alternative names before querying the DB.
 
 setLocalDomainPrefix ( $prefix)
 Set a new table prefix for the existing local domain ID for testing.
 
 setTableAliases (array $aliases)
 Make certain table names use their own database, schema, and table prefix when passed into SQL queries pre-escaped and without a qualified database name.
 
 setTempTablesOnlyMode ( $value, $domain)
 Indicate whether the tables on this domain are only temporary tables for testing.
 
 setTransactionListener ( $name, callable $callback=null)
 Set a callback via IDatabase::setTransactionListener() on all current and future primary connections of this load balancer.
 
 waitFor (DBPrimaryPos $pos)
 Set the primary position to reach before the next generic group DB query.
 
 waitForAll (DBPrimaryPos $pos, $timeout=null)
 Set the primary wait position and wait for ALL replica DBs to catch up to it.
 
 waitForPrimaryPos (IDatabase $conn)
 Wait for a replica DB to reach a specified primary position.
 

Public Attributes

const MAX_LAG_DEFAULT = ServerInfo::MAX_LAG_DEFAULT
 Default 'maxLag' when unspecified.
 
- Public Attributes inherited from Wikimedia\Rdbms\ILoadBalancerForOwner
const STAGE_POSTCOMMIT_CALLBACKS = 'stage-postcommit-callbacks'
 Manager of ILoadBalancer instances is running post-commit callbacks.
 
const STAGE_POSTROLLBACK_CALLBACKS = 'stage-postrollback-callbacks'
 Manager of ILoadBalancer instances is running post-rollback callbacks.
 
- Public Attributes inherited from Wikimedia\Rdbms\ILoadBalancer
const CONN_INTENT_WRITABLE = 8
 Caller is requesting the primary DB server for possibly writes.
 
const CONN_REFRESH_READ_ONLY = 16
 Bypass and update any server-side read-only mode state cache.
 
const CONN_SILENCE_ERRORS = 4
 Yield null on connection failure instead of throwing an exception.
 
const CONN_TRX_AUTOCOMMIT = 2
 Yield a tracked autocommit-mode handle (reuse existing ones)
 
const CONN_UNTRACKED_GAUGE = 1
 Yield an untracked, low-timeout, autocommit-mode handle (to gauge server health)
 
const DB_MASTER = self::DB_PRIMARY
 Request a primary, write-enabled DB connection.
 
const DB_PRIMARY = -2
 Request a primary, write-enabled DB connection.
 
const DB_REPLICA = -1
 Request a replica DB connection.
 
const DOMAIN_ANY = ''
 Domain specifier when no specific database needs to be selected.
 
const GROUP_GENERIC = ''
 The generic query group.
 

Protected Member Functions

 configure (array $params)
 
 getConnLogContext (IDatabase $conn, array $extras=[])
 Create a log context to pass to PSR-3 logger functions.
 
 getExistingReaderIndex ( $group)
 Get the server index chosen for DB_REPLICA connections for the given query group.
 
 reallyOpenConnection ( $i, DatabaseDomain $domain, array $lbInfo)
 Open a new network connection to a server (uncached)
 
 resolveDomainInstance ( $domain)
 

Detailed Description

See also
ILoadBalancer

Definition at line 42 of file LoadBalancer.php.

Constructor & Destructor Documentation

◆ __construct()

Wikimedia\Rdbms\LoadBalancer::__construct ( array $params)
Parameters
array$paramsParameter map with keys:
  • servers : List of server configuration maps, starting with either the global master or local datacenter multi-master, and optionally followed by local datacenter replicas. Each server configuration map has the same format as the Database::factory() $params argument, with the following additional optional fields:
    • type: the DB type (sqlite, mysql, postgres,...)
    • groupLoads: map of (group => weight for this server) [optional]
    • max lag: per-server override of the "max lag" [optional]
    • is static: whether the dataset is static and this server has a copy [optional]
  • localDomain: A DatabaseDomain or domain ID string
  • loadMonitor : LoadMonitor::__construct() parameters with "class" field [optional]
  • readOnlyReason : Reason the primary server is read-only if so [optional]
  • srvCache : BagOStuff object for server cache [optional]
  • wanCache : WANObjectCache object [optional]
  • databaseFactory: DatabaseFactory object [optional]
  • chronologyCallback: Callback to run before the first connection attempt. It takes this ILoadBalancerForOwner instance and yields the relevant DBPrimaryPos for session (null if not applicable). [optional]
  • defaultGroup: Default query group; the generic group if not specified [optional]
  • hostname : The name of the current server [optional]
  • cliMode: Whether the execution context is a CLI script [optional]
  • profiler : Callback that takes a section name argument and returns a ScopedCallback instance that ends the profile section in its destructor [optional]
  • trxProfiler: TransactionProfiler instance [optional]
  • logger: PSR-3 logger instance [optional]
  • errorLogger : Callback that takes an Exception and logs it [optional]
  • deprecationLogger: Callback to log a deprecation warning [optional]
  • roundStage: STAGE_POSTCOMMIT_* class constant; for internal use [optional]
  • clusterName: The name of the overall (single/multi-datacenter) cluster of servers managing the dataset, regardless of 'servers' excluding replicas and multi-masters from remote datacenter [optional]
  • criticalSectionProvider: CriticalSectionProvider instance [optional]

Implements Wikimedia\Rdbms\ILoadBalancerForOwner.

Reimplemented in Wikimedia\Rdbms\LoadBalancerSingle.

Definition at line 177 of file LoadBalancer.php.

References Wikimedia\Rdbms\LoadBalancer\configure().

Member Function Documentation

◆ approvePrimaryChanges()

Wikimedia\Rdbms\LoadBalancer::approvePrimaryChanges ( int $maxWriteDuration,
$fname = __METHOD__ )

Perform all pre-commit checks for things like replication safety.

Use this only for multi-database commits

Parameters
int$maxWriteDuration: max write query duration time in seconds
string$fnameCaller name
Exceptions
DBTransactionError
Since
1.37

Implements Wikimedia\Rdbms\ILoadBalancerForOwner.

Definition at line 1505 of file LoadBalancer.php.

◆ beginPrimaryChanges()

Wikimedia\Rdbms\LoadBalancer::beginPrimaryChanges ( $fname = __METHOD__)

Flush any primary transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)

The DBO_TRX setting will be reverted to the default in each of these methods:

  • commitPrimaryChanges()
  • rollbackPrimaryChanges() This allows for custom transaction rounds from any outer transaction scope.
Parameters
string$fnameCaller name
Exceptions
DBExpectedError
Since
1.37

Implements Wikimedia\Rdbms\ILoadBalancerForOwner.

Definition at line 1559 of file LoadBalancer.php.

◆ closeAll()

Wikimedia\Rdbms\LoadBalancer::closeAll ( $fname = __METHOD__)

Close all open connections.

Parameters
string$fnameCaller name

Implements Wikimedia\Rdbms\ILoadBalancerForOwner.

Definition at line 1431 of file LoadBalancer.php.

◆ closeConnection()

Wikimedia\Rdbms\LoadBalancer::closeConnection ( IDatabase $conn)

Close a connection.

Using this function makes sure the LoadBalancer knows the connection is closed. If you use $conn->close() directly, the load balancer won't update its state.

Parameters
IDatabase$conn

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 1441 of file LoadBalancer.php.

References $type, Wikimedia\Rdbms\IReadableDatabase\close(), Wikimedia\Rdbms\IReadableDatabase\getDomainID(), and Wikimedia\Rdbms\IDatabase\getLBInfo().

◆ commitPrimaryChanges()

Wikimedia\Rdbms\LoadBalancer::commitPrimaryChanges ( $fname = __METHOD__)

Issue COMMIT on all open primary connections to flush changes and view snapshots.

Parameters
string$fnameCaller name
Exceptions
DBExpectedError
Since
1.37

Implements Wikimedia\Rdbms\ILoadBalancerForOwner.

Definition at line 1585 of file LoadBalancer.php.

◆ configure()

Wikimedia\Rdbms\LoadBalancer::configure ( array $params)
protected
Parameters
array$paramsA database configuration array, see $wgLBFactoryConf.
Returns
void

Definition at line 188 of file LoadBalancer.php.

Referenced by Wikimedia\Rdbms\LoadBalancer\__construct().

◆ disable()

Wikimedia\Rdbms\LoadBalancer::disable ( $fname = __METHOD__)

Close all connections and disable this load balancer.

Any attempt to open a new connection will result in a DBAccessError.

Parameters
string$fnameCaller name

Implements Wikimedia\Rdbms\ILoadBalancerForOwner.

Definition at line 1426 of file LoadBalancer.php.

◆ explicitTrxActive()

Wikimedia\Rdbms\LoadBalancer::explicitTrxActive ( )

Determine whether an explicit transaction is active on any open primary connection.

Returns
bool
Since
1.39

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 1853 of file LoadBalancer.php.

◆ finalizePrimaryChanges()

Wikimedia\Rdbms\LoadBalancer::finalizePrimaryChanges ( $fname = __METHOD__)

Run pre-commit callbacks and defer execution of post-commit callbacks.

Use this only for multi-database commits

Parameters
string$fnameCaller name
Returns
int Number of pre-commit callbacks run (since 1.32)
Since
1.37

Implements Wikimedia\Rdbms\ILoadBalancerForOwner.

Definition at line 1479 of file LoadBalancer.php.

◆ flushPrimarySessions()

Wikimedia\Rdbms\LoadBalancer::flushPrimarySessions ( $fname = __METHOD__)

Release/destroy session-level named locks, table locks, and temp tables.

Only call this function right after calling rollbackPrimaryChanges()

Parameters
string$fnameCaller name
Exceptions
DBExpectedError
Since
1.38

Implements Wikimedia\Rdbms\ILoadBalancerForOwner.

Definition at line 1727 of file LoadBalancer.php.

◆ flushPrimarySnapshots()

Wikimedia\Rdbms\LoadBalancer::flushPrimarySnapshots ( $fname = __METHOD__)

Commit all primary DB transactions so as to flush any REPEATABLE-READ or SSI snapshots.

An error will be thrown if a connection has pending writes or callbacks

Parameters
string$fnameCaller name
Since
1.37

Implements Wikimedia\Rdbms\ILoadBalancerForOwner.

Definition at line 1808 of file LoadBalancer.php.

◆ flushReplicaSnapshots()

Wikimedia\Rdbms\LoadBalancer::flushReplicaSnapshots ( $fname = __METHOD__)

Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshots.

Parameters
string$fnameCaller name

Implements Wikimedia\Rdbms\ILoadBalancerForOwner.

Definition at line 1802 of file LoadBalancer.php.

◆ getAnyOpenConnection()

Wikimedia\Rdbms\LoadBalancer::getAnyOpenConnection ( $i,
$flags = 0 )

Get an existing DB handle to the given server index (on any domain)

Use the CONN_TRX_AUTOCOMMIT flag to only look for connections opened with that flag.

Avoid the use of begin()/commit() and startAtomic()/endAtomic() on any handle returned. This method is intended for internal RDBMS callers that issue queries that do not affect any current transaction.

Access: internal
For use by Rdbms classes only
Parameters
int$iSpecific or virtual (DB_PRIMARY/DB_REPLICA) server index
int$flagsBitfield of CONN_* class constants
Returns
Database|false False if no such connection is open

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 672 of file LoadBalancer.php.

References $type, and DB_PRIMARY.

◆ getClusterName()

Wikimedia\Rdbms\LoadBalancer::getClusterName ( )

Get the name of the overall cluster of database servers managing the dataset.

Note that the cluster might contain servers in multiple datacenters. The load balancer instance only needs to be aware of the local replica servers, along with either the sole-primary server or the local co-primary server.

This is useful for identifying a cluster or replicated dataset, even when:

  • The primary server is sometimes swapped with another one
  • The cluster/dataset is replicated among multiple datacenters, with one "primary" datacenter having the writable primary server and the other datacenters having a read-only replica in the "primary" server slot
  • The dataset is replicated among multiple datacenters, via circular replication, with each datacenter having its own "co-primary" server
Returns
string
Since
1.36

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 255 of file LoadBalancer.php.

◆ getConnection()

Wikimedia\Rdbms\LoadBalancer::getConnection ( $i,
$groups = [],
$domain = false,
$flags = 0 )

Get a lazy-connecting database handle for a specific or virtual (DB_PRIMARY/DB_REPLICA) server index.

The server index, $i, can be one of the following:

  • DB_REPLICA: a server index will be selected by the load balancer based on read weight, connectivity, and replication lag. Note that the primary server might be configured with read weight. If $groups is empty then it means "the generic group", in which case all servers defined with read weight will be considered. Additional query groups can be configured, having their own list of server indexes and read weights. If a query group list is provided in $groups, then each recognized group will be tried, left-to-right, until server index selection succeeds or all groups have been tried, in which case the generic group will be tried.
  • DB_PRIMARY: the primary server index will be used; the same as getWriterIndex(). The value of $groups should be [] when using this server index.
  • Specific server index: a positive integer can be provided to use the server with that index. An error will be thrown in no such server index is recognized. This server selection method is usually only useful for internal load balancing logic. The value of $groups should be [] when using a specific server index.

Handle sharing is very useful when callers get DB_PRIMARY handles that are transaction round aware (the default). All such callers will operate within a single transaction as a consequence. The same applies to DB_REPLICA that are samely query grouped (the default) and transaction round aware (the default).

Use CONN_TRX_AUTOCOMMIT to use a separate pool of only autocommit handles. This flag is ignored for databases with ATTR_DB_LEVEL_LOCKING (e.g. sqlite) in order to avoid deadlocks. getServerAttributes() can be used to check this attribute beforehand. Avoid using begin() and commit() on such handles. If handle methods like startAtomic() and endAtomic() must be used on the handles, callers should at least make sure that the atomic sections are closed on failure via try/catch and cancelAtomic().

Use CONN_UNTRACKED_GAUGE to get a new, untracked, handle, that uses a low connection timeout, a low read timeout, and autocommit mode. This flag is intended for use only be internal callers.

CONN_UNTRACKED_GAUGE and CONN_TRX_AUTOCOMMIT are incompatible.

See also
ILoadBalancer::reuseConnection()
ILoadBalancer::getServerAttributes()
Parameters
int$iSpecific (overrides $groups) or virtual (DB_PRIMARY/DB_REPLICA) server index
string[] | string$groupsQuery group(s) in preference order; [] for the default group
string | false$domainDB domain ID or false for the local domain
int$flagsBitfield of CONN_* class constants
Returns
IDatabase|false This returns false on failure if CONN_SILENCE_ERRORS is set

Implements Wikimedia\Rdbms\ILoadBalancer.

Reimplemented in Wikimedia\Rdbms\LoadBalancerDisabled.

Definition at line 833 of file LoadBalancer.php.

◆ getConnectionInternal()

Wikimedia\Rdbms\LoadBalancer::getConnectionInternal ( $i,
$groups = [],
$domain = false,
$flags = 0 )
Access: internal
Only to be used by DBConnRef
Parameters
int$iSpecific (overrides $groups) or virtual (DB_PRIMARY/DB_REPLICA) server index
string[] | string$groupsQuery group(s) in preference order; [] for the default group
string | false$domainDB domain ID or false for the local domain
int$flagsBitfield of CONN_* class constants (e.g. CONN_TRX_AUTOCOMMIT)
Returns
IDatabase

Implements Wikimedia\Rdbms\ILoadBalancer.

Reimplemented in Wikimedia\Rdbms\LoadBalancerDisabled.

Definition at line 837 of file LoadBalancer.php.

◆ getConnectionRef()

Wikimedia\Rdbms\LoadBalancer::getConnectionRef ( $i,
$groups = [],
$domain = false,
$flags = 0 )
Deprecated
since 1.39, use ILoadBalancer::getConnection() instead.
Parameters
int$iSpecific or virtual (DB_PRIMARY/DB_REPLICA) server index
string[] | string$groupsQuery group(s) in preference order; [] for the default group
string | false$domainDB domain ID or false for the local domain
int$flagsBitfield of CONN_* class constants (e.g. CONN_TRX_AUTOCOMMIT)
Returns
DBConnRef

Implements Wikimedia\Rdbms\ILoadBalancer.

Reimplemented in Wikimedia\Rdbms\LoadBalancerDisabled.

Definition at line 921 of file LoadBalancer.php.

◆ getConnLogContext()

Wikimedia\Rdbms\LoadBalancer::getConnLogContext ( IDatabase $conn,
array $extras = [] )
protected

Create a log context to pass to PSR-3 logger functions.

Parameters
IDatabase$conn
array$extrasAdditional data to add to context
Returns
array

Definition at line 2165 of file LoadBalancer.php.

References Wikimedia\Rdbms\IReadableDatabase\getDomainID(), and Wikimedia\Rdbms\IReadableDatabase\getServerName().

◆ getExistingReaderIndex()

Wikimedia\Rdbms\LoadBalancer::getExistingReaderIndex ( $group)
protected

Get the server index chosen for DB_REPLICA connections for the given query group.

Parameters
string$groupQuery group; use false for the generic group
Returns
int Specific server index or LoadBalancer::READER_INDEX_NONE if none was chosen

Definition at line 527 of file LoadBalancer.php.

◆ getLagTimes()

Wikimedia\Rdbms\LoadBalancer::getLagTimes ( )

Get an estimate of replication lag (in seconds) for each server.

Results are cached for a short time in memcached/process cache

Values may be "false" if replication is too broken to estimate

Returns
float[]|int[]|false[] Map of (server index => lag) in order of server index

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 2034 of file LoadBalancer.php.

◆ getLocalDomainID()

Wikimedia\Rdbms\LoadBalancer::getLocalDomainID ( )

Get the local (and default) database domain ID of connection handles.

See also
DatabaseDomain
Returns
string Database domain ID; this specifies DB name, schema, and table prefix
Since
1.31

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 260 of file LoadBalancer.php.

◆ getMaintenanceConnectionRef()

Wikimedia\Rdbms\LoadBalancer::getMaintenanceConnectionRef ( $i,
$groups = [],
$domain = false,
$flags = 0 )

Get a DB handle, suitable for migrations and schema changes, for a server index.

The DBConnRef methods simply proxy an underlying IDatabase object which takes care of the actual connection and query logic.

The CONN_TRX_AUTOCOMMIT flag is ignored for databases with ATTR_DB_LEVEL_LOCKING (e.g. sqlite) in order to avoid deadlocks. getServerAttributes() can be used to check such flags beforehand. Avoid the use of begin() or startAtomic() on any CONN_TRX_AUTOCOMMIT connections.

See also
ILoadBalancer::getConnection() for parameter information
Parameters
int$iSpecific or virtual (DB_PRIMARY/DB_REPLICA) server index
string[] | string$groupsQuery group(s) in preference order; [] for the default group
string | false$domainDB domain ID or false for the local domain
int$flagsBitfield of CONN_* class constants (e.g. CONN_TRX_AUTOCOMMIT)
Returns
DBConnRef

Implements Wikimedia\Rdbms\ILoadBalancer.

Reimplemented in Wikimedia\Rdbms\LoadBalancerDisabled.

Definition at line 934 of file LoadBalancer.php.

◆ getMaxLag()

Wikimedia\Rdbms\LoadBalancer::getMaxLag ( )

Get the name and lag time of the most-lagged replica server.

This is useful for maintenance scripts that need to throttle their updates. May attempt to open connections to replica DBs on the default DB. If there is no lag, the maximum lag will be reported as -1.

Returns
array{0:string,1:float|int|false,2:int} (host, max lag, index of max lagged host)

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 2015 of file LoadBalancer.php.

◆ getPrimaryPos()

Wikimedia\Rdbms\LoadBalancer::getPrimaryPos ( )

Get the current primary replication position.

Returns
DBPrimaryPos|false Returns false if not applicable
Exceptions
DBError
Since
1.37

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 1314 of file LoadBalancer.php.

◆ getReaderIndex()

Wikimedia\Rdbms\LoadBalancer::getReaderIndex ( $group = false)

Get the specific server index of the reader connection for a given group.

This takes into account load ratios and lag times. It should return a consistent index during the life time of the load balancer. This initially checks replica DBs for connectivity to avoid returning an unusable server. This means that connections might be attempted by calling this method (usually one at the most but possibly more). Subsequent calls with the same $group will not need to make new connection attempts since the acquired connection for each group is preserved.

Parameters
string | false$groupQuery group or false for the generic group
Returns
int|false Specific server index, or false if no DB handle can be obtained

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 462 of file LoadBalancer.php.

◆ getReadOnlyReason()

Wikimedia\Rdbms\LoadBalancer::getReadOnlyReason ( $domain = false)
Note
This method may trigger a DB connection if not yet done
Parameters
string | false$domainDB domain ID or false (unused and deprecated since 1.40)
Returns
string|false Reason the primary is read-only or false if it is not

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 1871 of file LoadBalancer.php.

◆ getReplicaResumePos()

Wikimedia\Rdbms\LoadBalancer::getReplicaResumePos ( )

Get the highest DB replication position for chronology control purposes.

If there is only a primary server then this returns false. If replication is present and correctly configured, then this returns the highest replication position of any server with an open connection. That position can later be passed to waitFor() on a new load balancer instance to make sure that queries on the new connections see data at least as up-to-date as queries (prior to this method call) on the old connections.

This can be useful for implementing session consistency, where the session will be resumed across multiple HTTP requests or CLI script instances.

Access: internal
For use by Rdbms classes only
Returns
DBPrimaryPos|false Replication position or false if not applicable
Since
1.34

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 1333 of file LoadBalancer.php.

◆ getServerAttributes()

Wikimedia\Rdbms\LoadBalancer::getServerAttributes ( $i)

Get basic attributes of the server with the specified index without connecting.

Parameters
int$iSpecific server index
Returns
array (Database::ATTRIBUTE_* constant => value) for all such constants
Since
1.31

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 1063 of file LoadBalancer.php.

◆ getServerConnection()

Wikimedia\Rdbms\LoadBalancer::getServerConnection ( $i,
$domain,
$flags = 0 )

Get a DB handle for a specific server index.

This is an internal utility method for methods like LoadBalancer::getConnectionInternal() and DBConnRef to create the underlying connection to a concrete server.

The following is the responsibility of the caller:

  • translate any virtual server indexes (DB_PRIMARY/DB_REPLICA) to a real server index.
  • enforce read-only mode on primary DB handle if there is high replication lag.
See also
ILoadBalancer::getConnection()
Access: internal
Only for use within ILoadBalancer/ILoadMonitor
Parameters
int$iSpecific server index
string$domainResolved DB domain
int$flagsBitfield of class CONN_* constants
Returns
IDatabase|false This returns false on failure if CONN_SILENCE_ERRORS is set
Exceptions
DBErrorIf no DB handle could be obtained and CONN_SILENCE_ERRORS is not set

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 864 of file LoadBalancer.php.

◆ getServerCount()

Wikimedia\Rdbms\LoadBalancer::getServerCount ( )

Get the number of servers defined in configuration.

Returns
int

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 1290 of file LoadBalancer.php.

◆ getServerInfo()

Wikimedia\Rdbms\LoadBalancer::getServerInfo ( $i)

Return the server configuration map for the server with the specified index.

Parameters
int$iSpecific server index
Returns
array|false Server configuration map; false if the index is invalid
Since
1.31

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 1306 of file LoadBalancer.php.

◆ getServerName()

Wikimedia\Rdbms\LoadBalancer::getServerName ( $i)

Get the readable name of the server with the specified index.

Parameters
int$iSpecific server index
Returns
string Readable server name, falling back to the hostname or IP address

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 1302 of file LoadBalancer.php.

◆ getServerType()

Wikimedia\Rdbms\LoadBalancer::getServerType ( $i)

Get the RDBMS type of the server with the specified index (e.g.

"mysql", "sqlite")

Parameters
int$iSpecific server index
Returns
string One of (mysql,postgres,sqlite,...) or "unknown" for bad indexes
Since
1.30

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 1310 of file LoadBalancer.php.

◆ getWriterIndex()

Wikimedia\Rdbms\LoadBalancer::getWriterIndex ( )

Get the specific server index of the "writer server".

The "writer server" is the server that should be used to source writes and critical reads originating from the local datacenter. The "writer server" will be one of the following:

  • The primary, for single-primary setups (even if it resides in a remote datacenter)
  • The "preferred" co-primary relative to the local datacenter, for multi-primary setups
  • The "preferred" static clone, for static clone server setups (e.g. no replication)
Returns
int Specific server index

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 1286 of file LoadBalancer.php.

◆ hasOrMadeRecentPrimaryChanges()

Wikimedia\Rdbms\LoadBalancer::hasOrMadeRecentPrimaryChanges ( $age = null)

Check if this load balancer object had any recent or still pending writes issued against it by this PHP thread.

Parameters
float | null$ageHow many seconds ago is "recent" [defaults to mWaitTimeout]
Returns
bool
Since
1.37

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 1837 of file LoadBalancer.php.

◆ hasPrimaryChanges()

Wikimedia\Rdbms\LoadBalancer::hasPrimaryChanges ( )

Whether there are pending changes or callbacks in a transaction by this thread.

Returns
bool
Since
1.37

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 1818 of file LoadBalancer.php.

◆ hasPrimaryConnection()

Wikimedia\Rdbms\LoadBalancer::hasPrimaryConnection ( )
Returns
bool Whether a primary connection is already open
Since
1.37

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 1814 of file LoadBalancer.php.

◆ hasReplicaServers()

Wikimedia\Rdbms\LoadBalancer::hasReplicaServers ( )

Whether there are any replica servers configured.

This scans the list of servers defined in configuration, checking for:

  • Servers that are listed after the primary and not flagged with "is static"; such servers are assumed to be typical streaming replicas
  • Servers that are listed after the primary and flagged with "is static"; such servers are assumed to have a clone of the static dataset (matching the primary)
Returns
bool
Since
1.34

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 1294 of file LoadBalancer.php.

◆ hasStreamingReplicaServers()

Wikimedia\Rdbms\LoadBalancer::hasStreamingReplicaServers ( )

Whether any replica servers use streaming replication from the primary server.

This scans the list of servers defined in configuration, checking for:

  • Servers that are listed after the primary and not flagged with "is static"; such servers are assumed to be typical streaming replicas

It is possible for some replicas to be configured with "is static" but not others, though it generally should either be set for all or none of the replicas.

If this returns false, this means that there is generally no reason to execute replication wait logic for session consistency and lag reduction.

Returns
bool
Since
1.34

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 1298 of file LoadBalancer.php.

◆ laggedReplicaUsed()

Wikimedia\Rdbms\LoadBalancer::laggedReplicaUsed ( )

Whether a highly "lagged" replica database connection was queried.

Note
This method will never cause a new DB connection
Returns
bool

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 1867 of file LoadBalancer.php.

◆ lastPrimaryChangeTimestamp()

Wikimedia\Rdbms\LoadBalancer::lastPrimaryChangeTimestamp ( )

Get the timestamp of the latest write query done by this thread.

Returns
float|false UNIX timestamp or false
Since
1.37

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 1828 of file LoadBalancer.php.

◆ pendingPrimaryChangeCallers()

Wikimedia\Rdbms\LoadBalancer::pendingPrimaryChangeCallers ( )

Get the list of callers that have pending primary changes.

Returns
string[] List of method names
Since
1.37

Implements Wikimedia\Rdbms\ILoadBalancerForOwner.

Definition at line 1844 of file LoadBalancer.php.

◆ pingAll()

Wikimedia\Rdbms\LoadBalancer::pingAll ( )
Returns
bool

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 1960 of file LoadBalancer.php.

References $success.

◆ reallyOpenConnection()

Wikimedia\Rdbms\LoadBalancer::reallyOpenConnection ( $i,
DatabaseDomain $domain,
array $lbInfo )
protected

Open a new network connection to a server (uncached)

Returns a Database object whether or not the connection was successful.

Parameters
int$iSpecific server index
DatabaseDomain$domainDomain the connection is for, possibly unspecified
array$lbInfoAdditional information for setLBInfo()
Returns
Database
Exceptions
DBAccessError
InvalidArgumentException

Reimplemented in Wikimedia\Rdbms\LoadBalancerDisabled, and Wikimedia\Rdbms\LoadBalancerSingle.

Definition at line 1082 of file LoadBalancer.php.

References Wikimedia\Rdbms\DatabaseDomain\getDatabase(), Wikimedia\Rdbms\DatabaseDomain\getId(), Wikimedia\Rdbms\DatabaseDomain\getSchema(), and Wikimedia\Rdbms\DatabaseDomain\getTablePrefix().

◆ reconfigure()

Wikimedia\Rdbms\LoadBalancer::reconfigure ( array $params)

Apply updated configuration.

This only unregisters servers that were removed in the new configuration. It does not register new servers nor update the group load weights.

This invalidates any open connections. However, existing connections may continue to be used while they are in an active transaction. In that case, the old connection will be discarded on the first operation after the transaction is complete. The next operation will use a new connection based on the new configuration.

Access: internal
for use by LBFactory::reconfigure()
See also
DBConnRef::ensureConnection()
LBFactory::reconfigure()
Parameters
array$paramsA database configuration array, see $wgLBFactoryConf.
Returns
void

Implements Wikimedia\Rdbms\ILoadBalancerForOwner.

Definition at line 1378 of file LoadBalancer.php.

◆ redefineLocalDomain()

Wikimedia\Rdbms\LoadBalancer::redefineLocalDomain ( $domain)

Close all connection and redefine the local domain for testing or schema creation.

Parameters
DatabaseDomain | string$domain
Since
1.33

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 2124 of file LoadBalancer.php.

◆ resolveDomainID()

Wikimedia\Rdbms\LoadBalancer::resolveDomainID ( $domain)
Parameters
DatabaseDomain | string | false$domainDatabase domain
Returns
string Value of $domain if it is foreign or the local domain otherwise
Since
1.32

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 264 of file LoadBalancer.php.

◆ resolveDomainInstance()

Wikimedia\Rdbms\LoadBalancer::resolveDomainInstance ( $domain)
finalprotected
Parameters
DatabaseDomain | string | false$domain
Returns
DatabaseDomain

Definition at line 272 of file LoadBalancer.php.

◆ reuseConnection()

Wikimedia\Rdbms\LoadBalancer::reuseConnection ( IDatabase $conn)
Deprecated
since 1.39 noop
Parameters
IDatabase$conn

Implements Wikimedia\Rdbms\ILoadBalancer.

Reimplemented in Wikimedia\Rdbms\LoadBalancerDisabled, and Wikimedia\Rdbms\LoadBalancerSingle.

Definition at line 917 of file LoadBalancer.php.

◆ rollbackPrimaryChanges()

Wikimedia\Rdbms\LoadBalancer::rollbackPrimaryChanges ( $fname = __METHOD__)

Issue ROLLBACK only on primary, only if queries were done on connection.

Parameters
string$fnameCaller name
Exceptions
DBExpectedError
Since
1.37

Implements Wikimedia\Rdbms\ILoadBalancerForOwner.

Definition at line 1708 of file LoadBalancer.php.

◆ runPrimaryTransactionIdleCallbacks()

Wikimedia\Rdbms\LoadBalancer::runPrimaryTransactionIdleCallbacks ( $fname = __METHOD__)

Consume and run all pending post-COMMIT/ROLLBACK callbacks and commit dangling transactions.

Parameters
string$fnameCaller name
Returns
Exception|null The first exception or null if there were none
Since
1.37

Implements Wikimedia\Rdbms\ILoadBalancerForOwner.

Definition at line 1620 of file LoadBalancer.php.

References $type.

◆ runPrimaryTransactionListenerCallbacks()

Wikimedia\Rdbms\LoadBalancer::runPrimaryTransactionListenerCallbacks ( $fname = __METHOD__)

Run all recurring post-COMMIT/ROLLBACK listener callbacks.

Parameters
string$fnameCaller name
Returns
Exception|null The first exception or null if there were none
Since
1.37

Implements Wikimedia\Rdbms\ILoadBalancerForOwner.

Definition at line 1684 of file LoadBalancer.php.

References $type.

◆ setDomainAliases()

Wikimedia\Rdbms\LoadBalancer::setDomainAliases ( array $aliases)

Convert certain database domains to alternative ones.

This can be used for backwards compatibility logic.

Parameters
DatabaseDomain[] | string[]$aliasesMap of (domain alias => domain)
Since
1.35

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 2103 of file LoadBalancer.php.

◆ setIndexAliases()

Wikimedia\Rdbms\LoadBalancer::setIndexAliases ( array $aliases)

Convert certain index names to alternative names before querying the DB.

Note that this applies to indexes regardless of the table they belong to.

This can be employed when an index was renamed X => Y in code, but the new Y-named indexes were not yet built on all DBs. After all the Y-named ones are added by the DBA, the aliases can be removed, and then the old X-named indexes dropped.

Parameters
string[]$aliases
Since
1.31

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 2099 of file LoadBalancer.php.

◆ setLocalDomainPrefix()

Wikimedia\Rdbms\LoadBalancer::setLocalDomainPrefix ( $prefix)

Set a new table prefix for the existing local domain ID for testing.

Parameters
string$prefix
Since
1.33

Implements Wikimedia\Rdbms\ILoadBalancerForOwner.

Definition at line 2107 of file LoadBalancer.php.

◆ setTableAliases()

Wikimedia\Rdbms\LoadBalancer::setTableAliases ( array $aliases)

Make certain table names use their own database, schema, and table prefix when passed into SQL queries pre-escaped and without a qualified database name.

For example, "user" can be converted to "myschema.mydbname.user" for convenience. Appearances like user, somedb.user, somedb.someschema.user will used literally.

Calling this twice will completely clear any old table aliases. Also, note that callers are responsible for making sure the schemas and databases actually exist.

Parameters
array[]$aliasesMap of (table => (dbname, schema, prefix) map)

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 2095 of file LoadBalancer.php.

◆ setTempTablesOnlyMode()

Wikimedia\Rdbms\LoadBalancer::setTempTablesOnlyMode ( $value,
$domain )

Indicate whether the tables on this domain are only temporary tables for testing.

In "temporary tables mode", the CONN_TRX_AUTOCOMMIT flag is ignored

Parameters
bool$value
string$domain
Returns
bool Whether "temporary tables mode" was active
Since
1.34

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 2129 of file LoadBalancer.php.

◆ setTransactionListener()

Wikimedia\Rdbms\LoadBalancer::setTransactionListener ( $name,
callable $callback = null )

Set a callback via IDatabase::setTransactionListener() on all current and future primary connections of this load balancer.

Parameters
string$nameCallback name
callable | null$callback

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 2084 of file LoadBalancer.php.

◆ waitFor()

Wikimedia\Rdbms\LoadBalancer::waitFor ( DBPrimaryPos $pos)

Set the primary position to reach before the next generic group DB query.

If a generic replica DB connection is already open then this immediately waits for that DB to catch up to the specified replication position. Otherwise, it will do so once such a connection is opened.

If a timeout happens when waiting, then laggedReplicaUsed() will return true. This is useful for discouraging clients from taking further actions if session consistency could not be maintained with respect to their last actions.

Parameters
DBPrimaryPos$posPrimary position

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 600 of file LoadBalancer.php.

◆ waitForAll()

Wikimedia\Rdbms\LoadBalancer::waitForAll ( DBPrimaryPos $pos,
$timeout = null )

Set the primary wait position and wait for ALL replica DBs to catch up to it.

This method is only intended for use a throttling mechanism for high-volume updates. Unlike waitFor(), failure does not effect laggedReplicaUsed().

Parameters
DBPrimaryPos$posPrimary position
int | null$timeoutMax seconds to wait; default is mWaitTimeout
Returns
bool Success (able to connect and no timeouts reached)

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 621 of file LoadBalancer.php.

◆ waitForPrimaryPos()

Wikimedia\Rdbms\LoadBalancer::waitForPrimaryPos ( IDatabase $conn)

Wait for a replica DB to reach a specified primary position.

If $conn is not a replica server connection, then this will return true. Otherwise, if $pos is not provided, this will connect to the primary server to get an accurate position.

Parameters
IDatabase$connReplica DB
Returns
bool Success
Since
1.37

Implements Wikimedia\Rdbms\ILoadBalancer.

Definition at line 2042 of file LoadBalancer.php.

References Wikimedia\Rdbms\IDatabase\getLBInfo(), and Wikimedia\Rdbms\IReadableDatabase\primaryPosWait().

Member Data Documentation

◆ MAX_LAG_DEFAULT

const Wikimedia\Rdbms\LoadBalancer::MAX_LAG_DEFAULT = ServerInfo::MAX_LAG_DEFAULT

Default 'maxLag' when unspecified.

Access: internal
Only for use within LoadBalancer/LoadMonitor

Definition at line 144 of file LoadBalancer.php.

Referenced by Wikimedia\Rdbms\LoadMonitor\__construct().


The documentation for this class was generated from the following file: