06e45f80f39fd0e2fcb20d2fcd651857f40749ac
[lhc/web/wiklou.git] / includes / libs / rdbms / lbfactory / ILBFactory.php
1 <?php
2 /**
3 * Generator and manager of database load balancing objects
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Database
22 */
23
24 namespace Wikimedia\Rdbms;
25
26 use InvalidArgumentException;
27
28 /**
29 * An interface for generating database load balancers
30 * @ingroup Database
31 * @since 1.28
32 */
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
37
38 /**
39 * Construct a manager of ILoadBalancer objects
40 *
41 * Sub-classes will extend the required keys in $conf with additional parameters
42 *
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 * - maxLag: Try to avoid DB replicas with lag above this many seconds [optional]
52 * - profiler: Class name or instance with profileIn()/profileOut() methods. [optional]
53 * - trxProfiler: TransactionProfiler instance. [optional]
54 * - replLogger: PSR-3 logger instance. [optional]
55 * - connLogger: PSR-3 logger instance. [optional]
56 * - queryLogger: PSR-3 logger instance. [optional]
57 * - perfLogger: PSR-3 logger instance. [optional]
58 * - errorLogger: Callback that takes an Exception and logs it. [optional]
59 * - deprecationLogger: Callback to log a deprecation warning. [optional]
60 * @throws InvalidArgumentException
61 */
62 public function __construct( array $conf );
63
64 /**
65 * Disables all load balancers. All connections are closed, and any attempt to
66 * open a new connection will result in a DBAccessError.
67 * @see ILoadBalancer::disable()
68 */
69 public function destroy();
70
71 /**
72 * Get the local (and default) database domain ID of connection handles
73 *
74 * @see DatabaseDomain
75 * @return string Database domain ID; this specifies DB name, schema, and table prefix
76 * @since 1.32
77 */
78 public function getLocalDomainID();
79
80 /**
81 * @param DatabaseDomain|string|bool $domain Database domain
82 * @return string Value of $domain if provided or the local domain otherwise
83 * @since 1.32
84 */
85 public function resolveDomainID( $domain );
86
87 /**
88 * Close all connection and redefine the local domain for testing or schema creation
89 *
90 * @param DatabaseDomain|string $domain
91 * @since 1.33
92 */
93 public function redefineLocalDomain( $domain );
94
95 /**
96 * Create a new load balancer object. The resulting object will be untracked,
97 * not chronology-protected, and the caller is responsible for cleaning it up.
98 *
99 * This method is for only advanced usage and callers should almost always use
100 * getMainLB() instead. This method can be useful when a table is used as a key/value
101 * store. In that cases, one might want to query it in autocommit mode (DBO_TRX off)
102 * but still use DBO_TRX transaction rounds on other tables.
103 *
104 * @param bool|string $domain Domain ID, or false for the current domain
105 * @return ILoadBalancer
106 */
107 public function newMainLB( $domain = false );
108
109 /**
110 * Get a cached (tracked) load balancer object.
111 *
112 * @param bool|string $domain Domain ID, or false for the current domain
113 * @return ILoadBalancer
114 */
115 public function getMainLB( $domain = false );
116
117 /**
118 * Create a new load balancer for external storage. The resulting object will be
119 * untracked, not chronology-protected, and the caller is responsible for cleaning it up.
120 *
121 * This method is for only advanced usage and callers should almost always use
122 * getExternalLB() instead. This method can be useful when a table is used as a
123 * key/value store. In that cases, one might want to query it in autocommit mode
124 * (DBO_TRX off) but still use DBO_TRX transaction rounds on other tables.
125 *
126 * @param string $cluster External storage cluster name
127 * @return ILoadBalancer
128 */
129 public function newExternalLB( $cluster );
130
131 /**
132 * Get a cached (tracked) load balancer for external storage
133 *
134 * @param string $cluster External storage cluster name
135 * @return ILoadBalancer
136 */
137 public function getExternalLB( $cluster );
138
139 /**
140 * Get cached (tracked) load balancers for all main database clusters
141 *
142 * @return LoadBalancer[] Map of (cluster name => LoadBalancer)
143 * @since 1.29
144 */
145 public function getAllMainLBs();
146
147 /**
148 * Get cached (tracked) load balancers for all external database clusters
149 *
150 * @return LoadBalancer[] Map of (cluster name => LoadBalancer)
151 * @since 1.29
152 */
153 public function getAllExternalLBs();
154
155 /**
156 * Execute a function for each tracked load balancer
157 * The callback is called with the load balancer as the first parameter,
158 * and $params passed as the subsequent parameters.
159 *
160 * @param callable $callback
161 * @param array $params
162 */
163 public function forEachLB( $callback, array $params = [] );
164
165 /**
166 * Prepare all tracked load balancers for shutdown
167 * @param int $mode One of the class SHUTDOWN_* constants
168 * @param callable|null $workCallback Work to mask ChronologyProtector writes
169 * @param int|null &$cpIndex Position key write counter for ChronologyProtector
170 * @param string|null &$cpClientId Client ID hash for ChronologyProtector
171 */
172 public function shutdown(
173 $mode = self::SHUTDOWN_CHRONPROT_SYNC,
174 callable $workCallback = null,
175 &$cpIndex = null,
176 &$cpClientId = null
177 );
178
179 /**
180 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
181 *
182 * @param string $fname Caller name
183 */
184 public function flushReplicaSnapshots( $fname = __METHOD__ );
185
186 /**
187 * Commit open transactions on all connections. This is useful for two main cases:
188 * - a) To commit changes to the masters.
189 * - b) To release the snapshot on all connections, master and replica DBs.
190 * @param string $fname Caller name
191 * @param array $options Options map:
192 * - maxWriteDuration: abort if more than this much time was spent in write queries
193 */
194 public function commitAll( $fname = __METHOD__, array $options = [] );
195
196 /**
197 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
198 *
199 * The DBO_TRX setting will be reverted to the default in each of these methods:
200 * - commitMasterChanges()
201 * - rollbackMasterChanges()
202 * - commitAll()
203 *
204 * This allows for custom transaction rounds from any outer transaction scope.
205 *
206 * @param string $fname
207 * @throws DBTransactionError
208 */
209 public function beginMasterChanges( $fname = __METHOD__ );
210
211 /**
212 * Commit changes and clear view snapshots on all master connections
213 * @param string $fname Caller name
214 * @param array $options Options map:
215 * - maxWriteDuration: abort if more than this much time was spent in write queries
216 * @throws DBTransactionError
217 */
218 public function commitMasterChanges( $fname = __METHOD__, array $options = [] );
219
220 /**
221 * Rollback changes on all master connections
222 * @param string $fname Caller name
223 */
224 public function rollbackMasterChanges( $fname = __METHOD__ );
225
226 /**
227 * Check if an explicit transaction round is active
228 * @return bool
229 * @since 1.29
230 */
231 public function hasTransactionRound();
232
233 /**
234 * Check if transaction rounds can be started, committed, or rolled back right now
235 *
236 * This can be used as a recusion guard to avoid exceptions in transaction callbacks
237 *
238 * @return bool
239 * @since 1.32
240 */
241 public function isReadyForRoundOperations();
242
243 /**
244 * Determine if any master connection has pending changes
245 * @return bool
246 */
247 public function hasMasterChanges();
248
249 /**
250 * Detemine if any lagged replica DB connection was used
251 * @return bool
252 */
253 public function laggedReplicaUsed();
254
255 /**
256 * Determine if any master connection has pending/written changes from this request
257 * @param float|null $age How many seconds ago is "recent" [defaults to LB lag wait timeout]
258 * @return bool
259 */
260 public function hasOrMadeRecentMasterChanges( $age = null );
261
262 /**
263 * Waits for the replica DBs to catch up to the current master position
264 *
265 * Use this when updating very large numbers of rows, as in maintenance scripts,
266 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
267 *
268 * By default this waits on all DB clusters actually used in this request.
269 * This makes sense when lag being waiting on is caused by the code that does this check.
270 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
271 * that were not changed since the last wait check. To forcefully wait on a specific cluster
272 * for a given domain, use the 'domain' parameter. To forcefully wait on an "external" cluster,
273 * use the "cluster" parameter.
274 *
275 * Never call this function after a large DB write that is *still* in a transaction.
276 * It only makes sense to call this after the possible lag inducing changes were committed.
277 *
278 * @param array $opts Optional fields that include:
279 * - domain : wait on the load balancer DBs that handles the given domain ID
280 * - cluster : wait on the given external load balancer DBs
281 * - timeout : Max wait time. Default: 60 seconds for CLI, 1 second for web.
282 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
283 * @return bool True on success, false if a timeout or error occurred while waiting
284 */
285 public function waitForReplication( array $opts = [] );
286
287 /**
288 * Add a callback to be run in every call to waitForReplication() before waiting
289 *
290 * Callbacks must clear any transactions that they start
291 *
292 * @param string $name Callback name
293 * @param callable|null $callback Use null to unset a callback
294 */
295 public function setWaitForReplicationListener( $name, callable $callback = null );
296
297 /**
298 * Get a token asserting that no transaction writes are active
299 *
300 * @param string $fname Caller name (e.g. __METHOD__)
301 * @return mixed A value to pass to commitAndWaitForReplication()
302 */
303 public function getEmptyTransactionTicket( $fname );
304
305 /**
306 * Convenience method for safely running commitMasterChanges()/waitForReplication()
307 *
308 * This will commit and wait unless $ticket indicates it is unsafe to do so
309 *
310 * @param string $fname Caller name (e.g. __METHOD__)
311 * @param mixed $ticket Result of getEmptyTransactionTicket()
312 * @param array $opts Options to waitForReplication()
313 * @return bool True if the wait was successful, false on timeout
314 */
315 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] );
316
317 /**
318 * @param string $dbName DB master name (e.g. "db1052")
319 * @return float|bool UNIX timestamp when client last touched the DB or false if not recent
320 */
321 public function getChronologyProtectorTouched( $dbName );
322
323 /**
324 * Disable the ChronologyProtector for all load balancers
325 *
326 * This can be called at the start of special API entry points
327 */
328 public function disableChronologyProtection();
329
330 /**
331 * Set a new table prefix for the existing local domain ID for testing
332 *
333 * @param string $prefix
334 * @since 1.33
335 */
336 public function setLocalDomainPrefix( $prefix );
337
338 /**
339 * Close all open database connections on all open load balancers.
340 */
341 public function closeAll();
342
343 /**
344 * @param string $agent Agent name for query profiling
345 */
346 public function setAgentName( $agent );
347
348 /**
349 * Append ?cpPosIndex parameter to a URL for ChronologyProtector purposes if needed
350 *
351 * Note that unlike cookies, this works across domains
352 *
353 * @param string $url
354 * @param int $index Write counter index
355 * @return string
356 */
357 public function appendShutdownCPIndexAsQuery( $url, $index );
358
359 /**
360 * Get the client ID of the ChronologyProtector instance
361 *
362 * @return string Client ID
363 * @since 1.34
364 */
365 public function getChronologyProtectorClientId();
366
367 /**
368 * @param array $info Map of fields, including:
369 * - IPAddress : IP address
370 * - UserAgent : User-Agent HTTP header
371 * - ChronologyProtection : cookie/header value specifying ChronologyProtector usage
372 * - ChronologyPositionIndex: timestamp used to get up-to-date DB positions for the agent
373 */
374 public function setRequestInfo( array $info );
375
376 /**
377 * Make certain table names use their own database, schema, and table prefix
378 * when passed into SQL queries pre-escaped and without a qualified database name
379 *
380 * For example, "user" can be converted to "myschema.mydbname.user" for convenience.
381 * Appearances like `user`, somedb.user, somedb.someschema.user will used literally.
382 *
383 * Calling this twice will completely clear any old table aliases. Also, note that
384 * callers are responsible for making sure the schemas and databases actually exist.
385 *
386 * @param array[] $aliases Map of (table => (dbname, schema, prefix) map)
387 * @since 1.31
388 */
389 public function setTableAliases( array $aliases );
390
391 /**
392 * Convert certain index names to alternative names before querying the DB
393 *
394 * Note that this applies to indexes regardless of the table they belong to.
395 *
396 * This can be employed when an index was renamed X => Y in code, but the new Y-named
397 * indexes were not yet built on all DBs. After all the Y-named ones are added by the DBA,
398 * the aliases can be removed, and then the old X-named indexes dropped.
399 *
400 * @param string[] $aliases
401 * @since 1.31
402 */
403 public function setIndexAliases( array $aliases );
404 }