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