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
24 namespace Wikimedia\Rdbms
;
26 use InvalidArgumentException
;
29 * An interface for generating database load balancers
33 interface ILBFactory
{
34 const SHUTDOWN_NO_CHRONPROT
= 0; // don't save DB positions at all
35 const SHUTDOWN_CHRONPROT_ASYNC
= 1; // save DB positions, but don't wait on remote DCs
36 const SHUTDOWN_CHRONPROT_SYNC
= 2; // save DB positions, waiting on all DCs
39 * Construct a manager of ILoadBalancer objects
41 * Sub-classes will extend the required keys in $conf with additional parameters
43 * @param array $conf Array with keys:
44 * - localDomain: A DatabaseDomain or domain ID string.
45 * - readOnlyReason: Reason the master DB is read-only if so [optional]
46 * - srvCache: BagOStuff object for server cache [optional]
47 * - memStash: BagOStuff object for cross-datacenter memory storage [optional]
48 * - wanCache: WANObjectCache object [optional]
49 * - hostname: The name of the current server [optional]
50 * - cliMode: Whether the execution context is a CLI script. [optional]
51 * - profiler: Class name or instance with profileIn()/profileOut() methods. [optional]
52 * - trxProfiler: TransactionProfiler instance. [optional]
53 * - replLogger: PSR-3 logger instance. [optional]
54 * - connLogger: PSR-3 logger instance. [optional]
55 * - queryLogger: PSR-3 logger instance. [optional]
56 * - perfLogger: PSR-3 logger instance. [optional]
57 * - errorLogger: Callback that takes an Exception and logs it. [optional]
58 * - deprecationLogger: Callback to log a deprecation warning. [optional]
59 * @throws InvalidArgumentException
61 public function __construct( array $conf );
64 * Disables all load balancers. All connections are closed, and any attempt to
65 * open a new connection will result in a DBAccessError.
66 * @see ILoadBalancer::disable()
68 public function destroy();
71 * Create a new load balancer object. The resulting object will be untracked,
72 * not chronology-protected, and the caller is responsible for cleaning it up.
74 * This method is for only advanced usage and callers should almost always use
75 * getMainLB() instead. This method can be useful when a table is used as a key/value
76 * store. In that cases, one might want to query it in autocommit mode (DBO_TRX off)
77 * but still use DBO_TRX transaction rounds on other tables.
79 * @param bool|string $domain Domain ID, or false for the current domain
80 * @return ILoadBalancer
82 public function newMainLB( $domain = false );
85 * Get a cached (tracked) load balancer object.
87 * @param bool|string $domain Domain ID, or false for the current domain
88 * @return ILoadBalancer
90 public function getMainLB( $domain = false );
93 * Create a new load balancer for external storage. The resulting object will be
94 * untracked, not chronology-protected, and the caller is responsible for cleaning it up.
96 * This method is for only advanced usage and callers should almost always use
97 * getExternalLB() instead. This method can be useful when a table is used as a
98 * key/value store. In that cases, one might want to query it in autocommit mode
99 * (DBO_TRX off) but still use DBO_TRX transaction rounds on other tables.
101 * @param string $cluster External storage cluster name
102 * @return ILoadBalancer
104 public function newExternalLB( $cluster );
107 * Get a cached (tracked) load balancer for external storage
109 * @param string $cluster External storage cluster name
110 * @return ILoadBalancer
112 public function getExternalLB( $cluster );
115 * Get cached (tracked) load balancers for all main database clusters
117 * @return LoadBalancer[] Map of (cluster name => LoadBalancer)
120 public function getAllMainLBs();
123 * Get cached (tracked) load balancers for all external database clusters
125 * @return LoadBalancer[] Map of (cluster name => LoadBalancer)
128 public function getAllExternalLBs();
131 * Execute a function for each tracked load balancer
132 * The callback is called with the load balancer as the first parameter,
133 * and $params passed as the subsequent parameters.
135 * @param callable $callback
136 * @param array $params
138 public function forEachLB( $callback, array $params = [] );
141 * Prepare all tracked load balancers for shutdown
142 * @param int $mode One of the class SHUTDOWN_* constants
143 * @param callable|null $workCallback Work to mask ChronologyProtector writes
144 * @param int|null &$cpIndex Position key write counter for ChronologyProtector
145 * @param string|null &$cpClientId Client ID hash for ChronologyProtector
147 public function shutdown(
148 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
,
149 callable
$workCallback = null,
155 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
157 * @param string $fname Caller name
159 public function flushReplicaSnapshots( $fname = __METHOD__
);
162 * Commit open transactions on all connections. This is useful for two main cases:
163 * - a) To commit changes to the masters.
164 * - b) To release the snapshot on all connections, master and replica DBs.
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
169 public function commitAll( $fname = __METHOD__
, array $options = [] );
172 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
174 * The DBO_TRX setting will be reverted to the default in each of these methods:
175 * - commitMasterChanges()
176 * - rollbackMasterChanges()
179 * This allows for custom transaction rounds from any outer transaction scope.
181 * @param string $fname
182 * @throws DBTransactionError
184 public function beginMasterChanges( $fname = __METHOD__
);
187 * Commit changes on all master connections
188 * @param string $fname Caller name
189 * @param array $options Options map:
190 * - maxWriteDuration: abort if more than this much time was spent in write queries
191 * @throws DBTransactionError
193 public function commitMasterChanges( $fname = __METHOD__
, array $options = [] );
196 * Rollback changes on all master connections
197 * @param string $fname Caller name
199 public function rollbackMasterChanges( $fname = __METHOD__
);
202 * Check if an explicit transaction round is active
206 public function hasTransactionRound();
209 * Check if transaction rounds can be started, committed, or rolled back right now
211 * This can be used as a recusion guard to avoid exceptions in transaction callbacks
216 public function isReadyForRoundOperations();
219 * Determine if any master connection has pending changes
222 public function hasMasterChanges();
225 * Detemine if any lagged replica DB connection was used
228 public function laggedReplicaUsed();
231 * Determine if any master connection has pending/written changes from this request
232 * @param float $age How many seconds ago is "recent" [defaults to LB lag wait timeout]
235 public function hasOrMadeRecentMasterChanges( $age = null );
238 * Waits for the replica DBs to catch up to the current master position
240 * Use this when updating very large numbers of rows, as in maintenance scripts,
241 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
243 * By default this waits on all DB clusters actually used in this request.
244 * This makes sense when lag being waiting on is caused by the code that does this check.
245 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
246 * that were not changed since the last wait check. To forcefully wait on a specific cluster
247 * for a given domain, use the 'domain' parameter. To forcefully wait on an "external" cluster,
248 * use the "cluster" parameter.
250 * Never call this function after a large DB write that is *still* in a transaction.
251 * It only makes sense to call this after the possible lag inducing changes were committed.
253 * @param array $opts Optional fields that include:
254 * - domain : wait on the load balancer DBs that handles the given domain ID
255 * - cluster : wait on the given external load balancer DBs
256 * - timeout : Max wait time. Default: ~60 seconds
257 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
258 * @throws DBReplicationWaitError If a timeout or error occurred waiting on a DB cluster
260 public function waitForReplication( array $opts = [] );
263 * Add a callback to be run in every call to waitForReplication() before waiting
265 * Callbacks must clear any transactions that they start
267 * @param string $name Callback name
268 * @param callable|null $callback Use null to unset a callback
270 public function setWaitForReplicationListener( $name, callable
$callback = null );
273 * Get a token asserting that no transaction writes are active
275 * @param string $fname Caller name (e.g. __METHOD__)
276 * @return mixed A value to pass to commitAndWaitForReplication()
278 public function getEmptyTransactionTicket( $fname );
281 * Convenience method for safely running commitMasterChanges()/waitForReplication()
283 * This will commit and wait unless $ticket indicates it is unsafe to do so
285 * @param string $fname Caller name (e.g. __METHOD__)
286 * @param mixed $ticket Result of getEmptyTransactionTicket()
287 * @param array $opts Options to waitForReplication()
288 * @throws DBReplicationWaitError
290 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] );
293 * @param string $dbName DB master name (e.g. "db1052")
294 * @return float|bool UNIX timestamp when client last touched the DB or false if not recent
296 public function getChronologyProtectorTouched( $dbName );
299 * Disable the ChronologyProtector for all load balancers
301 * This can be called at the start of special API entry points
303 public function disableChronologyProtection();
306 * Set a new table prefix for the existing local domain ID for testing
308 * @param string $prefix
310 public function setDomainPrefix( $prefix );
313 * Close all open database connections on all open load balancers.
315 public function closeAll();
318 * @param string $agent Agent name for query profiling
320 public function setAgentName( $agent );
323 * Append ?cpPosIndex parameter to a URL for ChronologyProtector purposes if needed
325 * Note that unlike cookies, this works accross domains
328 * @param int $index Write counter index
331 public function appendShutdownCPIndexAsQuery( $url, $index );
334 * @param array $info Map of fields, including:
335 * - IPAddress : IP address
336 * - UserAgent : User-Agent HTTP header
337 * - ChronologyProtection : cookie/header value specifying ChronologyProtector usage
338 * - ChronologyPositionIndex: timestamp used to get up-to-date DB positions for the agent
340 public function setRequestInfo( array $info );
343 * Make certain table names use their own database, schema, and table prefix
344 * when passed into SQL queries pre-escaped and without a qualified database name
346 * For example, "user" can be converted to "myschema.mydbname.user" for convenience.
347 * Appearances like `user`, somedb.user, somedb.someschema.user will used literally.
349 * Calling this twice will completely clear any old table aliases. Also, note that
350 * callers are responsible for making sure the schemas and databases actually exist.
352 * @param array[] $aliases Map of (table => (dbname, schema, prefix) map)
355 public function setTableAliases( array $aliases );
358 * Convert certain index names to alternative names before querying the DB
360 * Note that this applies to indexes regardless of the table they belong to.
362 * This can be employed when an index was renamed X => Y in code, but the new Y-named
363 * indexes were not yet built on all DBs. After all the Y-named ones are added by the DBA,
364 * the aliases can be removed, and then the old X-named indexes dropped.
366 * @param string[] $aliases
370 public function setIndexAliases( array $aliases );