3 * Generator and manager of database load balancing objects
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * An interface for generating database load balancers
29 interface ILBFactory
{
30 const SHUTDOWN_NO_CHRONPROT
= 0; // don't save DB positions at all
31 const SHUTDOWN_CHRONPROT_ASYNC
= 1; // save DB positions, but don't wait on remote DCs
32 const SHUTDOWN_CHRONPROT_SYNC
= 2; // save DB positions, waiting on all DCs
35 * Construct a manager of ILoadBalancer objects
37 * Sub-classes will extend the required keys in $conf with additional parameters
39 * @param $conf $params Array with keys:
40 * - localDomain: A DatabaseDomain or domain ID string.
41 * - readOnlyReason : Reason the master DB is read-only if so [optional]
42 * - srvCache : BagOStuff object for server cache [optional]
43 * - memCache : BagOStuff object for cluster memory cache [optional]
44 * - wanCache : WANObjectCache object [optional]
45 * - hostname : The name of the current server [optional]
46 * - cliMode: Whether the execution context is a CLI script. [optional]
47 * - profiler : Class name or instance with profileIn()/profileOut() methods. [optional]
48 * - trxProfiler: TransactionProfiler instance. [optional]
49 * - replLogger: PSR-3 logger instance. [optional]
50 * - connLogger: PSR-3 logger instance. [optional]
51 * - queryLogger: PSR-3 logger instance. [optional]
52 * - perfLogger: PSR-3 logger instance. [optional]
53 * - errorLogger : Callback that takes an Exception and logs it. [optional]
54 * @throws InvalidArgumentException
56 public function __construct( array $conf );
59 * Disables all load balancers. All connections are closed, and any attempt to
60 * open a new connection will result in a DBAccessError.
61 * @see ILoadBalancer::disable()
63 public function destroy();
66 * Create a new load balancer object. The resulting object will be untracked,
67 * not chronology-protected, and the caller is responsible for cleaning it up.
69 * This method is for only advanced usage and callers should almost always use
70 * getMainLB() instead. This method can be useful when a table is used as a key/value
71 * store. In that cases, one might want to query it in autocommit mode (DBO_TRX off)
72 * but still use DBO_TRX transaction rounds on other tables.
74 * @param bool|string $domain Domain ID, or false for the current domain
75 * @return ILoadBalancer
77 public function newMainLB( $domain = false );
80 * Get a cached (tracked) load balancer object.
82 * @param bool|string $domain Domain ID, or false for the current domain
83 * @return ILoadBalancer
85 public function getMainLB( $domain = false );
88 * Create a new load balancer for external storage. The resulting object will be
89 * untracked, not chronology-protected, and the caller is responsible for
92 * This method is for only advanced usage and callers should almost always use
93 * getExternalLB() instead. This method can be useful when a table is used as a
94 * key/value store. In that cases, one might want to query it in autocommit mode
95 * (DBO_TRX off) but still use DBO_TRX transaction rounds on other tables.
97 * @param string $cluster External storage cluster, or false for core
98 * @param bool|string $domain Domain ID, or false for the current domain
99 * @return ILoadBalancer
101 public function newExternalLB( $cluster, $domain = false );
104 * Get a cached (tracked) load balancer for external storage
106 * @param string $cluster External storage cluster, or false for core
107 * @param bool|string $domain Domain ID, or false for the current domain
108 * @return ILoadBalancer
110 public function getExternalLB( $cluster, $domain = false );
113 * Execute a function for each tracked load balancer
114 * The callback is called with the load balancer as the first parameter,
115 * and $params passed as the subsequent parameters.
117 * @param callable $callback
118 * @param array $params
120 public function forEachLB( $callback, array $params = [] );
123 * Prepare all tracked load balancers for shutdown
124 * @param integer $mode One of the class SHUTDOWN_* constants
125 * @param callable|null $workCallback Work to mask ChronologyProtector writes
127 public function shutdown(
128 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
, callable
$workCallback = null
132 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
134 * @param string $fname Caller name
136 public function flushReplicaSnapshots( $fname = __METHOD__
);
139 * Commit on all connections. Done for two reasons:
140 * 1. To commit changes to the masters.
141 * 2. To release the snapshot on all connections, master and replica DB.
142 * @param string $fname Caller name
143 * @param array $options Options map:
144 * - maxWriteDuration: abort if more than this much time was spent in write queries
146 public function commitAll( $fname = __METHOD__
, array $options = [] );
149 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
151 * The DBO_TRX setting will be reverted to the default in each of these methods:
152 * - commitMasterChanges()
153 * - rollbackMasterChanges()
156 * This allows for custom transaction rounds from any outer transaction scope.
158 * @param string $fname
159 * @throws DBTransactionError
161 public function beginMasterChanges( $fname = __METHOD__
);
164 * Commit changes on all master connections
165 * @param string $fname Caller name
166 * @param array $options Options map:
167 * - maxWriteDuration: abort if more than this much time was spent in write queries
170 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] );
173 * Rollback changes on all master connections
174 * @param string $fname Caller name
176 public function rollbackMasterChanges( $fname = __METHOD__
);
179 * Determine if any master connection has pending changes
182 public function hasMasterChanges();
185 * Detemine if any lagged replica DB connection was used
188 public function laggedReplicaUsed();
191 * Determine if any master connection has pending/written changes from this request
192 * @param float $age How many seconds ago is "recent" [defaults to LB lag wait timeout]
195 public function hasOrMadeRecentMasterChanges( $age = null );
198 * Waits for the replica DBs to catch up to the current master position
200 * Use this when updating very large numbers of rows, as in maintenance scripts,
201 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
203 * By default this waits on all DB clusters actually used in this request.
204 * This makes sense when lag being waiting on is caused by the code that does this check.
205 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
206 * that were not changed since the last wait check. To forcefully wait on a specific cluster
207 * for a given domain, use the 'domain' parameter. To forcefully wait on an "external" cluster,
208 * use the "cluster" parameter.
210 * Never call this function after a large DB write that is *still* in a transaction.
211 * It only makes sense to call this after the possible lag inducing changes were committed.
213 * @param array $opts Optional fields that include:
214 * - domain : wait on the load balancer DBs that handles the given domain ID
215 * - cluster : wait on the given external load balancer DBs
216 * - timeout : Max wait time. Default: ~60 seconds
217 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
218 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
220 public function waitForReplication( array $opts = [] );
223 * Add a callback to be run in every call to waitForReplication() before waiting
225 * Callbacks must clear any transactions that they start
227 * @param string $name Callback name
228 * @param callable|null $callback Use null to unset a callback
230 public function setWaitForReplicationListener( $name, callable
$callback = null );
233 * Get a token asserting that no transaction writes are active
235 * @param string $fname Caller name (e.g. __METHOD__)
236 * @return mixed A value to pass to commitAndWaitForReplication()
238 public function getEmptyTransactionTicket( $fname );
241 * Convenience method for safely running commitMasterChanges()/waitForReplication()
243 * This will commit and wait unless $ticket indicates it is unsafe to do so
245 * @param string $fname Caller name (e.g. __METHOD__)
246 * @param mixed $ticket Result of getEmptyTransactionTicket()
247 * @param array $opts Options to waitForReplication()
248 * @throws DBReplicationWaitError
250 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] );
253 * @param string $dbName DB master name (e.g. "db1052")
254 * @return float|bool UNIX timestamp when client last touched the DB or false if not recent
256 public function getChronologyProtectorTouched( $dbName );
259 * Disable the ChronologyProtector for all load balancers
261 * This can be called at the start of special API entry points
263 public function disableChronologyProtection();
266 * Set a new table prefix for the existing local domain ID for testing
268 * @param string $prefix
270 public function setDomainPrefix( $prefix );
273 * Close all open database connections on all open load balancers.
275 public function closeAll();
278 * @param string $agent Agent name for query profiling
280 public function setAgentName( $agent );
283 * Append ?cpPosTime parameter to a URL for ChronologyProtector purposes if needed
285 * Note that unlike cookies, this works accross domains
288 * @param float $time UNIX timestamp just before shutdown() was called
291 public function appendPreShutdownTimeAsQuery( $url, $time );
294 * @param array $info Map of fields, including:
295 * - IPAddress : IP address
296 * - UserAgent : User-Agent HTTP header
297 * - ChronologyProtection : cookie/header value specifying ChronologyProtector usage
299 public function setRequestInfo( array $info );