Merge "FSFile and TempFSFile cleanups"
[lhc/web/wiklou.git] / includes / libs / rdbms / loadbalancer / ILoadBalancer.php
1 <?php
2 /**
3 * Database load balancing interface
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 * @author Aaron Schulz
23 */
24
25 /**
26 * Interface for database load balancing object that manages IDatabase handles
27 *
28 * @since 1.28
29 * @ingroup Database
30 */
31 interface ILoadBalancer {
32 /**
33 * Construct a manager of IDatabase connection objects
34 *
35 * @param array $params Parameter map with keys:
36 * - servers : Required. Array of server info structures.
37 * - localDomain: A DatabaseDomain or domain ID string.
38 * - loadMonitor : Name of a class used to fetch server lag and load.
39 * - readOnlyReason : Reason the master DB is read-only if so [optional]
40 * - waitTimeout : Maximum time to wait for replicas for consistency [optional]
41 * - srvCache : BagOStuff object for server cache [optional]
42 * - memCache : BagOStuff object for cluster memory cache [optional]
43 * - wanCache : WANObjectCache object [optional]
44 * - hostname : The name of the current server [optional]
45 * - cliMode: Whether the execution context is a CLI script. [optional]
46 * - profiler : Class name or instance with profileIn()/profileOut() methods. [optional]
47 * - trxProfiler: TransactionProfiler instance. [optional]
48 * - replLogger: PSR-3 logger instance. [optional]
49 * - connLogger: PSR-3 logger instance. [optional]
50 * - queryLogger: PSR-3 logger instance. [optional]
51 * - perfLogger: PSR-3 logger instance. [optional]
52 * - errorLogger : Callback that takes an Exception and logs it. [optional]
53 * @throws InvalidArgumentException
54 */
55 public function __construct( array $params );
56
57 /**
58 * Get the index of the reader connection, which may be a replica DB
59 * This takes into account load ratios and lag times. It should
60 * always return a consistent index during a given invocation
61 *
62 * Side effect: opens connections to databases
63 * @param string|bool $group Query group, or false for the generic reader
64 * @param string|bool $domain Domain ID, or false for the current domain
65 * @throws DBError
66 * @return bool|int|string
67 */
68 public function getReaderIndex( $group = false, $domain = false );
69
70 /**
71 * Set the master wait position
72 * If a DB_REPLICA connection has been opened already, waits
73 * Otherwise sets a variable telling it to wait if such a connection is opened
74 * @param DBMasterPos $pos
75 */
76 public function waitFor( $pos );
77
78 /**
79 * Set the master wait position and wait for a "generic" replica DB to catch up to it
80 *
81 * This can be used a faster proxy for waitForAll()
82 *
83 * @param DBMasterPos $pos
84 * @param int $timeout Max seconds to wait; default is mWaitTimeout
85 * @return bool Success (able to connect and no timeouts reached)
86 */
87 public function waitForOne( $pos, $timeout = null );
88
89 /**
90 * Set the master wait position and wait for ALL replica DBs to catch up to it
91 * @param DBMasterPos $pos
92 * @param int $timeout Max seconds to wait; default is mWaitTimeout
93 * @return bool Success (able to connect and no timeouts reached)
94 */
95 public function waitForAll( $pos, $timeout = null );
96
97 /**
98 * Get any open connection to a given server index, local or foreign
99 * Returns false if there is no connection open
100 *
101 * @param int $i Server index
102 * @return IDatabase|bool False on failure
103 */
104 public function getAnyOpenConnection( $i );
105
106 /**
107 * Get a connection by index
108 * This is the main entry point for this class.
109 *
110 * @param int $i Server index
111 * @param array|string|bool $groups Query group(s), or false for the generic reader
112 * @param string|bool $domain Domain ID, or false for the current domain
113 *
114 * @throws DBError
115 * @return IDatabase
116 */
117 public function getConnection( $i, $groups = [], $domain = false );
118
119 /**
120 * Mark a foreign connection as being available for reuse under a different
121 * DB name or prefix. This mechanism is reference-counted, and must be called
122 * the same number of times as getConnection() to work.
123 *
124 * @param IDatabase $conn
125 * @throws InvalidArgumentException
126 */
127 public function reuseConnection( $conn );
128
129 /**
130 * Get a database connection handle reference
131 *
132 * The handle's methods wrap simply wrap those of a IDatabase handle
133 *
134 * @see LoadBalancer::getConnection() for parameter information
135 *
136 * @param int $db
137 * @param array|string|bool $groups Query group(s), or false for the generic reader
138 * @param string|bool $domain Domain ID, or false for the current domain
139 * @return DBConnRef
140 */
141 public function getConnectionRef( $db, $groups = [], $domain = false );
142
143 /**
144 * Get a database connection handle reference without connecting yet
145 *
146 * The handle's methods wrap simply wrap those of a IDatabase handle
147 *
148 * @see LoadBalancer::getConnection() for parameter information
149 *
150 * @param int $db
151 * @param array|string|bool $groups Query group(s), or false for the generic reader
152 * @param string|bool $domain Domain ID, or false for the current domain
153 * @return DBConnRef
154 */
155 public function getLazyConnectionRef( $db, $groups = [], $domain = false );
156
157 /**
158 * Open a connection to the server given by the specified index
159 * Index must be an actual index into the array.
160 * If the server is already open, returns it.
161 *
162 * On error, returns false, and the connection which caused the
163 * error will be available via $this->mErrorConnection.
164 *
165 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
166 *
167 * @param int $i Server index
168 * @param string|bool $domain Domain ID, or false for the current domain
169 * @return IDatabase|bool Returns false on errors
170 */
171 public function openConnection( $i, $domain = false );
172
173 /**
174 * @return int
175 */
176 public function getWriterIndex();
177
178 /**
179 * Returns true if the specified index is a valid server index
180 *
181 * @param string $i
182 * @return bool
183 */
184 public function haveIndex( $i );
185
186 /**
187 * Returns true if the specified index is valid and has non-zero load
188 *
189 * @param string $i
190 * @return bool
191 */
192 public function isNonZeroLoad( $i );
193
194 /**
195 * Get the number of defined servers (not the number of open connections)
196 *
197 * @return int
198 */
199 public function getServerCount();
200
201 /**
202 * Get the host name or IP address of the server with the specified index
203 * Prefer a readable name if available.
204 * @param string $i
205 * @return string
206 */
207 public function getServerName( $i );
208
209 /**
210 * Return the server info structure for a given index, or false if the index is invalid.
211 * @param int $i
212 * @return array|bool
213 */
214 public function getServerInfo( $i );
215
216 /**
217 * Sets the server info structure for the given index. Entry at index $i
218 * is created if it doesn't exist
219 * @param int $i
220 * @param array $serverInfo
221 */
222 public function setServerInfo( $i, array $serverInfo );
223
224 /**
225 * Get the current master position for chronology control purposes
226 * @return DBMasterPos|bool Returns false if not applicable
227 */
228 public function getMasterPos();
229
230 /**
231 * Disable this load balancer. All connections are closed, and any attempt to
232 * open a new connection will result in a DBAccessError.
233 */
234 public function disable();
235
236 /**
237 * Close all open connections
238 */
239 public function closeAll();
240
241 /**
242 * Close a connection
243 *
244 * Using this function makes sure the LoadBalancer knows the connection is closed.
245 * If you use $conn->close() directly, the load balancer won't update its state.
246 *
247 * @param IDatabase $conn
248 */
249 public function closeConnection( IDatabase $conn );
250
251 /**
252 * Commit transactions on all open connections
253 * @param string $fname Caller name
254 * @throws DBExpectedError
255 */
256 public function commitAll( $fname = __METHOD__ );
257
258 /**
259 * Perform all pre-commit callbacks that remain part of the atomic transactions
260 * and disable any post-commit callbacks until runMasterPostTrxCallbacks()
261 *
262 * Use this only for mutli-database commits
263 */
264 public function finalizeMasterChanges();
265
266 /**
267 * Perform all pre-commit checks for things like replication safety
268 *
269 * Use this only for mutli-database commits
270 *
271 * @param array $options Includes:
272 * - maxWriteDuration : max write query duration time in seconds
273 * @throws DBTransactionError
274 */
275 public function approveMasterChanges( array $options );
276
277 /**
278 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
279 *
280 * The DBO_TRX setting will be reverted to the default in each of these methods:
281 * - commitMasterChanges()
282 * - rollbackMasterChanges()
283 * - commitAll()
284 * This allows for custom transaction rounds from any outer transaction scope.
285 *
286 * @param string $fname
287 * @throws DBExpectedError
288 */
289 public function beginMasterChanges( $fname = __METHOD__ );
290
291 /**
292 * Issue COMMIT on all master connections where writes where done
293 * @param string $fname Caller name
294 * @throws DBExpectedError
295 */
296 public function commitMasterChanges( $fname = __METHOD__ );
297
298 /**
299 * Issue all pending post-COMMIT/ROLLBACK callbacks
300 *
301 * Use this only for mutli-database commits
302 *
303 * @param integer $type IDatabase::TRIGGER_* constant
304 * @return Exception|null The first exception or null if there were none
305 */
306 public function runMasterPostTrxCallbacks( $type );
307
308 /**
309 * Issue ROLLBACK only on master, only if queries were done on connection
310 * @param string $fname Caller name
311 * @throws DBExpectedError
312 */
313 public function rollbackMasterChanges( $fname = __METHOD__ );
314
315 /**
316 * Suppress all pending post-COMMIT/ROLLBACK callbacks
317 *
318 * Use this only for mutli-database commits
319 *
320 * @return Exception|null The first exception or null if there were none
321 */
322 public function suppressTransactionEndCallbacks();
323
324 /**
325 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
326 *
327 * @param string $fname Caller name
328 */
329 public function flushReplicaSnapshots( $fname = __METHOD__ );
330
331 /**
332 * @return bool Whether a master connection is already open
333 */
334 public function hasMasterConnection();
335
336 /**
337 * Determine if there are pending changes in a transaction by this thread
338 * @return bool
339 */
340 public function hasMasterChanges();
341
342 /**
343 * Get the timestamp of the latest write query done by this thread
344 * @return float|bool UNIX timestamp or false
345 */
346 public function lastMasterChangeTimestamp();
347
348 /**
349 * Check if this load balancer object had any recent or still
350 * pending writes issued against it by this PHP thread
351 *
352 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
353 * @return bool
354 */
355 public function hasOrMadeRecentMasterChanges( $age = null );
356
357 /**
358 * Get the list of callers that have pending master changes
359 *
360 * @return string[] List of method names
361 */
362 public function pendingMasterChangeCallers();
363
364 /**
365 * @note This method will trigger a DB connection if not yet done
366 * @param string|bool $domain Domain ID, or false for the current domain
367 * @return bool Whether the generic connection for reads is highly "lagged"
368 */
369 public function getLaggedReplicaMode( $domain = false );
370
371 /**
372 * @note This method will never cause a new DB connection
373 * @return bool Whether any generic connection used for reads was highly "lagged"
374 */
375 public function laggedReplicaUsed();
376
377 /**
378 * @note This method may trigger a DB connection if not yet done
379 * @param string|bool $domain Domain ID, or false for the current domain
380 * @param IDatabase|null DB master connection; used to avoid loops [optional]
381 * @return string|bool Reason the master is read-only or false if it is not
382 */
383 public function getReadOnlyReason( $domain = false, IDatabase $conn = null );
384
385 /**
386 * Disables/enables lag checks
387 * @param null|bool $mode
388 * @return bool
389 */
390 public function allowLagged( $mode = null );
391
392 /**
393 * @return bool
394 */
395 public function pingAll();
396
397 /**
398 * Call a function with each open connection object
399 * @param callable $callback
400 * @param array $params
401 */
402 public function forEachOpenConnection( $callback, array $params = [] );
403
404 /**
405 * Call a function with each open connection object to a master
406 * @param callable $callback
407 * @param array $params
408 */
409 public function forEachOpenMasterConnection( $callback, array $params = [] );
410
411 /**
412 * Call a function with each open replica DB connection object
413 * @param callable $callback
414 * @param array $params
415 */
416 public function forEachOpenReplicaConnection( $callback, array $params = [] );
417
418 /**
419 * Get the hostname and lag time of the most-lagged replica DB
420 *
421 * This is useful for maintenance scripts that need to throttle their updates.
422 * May attempt to open connections to replica DBs on the default DB. If there is
423 * no lag, the maximum lag will be reported as -1.
424 *
425 * @param bool|string $domain Domain ID, or false for the default database
426 * @return array ( host, max lag, index of max lagged host )
427 */
428 public function getMaxLag( $domain = false );
429
430 /**
431 * Get an estimate of replication lag (in seconds) for each server
432 *
433 * Results are cached for a short time in memcached/process cache
434 *
435 * Values may be "false" if replication is too broken to estimate
436 *
437 * @param string|bool $domain
438 * @return int[] Map of (server index => float|int|bool)
439 */
440 public function getLagTimes( $domain = false );
441
442 /**
443 * Get the lag in seconds for a given connection, or zero if this load
444 * balancer does not have replication enabled.
445 *
446 * This should be used in preference to Database::getLag() in cases where
447 * replication may not be in use, since there is no way to determine if
448 * replication is in use at the connection level without running
449 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
450 * function instead of Database::getLag() avoids a fatal error in this
451 * case on many installations.
452 *
453 * @param IDatabase $conn
454 * @return int|bool Returns false on error
455 */
456 public function safeGetLag( IDatabase $conn );
457
458 /**
459 * Wait for a replica DB to reach a specified master position
460 *
461 * This will connect to the master to get an accurate position if $pos is not given
462 *
463 * @param IDatabase $conn Replica DB
464 * @param DBMasterPos|bool $pos Master position; default: current position
465 * @param integer|null $timeout Timeout in seconds [optional]
466 * @return bool Success
467 */
468 public function safeWaitForMasterPos( IDatabase $conn, $pos = false, $timeout = null );
469
470 /**
471 * Clear the cache for slag lag delay times
472 *
473 * This is only used for testing
474 */
475 public function clearLagTimeCache();
476
477 /**
478 * Set a callback via IDatabase::setTransactionListener() on
479 * all current and future master connections of this load balancer
480 *
481 * @param string $name Callback name
482 * @param callable|null $callback
483 */
484 public function setTransactionListener( $name, callable $callback = null );
485
486 /**
487 * Set a new table prefix for the existing local domain ID for testing
488 *
489 * @param string $prefix
490 */
491 public function setDomainPrefix( $prefix );
492
493 /**
494 * Make certain table names use their own database, schema, and table prefix
495 * when passed into SQL queries pre-escaped and without a qualified database name
496 *
497 * For example, "user" can be converted to "myschema.mydbname.user" for convenience.
498 * Appearances like `user`, somedb.user, somedb.someschema.user will used literally.
499 *
500 * Calling this twice will completely clear any old table aliases. Also, note that
501 * callers are responsible for making sure the schemas and databases actually exist.
502 *
503 * @param array[] $aliases Map of (table => (dbname, schema, prefix) map)
504 */
505 public function setTableAliases( array $aliases );
506 }