Merge "Change 'editfont' default preference to 'monospace'"
[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 */
23 namespace Wikimedia\Rdbms;
24
25 use Exception;
26 use InvalidArgumentException;
27
28 /**
29 * Database cluster connection, tracking, load balancing, and transaction manager interface
30 *
31 * A "cluster" is considered to be one master database and zero or more replica databases.
32 * Typically, the replica DBs replicate from the master asynchronously. The first node in the
33 * "servers" configuration array is always considered the "master". However, this class can still
34 * be used when all or some of the "replica" DBs are multi-master peers of the master or even
35 * when all the DBs are non-replicating clones of each other holding read-only data. Thus, the
36 * role of "master" is in some cases merely nominal.
37 *
38 * By default, each DB server uses DBO_DEFAULT for its 'flags' setting, unless explicitly set
39 * otherwise in configuration. DBO_DEFAULT behavior depends on whether 'cliMode' is set:
40 * - In CLI mode, the flag has no effect with regards to LoadBalancer.
41 * - In non-CLI mode, the flag causes implicit transactions to be used; the first query on
42 * a database starts a transaction on that database. The transactions are meant to remain
43 * pending until either commitMasterChanges() or rollbackMasterChanges() is called. The
44 * application must have some point where it calls commitMasterChanges() near the end of
45 * the PHP request.
46 * Every iteration of beginMasterChanges()/commitMasterChanges() is called a "transaction round".
47 * Rounds are useful on the master DB connections because they make single-DB (and by and large
48 * multi-DB) updates in web requests all-or-nothing. Also, transactions on replica DBs are useful
49 * when REPEATABLE-READ or SERIALIZABLE isolation is used because all foriegn keys and constraints
50 * hold across separate queries in the DB transaction since the data appears within a consistent
51 * point-in-time snapshot.
52 *
53 * The typical caller will use LoadBalancer::getConnection( DB_* ) to yield a live database
54 * connection handle. The choice of which DB server to use is based on pre-defined loads for
55 * weighted random selection, adjustments thereof by LoadMonitor, and the amount of replication
56 * lag on each DB server. Lag checks might cause problems in certain setups, so they should be
57 * tuned in the server configuration maps as follows:
58 * - Master + N Replica(s): set 'max lag' to an appropriate threshold for avoiding any database
59 * lagged by this much or more. If all DBs are this lagged, then the load balancer considers
60 * the cluster to be read-only.
61 * - Galera Cluster: Seconds_Behind_Master will be 0, so there probably is nothing to tune.
62 * Note that lag is still possible depending on how wsrep-sync-wait is set server-side.
63 * - Read-only archive clones: set 'is static' in the server configuration maps. This will
64 * treat all such DBs as having 0 lag.
65 * - SQL load balancing proxy: any proxy should handle lag checks on its own, so the 'max lag'
66 * parameter should probably be set to INF in the server configuration maps. This will make
67 * the load balancer ignore whatever it detects as the lag of the logical replica is (which
68 * would probably just randomly bounce around).
69 *
70 * If using a SQL proxy service, it would probably be best to have two proxy hosts for the
71 * load balancer to talk to. One would be the 'host' of the master server entry and another for
72 * the (logical) replica server entry. The proxy could map the load balancer's "replica" DB to
73 * any number of physical replica DBs.
74 *
75 * @since 1.28
76 * @ingroup Database
77 */
78 interface ILoadBalancer {
79 /** @var int Request a replica DB connection */
80 const DB_REPLICA = -1;
81 /** @var int Request a master DB connection */
82 const DB_MASTER = -2;
83
84 /** @var string Domain specifier when no specific database needs to be selected */
85 const DOMAIN_ANY = '';
86
87 /** @var int DB handle should have DBO_TRX disabled and the caller will leave it as such */
88 const CONN_TRX_AUTO = 1;
89
90 /**
91 * Construct a manager of IDatabase connection objects
92 *
93 * @param array $params Parameter map with keys:
94 * - servers : Required. Array of server info structures.
95 * - localDomain: A DatabaseDomain or domain ID string.
96 * - loadMonitor : Name of a class used to fetch server lag and load.
97 * - readOnlyReason : Reason the master DB is read-only if so [optional]
98 * - waitTimeout : Maximum time to wait for replicas for consistency [optional]
99 * - srvCache : BagOStuff object for server cache [optional]
100 * - wanCache : WANObjectCache object [optional]
101 * - chronologyProtector: ChronologyProtector object [optional]
102 * - hostname : The name of the current server [optional]
103 * - cliMode: Whether the execution context is a CLI script. [optional]
104 * - profiler : Class name or instance with profileIn()/profileOut() methods. [optional]
105 * - trxProfiler: TransactionProfiler instance. [optional]
106 * - replLogger: PSR-3 logger instance. [optional]
107 * - connLogger: PSR-3 logger instance. [optional]
108 * - queryLogger: PSR-3 logger instance. [optional]
109 * - perfLogger: PSR-3 logger instance. [optional]
110 * - errorLogger : Callback that takes an Exception and logs it. [optional]
111 * @throws InvalidArgumentException
112 */
113 public function __construct( array $params );
114
115 /**
116 * Get the index of the reader connection, which may be a replica DB
117 *
118 * This takes into account load ratios and lag times. It should
119 * always return a consistent index during a given invocation.
120 *
121 * Side effect: opens connections to databases
122 * @param string|bool $group Query group, or false for the generic reader
123 * @param string|bool $domain Domain ID, or false for the current domain
124 * @throws DBError
125 * @return bool|int|string
126 */
127 public function getReaderIndex( $group = false, $domain = false );
128
129 /**
130 * Set the master wait position
131 *
132 * If a DB_REPLICA connection has been opened already, then wait immediately.
133 * Otherwise sets a variable telling it to wait if such a connection is opened.
134 *
135 * This only applies to connections to the generic replica DB for this request.
136 * If a timeout happens when waiting, then getLaggedReplicaMode()/laggedReplicaUsed()
137 * will return true.
138 *
139 * @param DBMasterPos|bool $pos Master position or false
140 */
141 public function waitFor( $pos );
142
143 /**
144 * Set the master wait position and wait for a "generic" replica DB to catch up to it
145 *
146 * This can be used a faster proxy for waitForAll()
147 *
148 * @param DBMasterPos|bool $pos Master position or false
149 * @param int $timeout Max seconds to wait; default is mWaitTimeout
150 * @return bool Success (able to connect and no timeouts reached)
151 */
152 public function waitForOne( $pos, $timeout = null );
153
154 /**
155 * Set the master wait position and wait for ALL replica DBs to catch up to it
156 *
157 * @param DBMasterPos|bool $pos Master position or false
158 * @param int $timeout Max seconds to wait; default is mWaitTimeout
159 * @return bool Success (able to connect and no timeouts reached)
160 */
161 public function waitForAll( $pos, $timeout = null );
162
163 /**
164 * Get any open connection to a given server index, local or foreign
165 *
166 * @param int $i Server index or DB_MASTER/DB_REPLICA
167 * @return Database|bool False if no such connection is open
168 */
169 public function getAnyOpenConnection( $i );
170
171 /**
172 * Get a connection by index
173 *
174 * Avoid using CONN_TRX_AUTO with sqlite (e.g. check getServerType() first)
175 *
176 * @param int $i Server index or DB_MASTER/DB_REPLICA
177 * @param array|string|bool $groups Query group(s), or false for the generic reader
178 * @param string|bool $domain Domain ID, or false for the current domain
179 * @param int $flags Bitfield of CONN_* class constants
180 *
181 * @throws DBError
182 * @return Database
183 */
184 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 );
185
186 /**
187 * Mark a foreign connection as being available for reuse under a different DB domain
188 *
189 * This mechanism is reference-counted, and must be called the same number of times
190 * as getConnection() to work.
191 *
192 * @param IDatabase $conn
193 * @throws InvalidArgumentException
194 */
195 public function reuseConnection( $conn );
196
197 /**
198 * Get a database connection handle reference
199 *
200 * The handle's methods simply wrap those of a Database handle
201 *
202 * Avoid using CONN_TRX_AUTO with sqlite (e.g. check getServerType() first)
203 *
204 * @see ILoadBalancer::getConnection() for parameter information
205 *
206 * @param int $i Server index or DB_MASTER/DB_REPLICA
207 * @param array|string|bool $groups Query group(s), or false for the generic reader
208 * @param string|bool $domain Domain ID, or false for the current domain
209 * @param int $flags Bitfield of CONN_* class constants (e.g. CONN_TRX_AUTO)
210 * @return DBConnRef
211 */
212 public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 );
213
214 /**
215 * Get a database connection handle reference without connecting yet
216 *
217 * The handle's methods simply wrap those of a Database handle
218 *
219 * Avoid using CONN_TRX_AUTO with sqlite (e.g. check getServerType() first)
220 *
221 * @see ILoadBalancer::getConnection() for parameter information
222 *
223 * @param int $i Server index or DB_MASTER/DB_REPLICA
224 * @param array|string|bool $groups Query group(s), or false for the generic reader
225 * @param string|bool $domain Domain ID, or false for the current domain
226 * @param int $flags Bitfield of CONN_* class constants (e.g. CONN_TRX_AUTO)
227 * @return DBConnRef
228 */
229 public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 );
230
231 /**
232 * Get a maintenance database connection handle reference for migrations and schema changes
233 *
234 * The handle's methods simply wrap those of a Database handle
235 *
236 * Avoid using CONN_TRX_AUTO with sqlite (e.g. check getServerType() first)
237 *
238 * @see ILoadBalancer::getConnection() for parameter information
239 *
240 * @param int $db Server index or DB_MASTER/DB_REPLICA
241 * @param array|string|bool $groups Query group(s), or false for the generic reader
242 * @param string|bool $domain Domain ID, or false for the current domain
243 * @param int $flags Bitfield of CONN_* class constants (e.g. CONN_TRX_AUTO)
244 * @return MaintainableDBConnRef
245 */
246 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 );
247
248 /**
249 * Open a connection to the server given by the specified index
250 *
251 * The index must be an actual index into the array. If a connection to the server is
252 * already open and not considered an "in use" foreign connection, this simply returns it.
253 *
254 * Avoid using CONN_TRX_AUTO with sqlite (e.g. check getServerType() first)
255 *
256 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
257 *
258 * @param int $i Server index (does not support DB_MASTER/DB_REPLICA)
259 * @param string|bool $domain Domain ID, or false for the current domain
260 * @param int $flags Bitfield of CONN_* class constants (e.g. CONN_TRX_AUTO)
261 * @return Database|bool Returns false on errors
262 * @throws DBAccessError
263 */
264 public function openConnection( $i, $domain = false, $flags = 0 );
265
266 /**
267 * @return int
268 */
269 public function getWriterIndex();
270
271 /**
272 * Returns true if the specified index is a valid server index
273 *
274 * @param int $i
275 * @return bool
276 */
277 public function haveIndex( $i );
278
279 /**
280 * Returns true if the specified index is valid and has non-zero load
281 *
282 * @param int $i
283 * @return bool
284 */
285 public function isNonZeroLoad( $i );
286
287 /**
288 * Get the number of defined servers (not the number of open connections)
289 *
290 * @return int
291 */
292 public function getServerCount();
293
294 /**
295 * Get the host name or IP address of the server with the specified index
296 *
297 * @param int $i
298 * @return string Readable name if available or IP/host otherwise
299 */
300 public function getServerName( $i );
301
302 /**
303 * Get DB type of the server with the specified index
304 *
305 * @param int $i
306 * @return string One of (mysql,postgres,sqlite,...) or "unknown" for bad indexes
307 * @since 1.30
308 */
309 public function getServerType( $i );
310
311 /**
312 * Return the server info structure for a given index, or false if the index is invalid.
313 * @param int $i
314 * @return array|bool
315 *
316 * @deprecated Since 1.30, no alternative
317 */
318 public function getServerInfo( $i );
319
320 /**
321 * Sets the server info structure for the given index. Entry at index $i
322 * is created if it doesn't exist
323 * @param int $i
324 * @param array $serverInfo
325 *
326 * @deprecated Since 1.30, construct new object
327 */
328 public function setServerInfo( $i, array $serverInfo );
329
330 /**
331 * Get the current master position for chronology control purposes
332 * @return DBMasterPos|bool Returns false if not applicable
333 */
334 public function getMasterPos();
335
336 /**
337 * Disable this load balancer. All connections are closed, and any attempt to
338 * open a new connection will result in a DBAccessError.
339 */
340 public function disable();
341
342 /**
343 * Close all open connections
344 */
345 public function closeAll();
346
347 /**
348 * Close a connection
349 *
350 * Using this function makes sure the LoadBalancer knows the connection is closed.
351 * If you use $conn->close() directly, the load balancer won't update its state.
352 *
353 * @param IDatabase $conn
354 */
355 public function closeConnection( IDatabase $conn );
356
357 /**
358 * Commit transactions on all open connections
359 * @param string $fname Caller name
360 * @throws DBExpectedError
361 */
362 public function commitAll( $fname = __METHOD__ );
363
364 /**
365 * Perform all pre-commit callbacks that remain part of the atomic transactions
366 * and disable any post-commit callbacks until runMasterPostTrxCallbacks()
367 *
368 * Use this only for mutli-database commits
369 */
370 public function finalizeMasterChanges();
371
372 /**
373 * Perform all pre-commit checks for things like replication safety
374 *
375 * Use this only for mutli-database commits
376 *
377 * @param array $options Includes:
378 * - maxWriteDuration : max write query duration time in seconds
379 * @throws DBTransactionError
380 */
381 public function approveMasterChanges( array $options );
382
383 /**
384 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
385 *
386 * The DBO_TRX setting will be reverted to the default in each of these methods:
387 * - commitMasterChanges()
388 * - rollbackMasterChanges()
389 * - commitAll()
390 * This allows for custom transaction rounds from any outer transaction scope.
391 *
392 * @param string $fname
393 * @throws DBExpectedError
394 */
395 public function beginMasterChanges( $fname = __METHOD__ );
396
397 /**
398 * Issue COMMIT on all master connections where writes where done
399 * @param string $fname Caller name
400 * @throws DBExpectedError
401 */
402 public function commitMasterChanges( $fname = __METHOD__ );
403
404 /**
405 * Issue all pending post-COMMIT/ROLLBACK callbacks
406 *
407 * Use this only for mutli-database commits
408 *
409 * @param int $type IDatabase::TRIGGER_* constant
410 * @return Exception|null The first exception or null if there were none
411 */
412 public function runMasterPostTrxCallbacks( $type );
413
414 /**
415 * Issue ROLLBACK only on master, only if queries were done on connection
416 * @param string $fname Caller name
417 * @throws DBExpectedError
418 */
419 public function rollbackMasterChanges( $fname = __METHOD__ );
420
421 /**
422 * Suppress all pending post-COMMIT/ROLLBACK callbacks
423 *
424 * Use this only for mutli-database commits
425 *
426 * @return Exception|null The first exception or null if there were none
427 */
428 public function suppressTransactionEndCallbacks();
429
430 /**
431 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
432 *
433 * @param string $fname Caller name
434 */
435 public function flushReplicaSnapshots( $fname = __METHOD__ );
436
437 /**
438 * @return bool Whether a master connection is already open
439 */
440 public function hasMasterConnection();
441
442 /**
443 * Determine if there are pending changes in a transaction by this thread
444 * @return bool
445 */
446 public function hasMasterChanges();
447
448 /**
449 * Get the timestamp of the latest write query done by this thread
450 * @return float|bool UNIX timestamp or false
451 */
452 public function lastMasterChangeTimestamp();
453
454 /**
455 * Check if this load balancer object had any recent or still
456 * pending writes issued against it by this PHP thread
457 *
458 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
459 * @return bool
460 */
461 public function hasOrMadeRecentMasterChanges( $age = null );
462
463 /**
464 * Get the list of callers that have pending master changes
465 *
466 * @return string[] List of method names
467 */
468 public function pendingMasterChangeCallers();
469
470 /**
471 * @note This method will trigger a DB connection if not yet done
472 * @param string|bool $domain Domain ID, or false for the current domain
473 * @return bool Whether the database for generic connections this request is highly "lagged"
474 */
475 public function getLaggedReplicaMode( $domain = false );
476
477 /**
478 * Checks whether the database for generic connections this request was both:
479 * - a) Already choosen due to a prior connection attempt
480 * - b) Considered highly "lagged"
481 *
482 * @note This method will never cause a new DB connection
483 * @return bool
484 */
485 public function laggedReplicaUsed();
486
487 /**
488 * @note This method may trigger a DB connection if not yet done
489 * @param string|bool $domain Domain ID, or false for the current domain
490 * @param IDatabase|null $conn DB master connection; used to avoid loops [optional]
491 * @return string|bool Reason the master is read-only or false if it is not
492 */
493 public function getReadOnlyReason( $domain = false, IDatabase $conn = null );
494
495 /**
496 * Disables/enables lag checks
497 * @param null|bool $mode
498 * @return bool
499 */
500 public function allowLagged( $mode = null );
501
502 /**
503 * @return bool
504 */
505 public function pingAll();
506
507 /**
508 * Call a function with each open connection object
509 * @param callable $callback
510 * @param array $params
511 */
512 public function forEachOpenConnection( $callback, array $params = [] );
513
514 /**
515 * Call a function with each open connection object to a master
516 * @param callable $callback
517 * @param array $params
518 */
519 public function forEachOpenMasterConnection( $callback, array $params = [] );
520
521 /**
522 * Call a function with each open replica DB connection object
523 * @param callable $callback
524 * @param array $params
525 */
526 public function forEachOpenReplicaConnection( $callback, array $params = [] );
527
528 /**
529 * Get the hostname and lag time of the most-lagged replica DB
530 *
531 * This is useful for maintenance scripts that need to throttle their updates.
532 * May attempt to open connections to replica DBs on the default DB. If there is
533 * no lag, the maximum lag will be reported as -1.
534 *
535 * @param bool|string $domain Domain ID, or false for the default database
536 * @return array ( host, max lag, index of max lagged host )
537 */
538 public function getMaxLag( $domain = false );
539
540 /**
541 * Get an estimate of replication lag (in seconds) for each server
542 *
543 * Results are cached for a short time in memcached/process cache
544 *
545 * Values may be "false" if replication is too broken to estimate
546 *
547 * @param string|bool $domain
548 * @return int[] Map of (server index => float|int|bool)
549 */
550 public function getLagTimes( $domain = false );
551
552 /**
553 * Get the lag in seconds for a given connection, or zero if this load
554 * balancer does not have replication enabled.
555 *
556 * This should be used in preference to Database::getLag() in cases where
557 * replication may not be in use, since there is no way to determine if
558 * replication is in use at the connection level without running
559 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
560 * function instead of Database::getLag() avoids a fatal error in this
561 * case on many installations.
562 *
563 * @param IDatabase $conn
564 * @return int|bool Returns false on error
565 */
566 public function safeGetLag( IDatabase $conn );
567
568 /**
569 * Wait for a replica DB to reach a specified master position
570 *
571 * This will connect to the master to get an accurate position if $pos is not given
572 *
573 * @param IDatabase $conn Replica DB
574 * @param DBMasterPos|bool $pos Master position; default: current position
575 * @param int $timeout Timeout in seconds [optional]
576 * @return bool Success
577 */
578 public function safeWaitForMasterPos( IDatabase $conn, $pos = false, $timeout = 10 );
579
580 /**
581 * Set a callback via IDatabase::setTransactionListener() on
582 * all current and future master connections of this load balancer
583 *
584 * @param string $name Callback name
585 * @param callable|null $callback
586 */
587 public function setTransactionListener( $name, callable $callback = null );
588
589 /**
590 * Set a new table prefix for the existing local domain ID for testing
591 *
592 * @param string $prefix
593 */
594 public function setDomainPrefix( $prefix );
595
596 /**
597 * Make certain table names use their own database, schema, and table prefix
598 * when passed into SQL queries pre-escaped and without a qualified database name
599 *
600 * For example, "user" can be converted to "myschema.mydbname.user" for convenience.
601 * Appearances like `user`, somedb.user, somedb.someschema.user will used literally.
602 *
603 * Calling this twice will completely clear any old table aliases. Also, note that
604 * callers are responsible for making sure the schemas and databases actually exist.
605 *
606 * @param array[] $aliases Map of (table => (dbname, schema, prefix) map)
607 */
608 public function setTableAliases( array $aliases );
609 }