MediaWiki  1.28.3
LoadBalancer Class Reference

Database connection, tracking, load balancing, and transaction manager for a cluster. More...

Inheritance diagram for LoadBalancer:
Collaboration diagram for LoadBalancer:

Public Member Functions

 __construct (array $params)
 Construct a manager of IDatabase connection objects. More...
 
 __destruct ()
 
 allowLagged ($mode=null)
 Disables/enables lag checks. More...
 
 approveMasterChanges (array $options)
 Perform all pre-commit checks for things like replication safety. More...
 
 beginMasterChanges ($fname=__METHOD__)
 Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set) More...
 
 closeAll ()
 Close all open connections. More...
 
 closeConnection (IDatabase $conn)
 Close a connection. More...
 
 commitAll ($fname=__METHOD__)
 Commit transactions on all open connections. More...
 
 commitMasterChanges ($fname=__METHOD__)
 Issue COMMIT on all master connections where writes where done. More...
 
 disable ()
 Disable this load balancer. More...
 
 finalizeMasterChanges ()
 Perform all pre-commit callbacks that remain part of the atomic transactions and disable any post-commit callbacks until runMasterPostTrxCallbacks() More...
 
 flushReplicaSnapshots ($fname=__METHOD__)
 Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot. More...
 
 forEachOpenConnection ($callback, array $params=[])
 Call a function with each open connection object. More...
 
 forEachOpenMasterConnection ($callback, array $params=[])
 Call a function with each open connection object to a master. More...
 
 forEachOpenReplicaConnection ($callback, array $params=[])
 Call a function with each open replica DB connection object. More...
 
 getAnyOpenConnection ($i)
 
 getConnection ($i, $groups=[], $domain=false)
 
 getConnectionRef ($db, $groups=[], $domain=false)
 Get a database connection handle reference. More...
 
 getLaggedReplicaMode ($domain=false)
 
 getLaggedSlaveMode ($domain=false)
 
 getLagTimes ($domain=false)
 Get an estimate of replication lag (in seconds) for each server. More...
 
 getLazyConnectionRef ($db, $groups=[], $domain=false)
 Get a database connection handle reference without connecting yet. More...
 
 getMasterPos ()
 Get the current master position for chronology control purposes. More...
 
 getMaxLag ($domain=false)
 Get the hostname and lag time of the most-lagged replica DB. More...
 
 getReaderIndex ($group=false, $domain=false)
 Get the index of the reader connection, which may be a replica DB This takes into account load ratios and lag times. More...
 
 getReadOnlyReason ($domain=false, IDatabase $conn=null)
 
 getServerCount ()
 Get the number of defined servers (not the number of open connections) More...
 
 getServerInfo ($i)
 Return the server info structure for a given index, or false if the index is invalid. More...
 
 getServerName ($i)
 Get the host name or IP address of the server with the specified index Prefer a readable name if available. More...
 
 getWriterIndex ()
 
 hasMasterChanges ()
 Determine if there are pending changes in a transaction by this thread. More...
 
 hasMasterConnection ()
 
 hasOrMadeRecentMasterChanges ($age=null)
 Check if this load balancer object had any recent or still pending writes issued against it by this PHP thread. More...
 
 haveIndex ($i)
 Returns true if the specified index is a valid server index. More...
 
 isNonZeroLoad ($i)
 Returns true if the specified index is valid and has non-zero load. More...
 
 laggedReplicaUsed ()
 
 laggedSlaveUsed ()
 
 lastMasterChangeTimestamp ()
 Get the timestamp of the latest write query done by this thread. More...
 
 openConnection ($i, $domain=false)
 
 pendingMasterChangeCallers ()
 Get the list of callers that have pending master changes. More...
 
 pingAll ()
 
 reuseConnection ($conn)
 Mark a foreign connection as being available for reuse under a different DB name or prefix. More...
 
 rollbackMasterChanges ($fname=__METHOD__)
 Issue ROLLBACK only on master, only if queries were done on connection. More...
 
 runMasterPostTrxCallbacks ($type)
 Issue all pending post-COMMIT/ROLLBACK callbacks. More...
 
 safeGetLag (IDatabase $conn)
 Get the lag in seconds for a given connection, or zero if this load balancer does not have replication enabled. More...
 
 safeWaitForMasterPos (IDatabase $conn, $pos=false, $timeout=10)
 
 setDomainPrefix ($prefix)
 Set a new table prefix for the existing local domain ID for testing. More...
 
 setServerInfo ($i, array $serverInfo)
 Sets the server info structure for the given index. More...
 
 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...
 
 setTransactionListener ($name, callable $callback=null)
 Set a callback via IDatabase::setTransactionListener() on all current and future master connections of this load balancer. More...
 
 suppressTransactionEndCallbacks ()
 Suppress all pending post-COMMIT/ROLLBACK callbacks. More...
 
 waitFor ($pos)
 
 waitForAll ($pos, $timeout=null)
 Set the master wait position and wait for ALL replica DBs to catch up to it. More...
 
 waitForOne ($pos, $timeout=null)
 Set the master wait position and wait for a "generic" replica DB to catch up to it. More...
 

Protected Member Functions

 doWait ($index, $open=false, $timeout=null)
 Wait for a given replica DB to catch up to the master pos stored in $this. More...
 
 getScopedPHPBehaviorForCommit ()
 Make PHP ignore user aborts/disconnects until the returned value leaves scope. More...
 
 reallyOpenConnection (array $server, $dbNameOverride=false)
 Really opens a connection. More...
 

Protected Attributes

string $agent
 Agent name for query profiling. More...
 
bool $cliMode
 Whether this PHP instance is for a CLI script. More...
 
LoggerInterface $connLogger
 
LoggerInterface $perfLogger
 
object string $profiler
 Class name or object With profileIn/profileOut methods. More...
 
LoggerInterface $queryLogger
 
LoggerInterface $replLogger
 
TransactionProfiler $trxProfiler
 

Private Member Functions

 applyTransactionRoundFlags (IDatabase $conn)
 
 getLoadMonitor ()
 Get a LoadMonitor instance. More...
 
 getRandomNonLagged (array $loads, $domain=false, $maxLag=INF)
 
 isOpen ($index)
 Test if the specified index represents an open connection. More...
 
 masterRunningReadOnly ($domain, IDatabase $conn=null)
 
 openForeignConnection ($i, $domain)
 Open a connection to a foreign DB, or return one if it is already open. More...
 
 reportConnectionError ()
 
 undoTransactionRoundFlags (IDatabase $conn)
 

Private Attributes

bool $allReplicasDownMode = false
 Whether the generic reader fell back to a lagged replica DB. More...
 
integer $connsOpened = 0
 Total connections opened. More...
 
boolean $disabled = false
 
callable $errorLogger
 Exception logger. More...
 
string $host
 Current server name. More...
 
bool $laggedReplicaMode = false
 Whether the generic reader fell back to a lagged replica DB. More...
 
ILoadMonitor $loadMonitor
 
array $loadMonitorConfig
 The LoadMonitor configuration. More...
 
DatabaseDomain $localDomain
 Local Domain ID and default for selectDB() calls. More...
 
string $localDomainIdAlias
 Alternate ID string for the domain instead of DatabaseDomain::getId() More...
 
bool $mAllowLagged
 Whether to disregard replica DB lag as a factor in replica DB selection. More...
 
IDatabase[][] $mConns
 Map of (local/foreignUsed/foreignFree => server index => IDatabase array) More...
 
BagOStuff $memCache
 
bool IDatabase $mErrorConnection
 Database connection that caused a problem. More...
 
array[] $mGroupLoads
 Map of (group => server index => weight) More...
 
string $mLastError = 'Unknown error'
 The last DB selection or connection error. More...
 
float[] $mLoads
 Map of (server index => weight) More...
 
integer $mReadIndex
 The generic (not query grouped) replica DB index (of $mServers) More...
 
array[] $mServers
 Map of (server index => server config array) More...
 
bool DBMasterPos $mWaitForPos
 False if not set. More...
 
integer $mWaitTimeout
 Seconds to spend waiting on replica DB lag to resolve. More...
 
string bool $readOnlyReason = false
 Reason the LB is read-only or false if not. More...
 
BagOStuff $srvCache
 
 $tableAliases = []
 
array[] $trxRecurringCallbacks = []
 Map of (name => callable) More...
 
string bool $trxRoundId = false
 String if a requested DBO_TRX transaction round is active. More...
 
WANObjectCache $wanCache
 

Detailed Description

Database connection, tracking, load balancing, and transaction manager for a cluster.

Definition at line 31 of file LoadBalancer.php.

Constructor & Destructor Documentation

LoadBalancer::__construct ( array  $params)

Construct a manager of IDatabase connection objects.

Parameters
array$paramsParameter map with keys:
  • servers : Required. Array of server info structures.
  • localDomain: A DatabaseDomain or domain ID string.
  • loadMonitor : Name of a class used to fetch server lag and load.
  • readOnlyReason : Reason the master DB is read-only if so [optional]
  • waitTimeout : Maximum time to wait for replicas for consistency [optional]
  • srvCache : BagOStuff object for server cache [optional]
  • memCache : BagOStuff object for cluster memory cache [optional]
  • wanCache : WANObjectCache object [optional]
  • hostname : The name of the current server [optional]
  • cliMode: Whether the execution context is a CLI script. [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]
Exceptions
InvalidArgumentException

Implements ILoadBalancer.

Definition at line 115 of file LoadBalancer.php.

References $e, as, WANObjectCache\newEmpty(), DatabaseDomain\newFromId(), and DatabaseDomain\newUnspecified().

LoadBalancer::__destruct ( )

Definition at line 1554 of file LoadBalancer.php.

References disable().

Member Function Documentation

LoadBalancer::allowLagged (   $mode = null)

Disables/enables lag checks.

Parameters
null | bool$mode
Returns
bool

Implements ILoadBalancer.

Definition at line 1352 of file LoadBalancer.php.

References $mAllowLagged.

LoadBalancer::applyTransactionRoundFlags ( IDatabase  $conn)
private
Parameters
IDatabase$conn

Definition at line 1201 of file LoadBalancer.php.

References DBO_DEFAULT, DBO_TRX, IDatabase\getFlag(), and IDatabase\setFlag().

Referenced by beginMasterChanges(), and reallyOpenConnection().

LoadBalancer::approveMasterChanges ( array  $options)

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

Use this only for mutli-database commits

Parameters
array$optionsIncludes:
  • maxWriteDuration : max write query duration time in seconds
Exceptions
DBTransactionError

Implements ILoadBalancer.

Definition at line 1045 of file LoadBalancer.php.

References $limit, $time, IDatabase\explicitTrxActive(), forEachOpenMasterConnection(), IDatabase\pendingWriteQueryDuration(), IDatabase\ping(), use, and IDatabase\writesOrCallbacksPending().

LoadBalancer::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:

Parameters
string$fname
Exceptions
DBExpectedError

Implements ILoadBalancer.

Definition at line 1078 of file LoadBalancer.php.

References $e, $fname, applyTransactionRoundFlags(), Database\flushSnapshot(), forEachOpenMasterConnection(), Database\setTrxEndCallbackSuppression(), and use.

LoadBalancer::closeAll ( )

Close all open connections.

Implements ILoadBalancer.

Definition at line 972 of file LoadBalancer.php.

References IDatabase\close(), forEachOpenConnection(), and IDatabase\getServer().

Referenced by disable().

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 ILoadBalancer.

Definition at line 987 of file LoadBalancer.php.

References $connsOpened, $type, as, IDatabase\close(), IDatabase\getLBInfo(), and getServerName().

Referenced by doWait(), and safeWaitForMasterPos().

LoadBalancer::commitAll (   $fname = __METHOD__)

Commit transactions on all open connections.

Parameters
string$fnameCaller name
Exceptions
DBExpectedError

Implements ILoadBalancer.

Definition at line 1008 of file LoadBalancer.php.

References $e, $fname, IDatabase\commit(), false, forEachOpenConnection(), IDatabase\getLBInfo(), undoTransactionRoundFlags(), and use.

LoadBalancer::commitMasterChanges (   $fname = __METHOD__)

Issue COMMIT on all master connections where writes where done.

Parameters
string$fnameCaller name
Exceptions
DBExpectedError

Implements ILoadBalancer.

Definition at line 1110 of file LoadBalancer.php.

References $e, $fname, IDatabase\commit(), false, IDatabase\flushSnapshot(), forEachOpenMasterConnection(), getScopedPHPBehaviorForCommit(), undoTransactionRoundFlags(), use, and IDatabase\writesOrCallbacksPending().

LoadBalancer::disable ( )

Disable this load balancer.

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

Implements ILoadBalancer.

Definition at line 967 of file LoadBalancer.php.

References closeAll().

Referenced by __destruct().

LoadBalancer::doWait (   $index,
  $open = false,
  $timeout = null 
)
protected

Wait for a given replica DB to catch up to the master pos stored in $this.

Parameters
int$indexServer index
bool$openCheck the server even if a new connection has to be made
int$timeoutMax seconds to wait; default is mWaitTimeout
Returns
bool

Definition at line 463 of file LoadBalancer.php.

References $mWaitTimeout, closeConnection(), getAnyOpenConnection(), getServerName(), openConnection(), and IExpiringStore\TTL_DAY.

Referenced by getReaderIndex(), waitFor(), waitForAll(), and waitForOne().

LoadBalancer::finalizeMasterChanges ( )

Perform all pre-commit callbacks that remain part of the atomic transactions and disable any post-commit callbacks until runMasterPostTrxCallbacks()

Use this only for mutli-database commits

Implements ILoadBalancer.

Definition at line 1035 of file LoadBalancer.php.

References forEachOpenMasterConnection(), Database\runOnTransactionPreCommitCallbacks(), and Database\setTrxEndCallbackSuppression().

LoadBalancer::flushReplicaSnapshots (   $fname = __METHOD__)

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

Parameters
string$fnameCaller name

Implements ILoadBalancer.

Definition at line 1221 of file LoadBalancer.php.

References IDatabase\flushSnapshot(), and forEachOpenReplicaConnection().

LoadBalancer::forEachOpenConnection (   $callback,
array  $params = [] 
)

Call a function with each open connection object.

Parameters
callable$callback
array$params

Implements ILoadBalancer.

Definition at line 1372 of file LoadBalancer.php.

References $params, and as.

Referenced by closeAll(), commitAll(), pingAll(), and setDomainPrefix().

LoadBalancer::forEachOpenMasterConnection (   $callback,
array  $params = [] 
)
LoadBalancer::forEachOpenReplicaConnection (   $callback,
array  $params = [] 
)

Call a function with each open replica DB connection object.

Parameters
callable$callback
array$params

Implements ILoadBalancer.

Definition at line 1396 of file LoadBalancer.php.

References $params, as, and getWriterIndex().

Referenced by flushReplicaSnapshots().

LoadBalancer::getAnyOpenConnection (   $i)
Parameters
int$i
Returns
IDatabase

Implements ILoadBalancer.

Definition at line 446 of file LoadBalancer.php.

References as.

Referenced by doWait(), getMasterPos(), isOpen(), and safeWaitForMasterPos().

LoadBalancer::getConnection (   $i,
  $groups = [],
  $domain = false 
)
LoadBalancer::getConnectionRef (   $db,
  $groups = [],
  $domain = false 
)

Get a database connection handle reference.

The handle's methods wrap simply wrap those of a IDatabase handle

See also
LoadBalancer::getConnection() for parameter information
Parameters
int$db
array | string | bool$groupsQuery group(s), or false for the generic reader
string | bool$domainDomain ID, or false for the current domain
Returns
DBConnRef

Implements ILoadBalancer.

Definition at line 648 of file LoadBalancer.php.

References false, and getConnection().

LoadBalancer::getLaggedReplicaMode (   $domain = false)
Note
This method will trigger a DB connection if not yet done
Parameters
string | bool$domainDomain ID, or false for the current domain
Returns
bool Whether the generic connection for reads is highly "lagged"

Implements ILoadBalancer.

Definition at line 1265 of file LoadBalancer.php.

References $e, $laggedReplicaMode, DB_REPLICA, getConnection(), getServerCount(), and reuseConnection().

Referenced by getLaggedSlaveMode(), and getReadOnlyReason().

LoadBalancer::getLaggedSlaveMode (   $domain = false)
Parameters
bool$domain
Returns
bool
Deprecated:
1.28; use getLaggedReplicaMode()

Definition at line 1287 of file LoadBalancer.php.

References getLaggedReplicaMode().

LoadBalancer::getLagTimes (   $domain = false)

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

Parameters
string | bool$domain
Returns
int[] Map of (server index => float|int|bool)

Implements ILoadBalancer.

Definition at line 1431 of file LoadBalancer.php.

References as, getLoadMonitor(), getServerCount(), and getWriterIndex().

Referenced by getMaxLag(), and getRandomNonLagged().

LoadBalancer::getLazyConnectionRef (   $db,
  $groups = [],
  $domain = false 
)

Get a database connection handle reference without connecting yet.

The handle's methods wrap simply wrap those of a IDatabase handle

See also
LoadBalancer::getConnection() for parameter information
Parameters
int$db
array | string | bool$groupsQuery group(s), or false for the generic reader
string | bool$domainDomain ID, or false for the current domain
Returns
DBConnRef

Implements ILoadBalancer.

Definition at line 654 of file LoadBalancer.php.

References false.

Referenced by reallyOpenConnection().

LoadBalancer::getLoadMonitor ( )
private

Get a LoadMonitor instance.

Returns
ILoadMonitor

Definition at line 212 of file LoadBalancer.php.

References $loadMonitor.

Referenced by getLagTimes(), and getReaderIndex().

LoadBalancer::getMasterPos ( )

Get the current master position for chronology control purposes.

Returns
DBMasterPos|bool Returns false if not applicable

Implements ILoadBalancer.

Definition at line 948 of file LoadBalancer.php.

References getAnyOpenConnection(), and getWriterIndex().

LoadBalancer::getMaxLag (   $domain = false)

Get the hostname and lag time of the most-lagged replica DB.

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.

Parameters
bool | string$domainDomain ID, or false for the default database
Returns
array ( host, max lag, index of max lagged host )

Implements ILoadBalancer.

Definition at line 1410 of file LoadBalancer.php.

References $host, as, getLagTimes(), and getServerCount().

LoadBalancer::getRandomNonLagged ( array  $loads,
  $domain = false,
  $maxLag = INF 
)
private
Parameters
array$loads
bool | string$domainDomain to get non-lagged for
int$maxLagRestrict the maximum allowed lag to this many seconds
Returns
bool|int|string

Definition at line 229 of file LoadBalancer.php.

References as, getLagTimes(), getServerName(), and ArrayUtils\pickRandom().

Referenced by getReaderIndex().

LoadBalancer::getReaderIndex (   $group = false,
  $domain = false 
)

Get the index of the reader connection, which may be a replica DB This takes into account load ratios and lag times.

It should always return a consistent index during a given invocation

Side effect: opens connections to databases

Parameters
string | bool$groupQuery group, or false for the generic reader
string | bool$domainDomain ID, or false for the current domain
Exceptions
DBError
Returns
bool|int|string

Implements ILoadBalancer.

Definition at line 274 of file LoadBalancer.php.

References $mLoads, $mReadIndex, doWait(), getLoadMonitor(), getRandomNonLagged(), getServerName(), getWriterIndex(), openConnection(), ArrayUtils\pickRandom(), and reuseConnection().

Referenced by getConnection().

LoadBalancer::getReadOnlyReason (   $domain = false,
IDatabase  $conn = null 
)
Note
This method may trigger a DB connection if not yet done
Parameters
string | bool$domainDomain ID, or false for the current domain
IDatabase|nullDB master connection; used to avoid loops [optional]
Returns
string|bool Reason the master is read-only or false if it is not

Implements ILoadBalancer.

Definition at line 1304 of file LoadBalancer.php.

References $readOnlyReason, getLaggedReplicaMode(), and masterRunningReadOnly().

Referenced by getConnection().

LoadBalancer::getScopedPHPBehaviorForCommit ( )
finalprotected

Make PHP ignore user aborts/disconnects until the returned value leaves scope.

This returns null and does nothing in CLI mode.

Returns
ScopedCallback|null

Definition at line 1543 of file LoadBalancer.php.

References use.

Referenced by commitMasterChanges().

LoadBalancer::getServerCount ( )

Get the number of defined servers (not the number of open connections)

Returns
int

Implements ILoadBalancer.

Definition at line 920 of file LoadBalancer.php.

Referenced by getLaggedReplicaMode(), getLagTimes(), getMaxLag(), safeGetLag(), and safeWaitForMasterPos().

LoadBalancer::getServerInfo (   $i)

Return the server info structure for a given index, or false if the index is invalid.

Parameters
int$i
Returns
array|bool

Implements ILoadBalancer.

Definition at line 936 of file LoadBalancer.php.

LoadBalancer::getServerName (   $i)

Get the host name or IP address of the server with the specified index Prefer a readable name if available.

Parameters
string$i
Returns
string

Implements ILoadBalancer.

Definition at line 924 of file LoadBalancer.php.

References $name.

Referenced by closeConnection(), doWait(), getRandomNonLagged(), getReaderIndex(), masterRunningReadOnly(), openConnection(), and reallyOpenConnection().

LoadBalancer::hasMasterChanges ( )

Determine if there are pending changes in a transaction by this thread.

Returns
bool

Implements ILoadBalancer.

Definition at line 1231 of file LoadBalancer.php.

References forEachOpenMasterConnection(), use, and IDatabase\writesOrCallbacksPending().

Referenced by hasOrMadeRecentMasterChanges().

LoadBalancer::hasMasterConnection ( )
Returns
bool Whether a master connection is already open

Implements ILoadBalancer.

Definition at line 1227 of file LoadBalancer.php.

References getWriterIndex(), and isOpen().

LoadBalancer::hasOrMadeRecentMasterChanges (   $age = null)

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

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

Implements ILoadBalancer.

Definition at line 1249 of file LoadBalancer.php.

References hasMasterChanges(), and lastMasterChangeTimestamp().

LoadBalancer::haveIndex (   $i)

Returns true if the specified index is a valid server index.

Parameters
string$i
Returns
bool

Implements ILoadBalancer.

Definition at line 912 of file LoadBalancer.php.

LoadBalancer::isNonZeroLoad (   $i)

Returns true if the specified index is valid and has non-zero load.

Parameters
string$i
Returns
bool

Implements ILoadBalancer.

Definition at line 916 of file LoadBalancer.php.

LoadBalancer::isOpen (   $index)
private

Test if the specified index represents an open connection.

Parameters
int$indexServer index private
Returns
bool

Definition at line 798 of file LoadBalancer.php.

References getAnyOpenConnection().

Referenced by hasMasterConnection().

LoadBalancer::laggedReplicaUsed ( )
Note
This method will never cause a new DB connection
Returns
bool Whether any generic connection used for reads was highly "lagged"

Implements ILoadBalancer.

Definition at line 1291 of file LoadBalancer.php.

References $laggedReplicaMode.

Referenced by laggedSlaveUsed().

LoadBalancer::laggedSlaveUsed ( )
Returns
bool
Since
1.27
Deprecated:
Since 1.28; use laggedReplicaUsed()

Definition at line 1300 of file LoadBalancer.php.

References laggedReplicaUsed().

LoadBalancer::lastMasterChangeTimestamp ( )

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

Returns
float|bool UNIX timestamp or false

Implements ILoadBalancer.

Definition at line 1240 of file LoadBalancer.php.

References forEachOpenMasterConnection(), IDatabase\lastDoneWrites(), and use.

Referenced by hasOrMadeRecentMasterChanges().

LoadBalancer::masterRunningReadOnly (   $domain,
IDatabase  $conn = null 
)
private
Parameters
string$domainDomain ID, or false for the current domain
IDatabase|nullDB master connectionl used to avoid loops [optional]
Returns
bool

Definition at line 1327 of file LoadBalancer.php.

References $cache, $e, $wanCache, DB_MASTER, getConnection(), getServerName(), getWriterIndex(), reuseConnection(), and use.

Referenced by getReadOnlyReason().

LoadBalancer::openConnection (   $i,
  $domain = false 
)
See also
ILoadBalancer::openConnection()
Parameters
int$i
bool$domain
Returns
bool|Database
Exceptions
DBAccessError

Implements ILoadBalancer.

Definition at line 668 of file LoadBalancer.php.

References $localDomainIdAlias, getServerName(), openForeignConnection(), and reallyOpenConnection().

Referenced by doWait(), getConnection(), getReaderIndex(), and safeWaitForMasterPos().

LoadBalancer::openForeignConnection (   $i,
  $domain 
)
private

Open a connection to a foreign DB, or return one if it is already open.

Increments a reference count on the returned connection which locks the connection to the requested domain. This reference count can be decremented by calling reuseConnection().

If a connection is open to the appropriate server already, but with the wrong database, it will be switched to the right database and returned, as long as it has been freed first with reuseConnection().

On error, returns false, and the connection which caused the error will be available via $this->mErrorConnection.

Note
If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
Parameters
int$iServer index
string$domainDomain ID to open
Returns
Database

Definition at line 728 of file LoadBalancer.php.

References key, DatabaseDomain\newFromId(), and reallyOpenConnection().

Referenced by openConnection().

LoadBalancer::pendingMasterChangeCallers ( )

Get the list of callers that have pending master changes.

Returns
string[] List of method names

Implements ILoadBalancer.

Definition at line 1256 of file LoadBalancer.php.

References forEachOpenMasterConnection(), IDatabase\pendingWriteCallers(), and use.

LoadBalancer::pingAll ( )
Returns
bool

Implements ILoadBalancer.

Definition at line 1361 of file LoadBalancer.php.

References $success, forEachOpenConnection(), IDatabase\ping(), and use.

LoadBalancer::reallyOpenConnection ( array  $server,
  $dbNameOverride = false 
)
protected

Really opens a connection.

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

Parameters
array$server
string | bool$dbNameOverrideUse "" to not select any database
Returns
Database
Exceptions
DBAccessError
InvalidArgumentException

Definition at line 817 of file LoadBalancer.php.

References $agent, $cliMode, $connLogger, $e, $errorLogger, $name, $profiler, $queryLogger, $srvCache, $trxProfiler, applyTransactionRoundFlags(), as, DB_MASTER, DBO_DEFAULT, Database\factory(), getLazyConnectionRef(), getServerName(), and getWriterIndex().

Referenced by openConnection(), and openForeignConnection().

LoadBalancer::reportConnectionError ( )
private
Exceptions
DBConnectionError

Definition at line 880 of file LoadBalancer.php.

References $context, $mErrorConnection, and $mLastError.

Referenced by getConnection().

LoadBalancer::reuseConnection (   $conn)

Mark a foreign connection as being available for reuse under a different DB name or prefix.

This mechanism is reference-counted, and must be called the same number of times as getConnection() to work.

Parameters
IDatabase$conn
Exceptions
InvalidArgumentException

Implements ILoadBalancer.

Definition at line 598 of file LoadBalancer.php.

Referenced by getLaggedReplicaMode(), getReaderIndex(), and masterRunningReadOnly().

LoadBalancer::rollbackMasterChanges (   $fname = __METHOD__)

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

Parameters
string$fnameCaller name
Exceptions
DBExpectedError

Implements ILoadBalancer.

Definition at line 1177 of file LoadBalancer.php.

References $fname, false, forEachOpenMasterConnection(), IDatabase\rollback(), undoTransactionRoundFlags(), use, and IDatabase\writesOrCallbacksPending().

LoadBalancer::runMasterPostTrxCallbacks (   $type)

Issue all pending post-COMMIT/ROLLBACK callbacks.

Use this only for mutli-database commits

Parameters
integer$typeIDatabase::TRIGGER_* constant
Returns
Exception|null The first exception or null if there were none

Implements ILoadBalancer.

Definition at line 1144 of file LoadBalancer.php.

References $e, $type, forEachOpenMasterConnection(), Database\runOnTransactionIdleCallbacks(), Database\runTransactionListenerCallbacks(), Database\setTrxEndCallbackSuppression(), Database\trxLevel(), use, and Database\writesOrCallbacksPending().

LoadBalancer::safeGetLag ( IDatabase  $conn)

Get the lag in seconds for a given connection, or zero if this load balancer does not have replication enabled.

This should be used in preference to Database::getLag() in cases where replication may not be in use, since there is no way to determine if replication is in use at the connection level without running potentially restricted queries such as SHOW SLAVE STATUS. Using this function instead of Database::getLag() avoids a fatal error in this case on many installations.

Parameters
IDatabase$conn
Returns
int|bool Returns false on error

Implements ILoadBalancer.

Definition at line 1449 of file LoadBalancer.php.

References IDatabase\getLag(), and getServerCount().

LoadBalancer::safeWaitForMasterPos ( IDatabase  $conn,
  $pos = false,
  $timeout = 10 
)
LoadBalancer::setDomainPrefix (   $prefix)

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

Parameters
string$prefix

Implements ILoadBalancer.

Definition at line 1514 of file LoadBalancer.php.

References as, forEachOpenConnection(), IDatabase\tablePrefix(), and use.

LoadBalancer::setServerInfo (   $i,
array  $serverInfo 
)

Sets the server info structure for the given index.

Entry at index $i is created if it doesn't exist

Parameters
int$i
array$serverInfo

Implements ILoadBalancer.

Definition at line 944 of file LoadBalancer.php.

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[]$aliases Map of (table => (dbname, schema, prefix) map)

Implements ILoadBalancer.

Definition at line 1510 of file LoadBalancer.php.

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

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

Parameters
string$nameCallback name
callable | null$callback

Implements ILoadBalancer.

Definition at line 1497 of file LoadBalancer.php.

References $name, forEachOpenMasterConnection(), IDatabase\setTransactionListener(), and use.

LoadBalancer::suppressTransactionEndCallbacks ( )

Suppress all pending post-COMMIT/ROLLBACK callbacks.

Use this only for mutli-database commits

Returns
Exception|null The first exception or null if there were none

Implements ILoadBalancer.

Definition at line 1192 of file LoadBalancer.php.

References forEachOpenMasterConnection(), and Database\setTrxEndCallbackSuppression().

LoadBalancer::undoTransactionRoundFlags ( IDatabase  $conn)
private
Parameters
IDatabase$conn

Definition at line 1215 of file LoadBalancer.php.

References DBO_DEFAULT, IDatabase\getFlag(), and IDatabase\restoreFlags().

Referenced by commitAll(), commitMasterChanges(), and rollbackMasterChanges().

LoadBalancer::waitFor (   $pos)
Parameters
DBMasterPos | false$pos

Implements ILoadBalancer.

Definition at line 396 of file LoadBalancer.php.

References $mReadIndex, and doWait().

LoadBalancer::waitForAll (   $pos,
  $timeout = null 
)

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

Parameters
DBMasterPos$pos
int$timeoutMax seconds to wait; default is mWaitTimeout
Returns
bool Success (able to connect and no timeouts reached)

Implements ILoadBalancer.

Definition at line 428 of file LoadBalancer.php.

References doWait().

LoadBalancer::waitForOne (   $pos,
  $timeout = null 
)

Set the master wait position and wait for a "generic" replica DB to catch up to it.

This can be used a faster proxy for waitForAll()

Parameters
DBMasterPos$pos
int$timeoutMax seconds to wait; default is mWaitTimeout
Returns
bool Success (able to connect and no timeouts reached)

Implements ILoadBalancer.

Definition at line 407 of file LoadBalancer.php.

References $mLoads, $mReadIndex, doWait(), getWriterIndex(), and ArrayUtils\pickRandom().

Member Data Documentation

string LoadBalancer::$agent
protected

Agent name for query profiling.

Definition at line 99 of file LoadBalancer.php.

Referenced by reallyOpenConnection().

bool LoadBalancer::$allReplicasDownMode = false
private

Whether the generic reader fell back to a lagged replica DB.

Definition at line 79 of file LoadBalancer.php.

bool LoadBalancer::$cliMode
protected

Whether this PHP instance is for a CLI script.

Definition at line 97 of file LoadBalancer.php.

Referenced by reallyOpenConnection().

LoggerInterface LoadBalancer::$connLogger
protected

Definition at line 64 of file LoadBalancer.php.

Referenced by reallyOpenConnection().

integer LoadBalancer::$connsOpened = 0
private

Total connections opened.

Definition at line 85 of file LoadBalancer.php.

Referenced by closeConnection(), and getConnection().

boolean LoadBalancer::$disabled = false
private

Definition at line 105 of file LoadBalancer.php.

callable LoadBalancer::$errorLogger
private

Exception logger.

Definition at line 102 of file LoadBalancer.php.

Referenced by reallyOpenConnection().

string LoadBalancer::$host
private

Current server name.

Definition at line 95 of file LoadBalancer.php.

Referenced by getMaxLag().

bool LoadBalancer::$laggedReplicaMode = false
private

Whether the generic reader fell back to a lagged replica DB.

Definition at line 77 of file LoadBalancer.php.

Referenced by getLaggedReplicaMode(), and laggedReplicaUsed().

ILoadMonitor LoadBalancer::$loadMonitor
private

Definition at line 50 of file LoadBalancer.php.

Referenced by getLoadMonitor().

array LoadBalancer::$loadMonitorConfig
private

The LoadMonitor configuration.

Definition at line 45 of file LoadBalancer.php.

DatabaseDomain LoadBalancer::$localDomain
private

Local Domain ID and default for selectDB() calls.

Definition at line 91 of file LoadBalancer.php.

string LoadBalancer::$localDomainIdAlias
private

Alternate ID string for the domain instead of DatabaseDomain::getId()

Definition at line 93 of file LoadBalancer.php.

Referenced by getConnection(), and openConnection().

bool LoadBalancer::$mAllowLagged
private

Whether to disregard replica DB lag as a factor in replica DB selection.

Definition at line 41 of file LoadBalancer.php.

Referenced by allowLagged().

IDatabase [][] LoadBalancer::$mConns
private

Map of (local/foreignUsed/foreignFree => server index => IDatabase array)

Definition at line 35 of file LoadBalancer.php.

BagOStuff LoadBalancer::$memCache
private

Definition at line 54 of file LoadBalancer.php.

bool IDatabase LoadBalancer::$mErrorConnection
private

Database connection that caused a problem.

Definition at line 71 of file LoadBalancer.php.

Referenced by reportConnectionError().

array [] LoadBalancer::$mGroupLoads
private

Map of (group => server index => weight)

Definition at line 39 of file LoadBalancer.php.

string LoadBalancer::$mLastError = 'Unknown error'
private

The last DB selection or connection error.

Definition at line 81 of file LoadBalancer.php.

Referenced by getConnection(), and reportConnectionError().

float [] LoadBalancer::$mLoads
private

Map of (server index => weight)

Definition at line 37 of file LoadBalancer.php.

Referenced by getReaderIndex(), and waitForOne().

integer LoadBalancer::$mReadIndex
private

The generic (not query grouped) replica DB index (of $mServers)

Definition at line 73 of file LoadBalancer.php.

Referenced by getReaderIndex(), waitFor(), and waitForOne().

array [] LoadBalancer::$mServers
private

Map of (server index => server config array)

Definition at line 33 of file LoadBalancer.php.

bool DBMasterPos LoadBalancer::$mWaitForPos
private

False if not set.

Definition at line 75 of file LoadBalancer.php.

integer LoadBalancer::$mWaitTimeout
private

Seconds to spend waiting on replica DB lag to resolve.

Definition at line 43 of file LoadBalancer.php.

Referenced by doWait().

LoggerInterface LoadBalancer::$perfLogger
protected

Definition at line 68 of file LoadBalancer.php.

object string LoadBalancer::$profiler
protected

Class name or object With profileIn/profileOut methods.

Definition at line 58 of file LoadBalancer.php.

Referenced by reallyOpenConnection().

LoggerInterface LoadBalancer::$queryLogger
protected

Definition at line 66 of file LoadBalancer.php.

Referenced by reallyOpenConnection().

string bool LoadBalancer::$readOnlyReason = false
private

Reason the LB is read-only or false if not.

Definition at line 83 of file LoadBalancer.php.

Referenced by getReadOnlyReason().

LoggerInterface LoadBalancer::$replLogger
protected

Definition at line 62 of file LoadBalancer.php.

BagOStuff LoadBalancer::$srvCache
private

Definition at line 52 of file LoadBalancer.php.

Referenced by reallyOpenConnection().

LoadBalancer::$tableAliases = []
private

Definition at line 47 of file LoadBalancer.php.

TransactionProfiler LoadBalancer::$trxProfiler
protected

Definition at line 60 of file LoadBalancer.php.

Referenced by reallyOpenConnection().

array [] LoadBalancer::$trxRecurringCallbacks = []
private

Map of (name => callable)

Definition at line 89 of file LoadBalancer.php.

string bool LoadBalancer::$trxRoundId = false
private

String if a requested DBO_TRX transaction round is active.

Definition at line 87 of file LoadBalancer.php.

WANObjectCache LoadBalancer::$wanCache
private

Definition at line 56 of file LoadBalancer.php.

Referenced by masterRunningReadOnly().


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