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