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