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