MediaWiki  1.33.0
Wikimedia\Rdbms\ILBFactory Interface Reference

An interface for generating database load balancers. More...

Inheritance diagram for Wikimedia\Rdbms\ILBFactory:

Public Member Functions

 __construct (array $conf)
 Construct a manager of ILoadBalancer objects. More...
 
 appendShutdownCPIndexAsQuery ( $url, $index)
 Append ?cpPosIndex parameter to a URL for ChronologyProtector purposes if needed. More...
 
 beginMasterChanges ( $fname=__METHOD__)
 Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set) More...
 
 closeAll ()
 Close all open database connections on all open load balancers. More...
 
 commitAll ( $fname=__METHOD__, array $options=[])
 Commit open transactions on all connections. More...
 
 commitAndWaitForReplication ( $fname, $ticket, array $opts=[])
 Convenience method for safely running commitMasterChanges()/waitForReplication() More...
 
 commitMasterChanges ( $fname=__METHOD__, array $options=[])
 Commit changes and clear view snapshots on all master connections. More...
 
 destroy ()
 Disables all load balancers. More...
 
 disableChronologyProtection ()
 Disable the ChronologyProtector for all load balancers. More...
 
 flushReplicaSnapshots ( $fname=__METHOD__)
 Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot. More...
 
 forEachLB ( $callback, array $params=[])
 Execute a function for each tracked load balancer The callback is called with the load balancer as the first parameter, and $params passed as the subsequent parameters. More...
 
 getAllExternalLBs ()
 Get cached (tracked) load balancers for all external database clusters. More...
 
 getAllMainLBs ()
 Get cached (tracked) load balancers for all main database clusters. More...
 
 getChronologyProtectorTouched ( $dbName)
 
 getEmptyTransactionTicket ( $fname)
 Get a token asserting that no transaction writes are active. More...
 
 getExternalLB ( $cluster)
 Get a cached (tracked) load balancer for external storage. More...
 
 getLocalDomainID ()
 Get the local (and default) database domain ID of connection handles. More...
 
 getMainLB ( $domain=false)
 Get a cached (tracked) load balancer object. More...
 
 hasMasterChanges ()
 Determine if any master connection has pending changes. More...
 
 hasOrMadeRecentMasterChanges ( $age=null)
 Determine if any master connection has pending/written changes from this request. More...
 
 hasTransactionRound ()
 Check if an explicit transaction round is active. More...
 
 isReadyForRoundOperations ()
 Check if transaction rounds can be started, committed, or rolled back right now. More...
 
 laggedReplicaUsed ()
 Detemine if any lagged replica DB connection was used. More...
 
 newExternalLB ( $cluster)
 Create a new load balancer for external storage. More...
 
 newMainLB ( $domain=false)
 Create a new load balancer object. More...
 
 redefineLocalDomain ( $domain)
 Close all connection and redefine the local domain for testing or schema creation. More...
 
 resolveDomainID ( $domain)
 
 rollbackMasterChanges ( $fname=__METHOD__)
 Rollback changes on all master connections. More...
 
 setAgentName ( $agent)
 
 setIndexAliases (array $aliases)
 Convert certain index names to alternative names before querying the DB. More...
 
 setLocalDomainPrefix ( $prefix)
 Set a new table prefix for the existing local domain ID for testing. More...
 
 setRequestInfo (array $info)
 
 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. More...
 
 setWaitForReplicationListener ( $name, callable $callback=null)
 Add a callback to be run in every call to waitForReplication() before waiting. More...
 
 shutdown ( $mode=self::SHUTDOWN_CHRONPROT_SYNC, callable $workCallback=null, &$cpIndex=null, &$cpClientId=null)
 Prepare all tracked load balancers for shutdown. More...
 
 waitForReplication (array $opts=[])
 Waits for the replica DBs to catch up to the current master position. More...
 

Public Attributes

const SHUTDOWN_CHRONPROT_ASYNC = 1
 
const SHUTDOWN_CHRONPROT_SYNC = 2
 
const SHUTDOWN_NO_CHRONPROT = 0
 

Detailed Description

An interface for generating database load balancers.

Since
1.28

Definition at line 33 of file ILBFactory.php.

Constructor & Destructor Documentation

◆ __construct()

Wikimedia\Rdbms\ILBFactory::__construct ( array  $conf)

Construct a manager of ILoadBalancer objects.

Sub-classes will extend the required keys in $conf with additional parameters

Parameters
array$confArray with keys:
  • localDomain: A DatabaseDomain or domain ID string.
  • readOnlyReason: Reason the master DB is read-only if so [optional]
  • srvCache: BagOStuff object for server cache [optional]
  • memStash: BagOStuff object for cross-datacenter memory storage [optional]
  • wanCache: WANObjectCache object [optional]
  • hostname: The name of the current server [optional]
  • cliMode: Whether the execution context is a CLI script. [optional]
  • maxLag: Try to avoid DB replicas with lag above this many seconds [optional]
  • profiler: Class name or instance with profileIn()/profileOut() methods. [optional]
  • trxProfiler: TransactionProfiler instance. [optional]
  • replLogger: PSR-3 logger instance. [optional]
  • connLogger: PSR-3 logger instance. [optional]
  • queryLogger: PSR-3 logger instance. [optional]
  • perfLogger: PSR-3 logger instance. [optional]
  • errorLogger: Callback that takes an Exception and logs it. [optional]
  • deprecationLogger: Callback to log a deprecation warning. [optional]
Exceptions
InvalidArgumentException

Implemented in Wikimedia\Rdbms\LBFactoryMulti, Wikimedia\Rdbms\LBFactory, Wikimedia\Rdbms\LBFactorySimple, and Wikimedia\Rdbms\LBFactorySingle.

Member Function Documentation

◆ appendShutdownCPIndexAsQuery()

Wikimedia\Rdbms\ILBFactory::appendShutdownCPIndexAsQuery (   $url,
  $index 
)

Append ?cpPosIndex parameter to a URL for ChronologyProtector purposes if needed.

Note that unlike cookies, this works across domains

Parameters
string$url
int$indexWrite counter index
Returns
string

Implemented in Wikimedia\Rdbms\LBFactory.

◆ beginMasterChanges()

Wikimedia\Rdbms\ILBFactory::beginMasterChanges (   $fname = __METHOD__)

Flush any master 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:

This allows for custom transaction rounds from any outer transaction scope.

Parameters
string$fname
Exceptions
DBTransactionError

Implemented in Wikimedia\Rdbms\LBFactory.

◆ closeAll()

Wikimedia\Rdbms\ILBFactory::closeAll ( )

Close all open database connections on all open load balancers.

Implemented in Wikimedia\Rdbms\LBFactory.

◆ commitAll()

Wikimedia\Rdbms\ILBFactory::commitAll (   $fname = __METHOD__,
array  $options = [] 
)

Commit open transactions on all connections.

This is useful for two main cases:

  • a) To commit changes to the masters.
  • b) To release the snapshot on all connections, master and replica DBs.
    Parameters
    string$fnameCaller name
    array$optionsOptions map:
  • maxWriteDuration: abort if more than this much time was spent in write queries

Implemented in Wikimedia\Rdbms\LBFactory.

◆ commitAndWaitForReplication()

Wikimedia\Rdbms\ILBFactory::commitAndWaitForReplication (   $fname,
  $ticket,
array  $opts = [] 
)

Convenience method for safely running commitMasterChanges()/waitForReplication()

This will commit and wait unless $ticket indicates it is unsafe to do so

Parameters
string$fnameCaller name (e.g. METHOD)
mixed$ticketResult of getEmptyTransactionTicket()
array$optsOptions to waitForReplication()
Returns
bool True if the wait was successful, false on timeout

Implemented in Wikimedia\Rdbms\LBFactory.

◆ commitMasterChanges()

Wikimedia\Rdbms\ILBFactory::commitMasterChanges (   $fname = __METHOD__,
array  $options = [] 
)

Commit changes and clear view snapshots on all master connections.

Parameters
string$fnameCaller name
array$optionsOptions map:
  • maxWriteDuration: abort if more than this much time was spent in write queries
Exceptions
DBTransactionError

Implemented in Wikimedia\Rdbms\LBFactory.

◆ destroy()

Wikimedia\Rdbms\ILBFactory::destroy ( )

Disables all load balancers.

All connections are closed, and any attempt to open a new connection will result in a DBAccessError.

See also
ILoadBalancer::disable()

Implemented in Wikimedia\Rdbms\LBFactory.

◆ disableChronologyProtection()

Wikimedia\Rdbms\ILBFactory::disableChronologyProtection ( )

Disable the ChronologyProtector for all load balancers.

This can be called at the start of special API entry points

Implemented in Wikimedia\Rdbms\LBFactory.

◆ flushReplicaSnapshots()

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

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

Parameters
string$fnameCaller name

Implemented in Wikimedia\Rdbms\LBFactory.

◆ forEachLB()

◆ getAllExternalLBs()

Wikimedia\Rdbms\ILBFactory::getAllExternalLBs ( )

Get cached (tracked) load balancers for all external database clusters.

Returns
LoadBalancer[] Map of (cluster name => LoadBalancer)
Since
1.29

Implemented in Wikimedia\Rdbms\LBFactoryMulti, Wikimedia\Rdbms\LBFactorySimple, and Wikimedia\Rdbms\LBFactorySingle.

◆ getAllMainLBs()

Wikimedia\Rdbms\ILBFactory::getAllMainLBs ( )

Get cached (tracked) load balancers for all main database clusters.

Returns
LoadBalancer[] Map of (cluster name => LoadBalancer)
Since
1.29

Implemented in Wikimedia\Rdbms\LBFactoryMulti, Wikimedia\Rdbms\LBFactorySimple, and Wikimedia\Rdbms\LBFactorySingle.

◆ getChronologyProtectorTouched()

Wikimedia\Rdbms\ILBFactory::getChronologyProtectorTouched (   $dbName)
Parameters
string$dbNameDB master name (e.g. "db1052")
Returns
float|bool UNIX timestamp when client last touched the DB or false if not recent

Implemented in Wikimedia\Rdbms\LBFactory.

◆ getEmptyTransactionTicket()

Wikimedia\Rdbms\ILBFactory::getEmptyTransactionTicket (   $fname)

Get a token asserting that no transaction writes are active.

Parameters
string$fnameCaller name (e.g. METHOD)
Returns
mixed A value to pass to commitAndWaitForReplication()

Implemented in Wikimedia\Rdbms\LBFactory.

◆ getExternalLB()

Wikimedia\Rdbms\ILBFactory::getExternalLB (   $cluster)

Get a cached (tracked) load balancer for external storage.

Parameters
string$clusterExternal storage cluster name
Returns
ILoadBalancer

Implemented in Wikimedia\Rdbms\LBFactoryMulti, Wikimedia\Rdbms\LBFactory, Wikimedia\Rdbms\LBFactorySimple, and Wikimedia\Rdbms\LBFactorySingle.

◆ getLocalDomainID()

Wikimedia\Rdbms\ILBFactory::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.32

Implemented in Wikimedia\Rdbms\LBFactory.

◆ getMainLB()

Wikimedia\Rdbms\ILBFactory::getMainLB (   $domain = false)

Get a cached (tracked) load balancer object.

Parameters
bool | string$domainDomain ID, or false for the current domain
Returns
ILoadBalancer

Implemented in Wikimedia\Rdbms\LBFactoryMulti, Wikimedia\Rdbms\LBFactory, Wikimedia\Rdbms\LBFactorySimple, and Wikimedia\Rdbms\LBFactorySingle.

Referenced by WatchedItemStore\__construct().

◆ hasMasterChanges()

Wikimedia\Rdbms\ILBFactory::hasMasterChanges ( )

Determine if any master connection has pending changes.

Returns
bool

Implemented in Wikimedia\Rdbms\LBFactory.

◆ hasOrMadeRecentMasterChanges()

Wikimedia\Rdbms\ILBFactory::hasOrMadeRecentMasterChanges (   $age = null)

Determine if any master connection has pending/written changes from this request.

Parameters
float | null$ageHow many seconds ago is "recent" [defaults to LB lag wait timeout]
Returns
bool

Implemented in Wikimedia\Rdbms\LBFactory.

◆ hasTransactionRound()

Wikimedia\Rdbms\ILBFactory::hasTransactionRound ( )

Check if an explicit transaction round is active.

Returns
bool
Since
1.29

Implemented in Wikimedia\Rdbms\LBFactory.

◆ isReadyForRoundOperations()

Wikimedia\Rdbms\ILBFactory::isReadyForRoundOperations ( )

Check if transaction rounds can be started, committed, or rolled back right now.

This can be used as a recusion guard to avoid exceptions in transaction callbacks

Returns
bool
Since
1.32

Implemented in Wikimedia\Rdbms\LBFactory.

◆ laggedReplicaUsed()

Wikimedia\Rdbms\ILBFactory::laggedReplicaUsed ( )

Detemine if any lagged replica DB connection was used.

Returns
bool

Implemented in Wikimedia\Rdbms\LBFactory.

◆ newExternalLB()

Wikimedia\Rdbms\ILBFactory::newExternalLB (   $cluster)

Create a new load balancer for external storage.

The resulting object will be untracked, not chronology-protected, and the caller is responsible for cleaning it up.

This method is for only advanced usage and callers should almost always use getExternalLB() instead. This method can be useful when a table is used as a key/value store. In that cases, one might want to query it in autocommit mode (DBO_TRX off) but still use DBO_TRX transaction rounds on other tables.

Parameters
string$clusterExternal storage cluster name
Returns
ILoadBalancer

Implemented in Wikimedia\Rdbms\LBFactoryMulti, Wikimedia\Rdbms\LBFactory, Wikimedia\Rdbms\LBFactorySimple, and Wikimedia\Rdbms\LBFactorySingle.

◆ newMainLB()

Wikimedia\Rdbms\ILBFactory::newMainLB (   $domain = false)

Create a new load balancer object.

The resulting object will be untracked, not chronology-protected, and the caller is responsible for cleaning it up.

This method is for only advanced usage and callers should almost always use getMainLB() instead. This method can be useful when a table is used as a key/value store. In that cases, one might want to query it in autocommit mode (DBO_TRX off) but still use DBO_TRX transaction rounds on other tables.

Parameters
bool | string$domainDomain ID, or false for the current domain
Returns
ILoadBalancer

Implemented in Wikimedia\Rdbms\LBFactoryMulti, Wikimedia\Rdbms\LBFactory, Wikimedia\Rdbms\LBFactorySimple, and Wikimedia\Rdbms\LBFactorySingle.

◆ redefineLocalDomain()

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

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

Parameters
DatabaseDomain | string$domain
Since
1.33

Implemented in Wikimedia\Rdbms\LBFactory.

◆ resolveDomainID()

Wikimedia\Rdbms\ILBFactory::resolveDomainID (   $domain)
Parameters
DatabaseDomain | string | bool$domainDatabase domain
Returns
string Value of $domain if provided or the local domain otherwise
Since
1.32

Implemented in Wikimedia\Rdbms\LBFactory.

◆ rollbackMasterChanges()

Wikimedia\Rdbms\ILBFactory::rollbackMasterChanges (   $fname = __METHOD__)

Rollback changes on all master connections.

Parameters
string$fnameCaller name

Implemented in Wikimedia\Rdbms\LBFactory.

◆ setAgentName()

Wikimedia\Rdbms\ILBFactory::setAgentName (   $agent)
Parameters
string$agentAgent name for query profiling

Implemented in Wikimedia\Rdbms\LBFactory.

◆ setIndexAliases()

Wikimedia\Rdbms\ILBFactory::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

Implemented in Wikimedia\Rdbms\LBFactory.

◆ setLocalDomainPrefix()

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

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

Parameters
string$prefix
Since
1.33

Implemented in Wikimedia\Rdbms\LBFactory.

◆ setRequestInfo()

Wikimedia\Rdbms\ILBFactory::setRequestInfo ( array  $info)
Parameters
array$infoMap of fields, including:
  • IPAddress : IP address
  • UserAgent : User-Agent HTTP header
  • ChronologyProtection : cookie/header value specifying ChronologyProtector usage
  • ChronologyPositionIndex: timestamp used to get up-to-date DB positions for the agent

Implemented in Wikimedia\Rdbms\LBFactory.

◆ setTableAliases()

Wikimedia\Rdbms\ILBFactory::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)
Since
1.31

Implemented in Wikimedia\Rdbms\LBFactory.

◆ setWaitForReplicationListener()

Wikimedia\Rdbms\ILBFactory::setWaitForReplicationListener (   $name,
callable  $callback = null 
)

Add a callback to be run in every call to waitForReplication() before waiting.

Callbacks must clear any transactions that they start

Parameters
string$nameCallback name
callable | null$callbackUse null to unset a callback

Implemented in Wikimedia\Rdbms\LBFactory.

◆ shutdown()

Wikimedia\Rdbms\ILBFactory::shutdown (   $mode = self::SHUTDOWN_CHRONPROT_SYNC,
callable  $workCallback = null,
$cpIndex = null,
$cpClientId = null 
)

Prepare all tracked load balancers for shutdown.

Parameters
int$modeOne of the class SHUTDOWN_* constants
callable | null$workCallbackWork to mask ChronologyProtector writes
int | null&$cpIndexPosition key write counter for ChronologyProtector
string | null&$cpClientIdClient ID hash for ChronologyProtector

Implemented in Wikimedia\Rdbms\LBFactory.

◆ waitForReplication()

Wikimedia\Rdbms\ILBFactory::waitForReplication ( array  $opts = [])

Waits for the replica DBs to catch up to the current master position.

Use this when updating very large numbers of rows, as in maintenance scripts, to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.

By default this waits on all DB clusters actually used in this request. This makes sense when lag being waiting on is caused by the code that does this check. In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters that were not changed since the last wait check. To forcefully wait on a specific cluster for a given domain, use the 'domain' parameter. To forcefully wait on an "external" cluster, use the "cluster" parameter.

Never call this function after a large DB write that is still in a transaction. It only makes sense to call this after the possible lag inducing changes were committed.

Parameters
array$optsOptional fields that include:
  • domain : wait on the load balancer DBs that handles the given domain ID
  • cluster : wait on the given external load balancer DBs
  • timeout : Max wait time. Default: 60 seconds for CLI, 1 second for web.
  • ifWritesSince: Only wait if writes were done since this UNIX timestamp
Returns
bool True on success, false if a timeout or error occurred while waiting

Implemented in Wikimedia\Rdbms\LBFactory.

Referenced by RebuildRecentchanges\rebuildRecentChangesTablePass1(), RebuildRecentchanges\rebuildRecentChangesTablePass2(), RebuildRecentchanges\rebuildRecentChangesTablePass3(), RebuildRecentchanges\rebuildRecentChangesTablePass4(), and RebuildRecentchanges\rebuildRecentChangesTablePass5().

Member Data Documentation

◆ SHUTDOWN_CHRONPROT_ASYNC

const Wikimedia\Rdbms\ILBFactory::SHUTDOWN_CHRONPROT_ASYNC = 1

Definition at line 35 of file ILBFactory.php.

◆ SHUTDOWN_CHRONPROT_SYNC

const Wikimedia\Rdbms\ILBFactory::SHUTDOWN_CHRONPROT_SYNC = 2

Definition at line 36 of file ILBFactory.php.

◆ SHUTDOWN_NO_CHRONPROT

const Wikimedia\Rdbms\ILBFactory::SHUTDOWN_NO_CHRONPROT = 0

Definition at line 34 of file ILBFactory.php.

Referenced by MediaWiki\restInPeace().


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