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