Merge "Add .pipeline/ with dev image variant"
[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 LogicException;
27 use InvalidArgumentException;
28
29 /**
30 * Database cluster connection, tracking, load balancing, and transaction manager interface
31 *
32 * A "cluster" is considered to be one master database and zero or more replica databases.
33 * Typically, the replica DBs replicate from the master asynchronously. The first node in the
34 * "servers" configuration array is always considered the "master". However, this class can still
35 * be used when all or some of the "replica" DBs are multi-master peers of the master or even
36 * when all the DBs are non-replicating clones of each other holding read-only data. Thus, the
37 * role of "master" is in some cases merely nominal.
38 *
39 * By default, each DB server uses DBO_DEFAULT for its 'flags' setting, unless explicitly set
40 * otherwise in configuration. DBO_DEFAULT behavior depends on whether 'cliMode' is set:
41 * - In CLI mode, the flag has no effect with regards to LoadBalancer.
42 * - In non-CLI mode, the flag causes implicit transactions to be used; the first query on
43 * a database starts a transaction on that database. The transactions are meant to remain
44 * pending until either commitMasterChanges() or rollbackMasterChanges() is called. The
45 * application must have some point where it calls commitMasterChanges() near the end of
46 * the PHP request.
47 * Every iteration of beginMasterChanges()/commitMasterChanges() is called a "transaction round".
48 * Rounds are useful on the master DB connections because they make single-DB (and by and large
49 * multi-DB) updates in web requests all-or-nothing. Also, transactions on replica DBs are useful
50 * when REPEATABLE-READ or SERIALIZABLE isolation is used because all foriegn keys and constraints
51 * hold across separate queries in the DB transaction since the data appears within a consistent
52 * point-in-time snapshot.
53 *
54 * The typical caller will use LoadBalancer::getConnection( DB_* ) to yield a live database
55 * connection handle. The choice of which DB server to use is based on pre-defined loads for
56 * weighted random selection, adjustments thereof by LoadMonitor, and the amount of replication
57 * lag on each DB server. Lag checks might cause problems in certain setups, so they should be
58 * tuned in the server configuration maps as follows:
59 * - Master + N Replica(s): set 'max lag' to an appropriate threshold for avoiding any database
60 * lagged by this much or more. If all DBs are this lagged, then the load balancer considers
61 * the cluster to be read-only.
62 * - Galera Cluster: Seconds_Behind_Master will be 0, so there probably is nothing to tune.
63 * Note that lag is still possible depending on how wsrep-sync-wait is set server-side.
64 * - Read-only archive clones: set 'is static' in the server configuration maps. This will
65 * treat all such DBs as having 0 lag.
66 * - Externally updated dataset clones: set 'is static' in the server configuration maps.
67 * This will treat all such DBs as having 0 lag.
68 * - SQL load balancing proxy: any proxy should handle lag checks on its own, so the 'max lag'
69 * parameter should probably be set to INF in the server configuration maps. This will make
70 * the load balancer ignore whatever it detects as the lag of the logical replica is (which
71 * would probably just randomly bounce around).
72 *
73 * If using a SQL proxy service, it would probably be best to have two proxy hosts for the
74 * load balancer to talk to. One would be the 'host' of the master server entry and another for
75 * the (logical) replica server entry. The proxy could map the load balancer's "replica" DB to
76 * any number of physical replica DBs.
77 *
78 * @since 1.28
79 * @ingroup Database
80 */
81 interface ILoadBalancer {
82 /** @var int Request a replica DB connection */
83 const DB_REPLICA = -1;
84 /** @var int Request a master DB connection */
85 const DB_MASTER = -2;
86
87 /** @var string Domain specifier when no specific database needs to be selected */
88 const DOMAIN_ANY = '';
89 /** @var string The generic query group */
90 const GROUP_GENERIC = '';
91
92 /** @var int DB handle should have DBO_TRX disabled and the caller will leave it as such */
93 const CONN_TRX_AUTOCOMMIT = 1;
94 /** @var int Return null on connection failure instead of throwing an exception */
95 const CONN_SILENCE_ERRORS = 2;
96 /** @var int Caller is requesting the master DB server for possibly writes */
97 const CONN_INTENT_WRITABLE = 4;
98 /** @var int Bypass and update any server-side read-only mode state cache */
99 const CONN_REFRESH_READ_ONLY = 8;
100
101 /** @var string Manager of ILoadBalancer instances is running post-commit callbacks */
102 const STAGE_POSTCOMMIT_CALLBACKS = 'stage-postcommit-callbacks';
103 /** @var string Manager of ILoadBalancer instances is running post-rollback callbacks */
104 const STAGE_POSTROLLBACK_CALLBACKS = 'stage-postrollback-callbacks';
105
106 /**
107 * Construct a manager of IDatabase connection objects
108 *
109 * @param array $params Parameter map with keys:
110 * - servers : List of server info structures
111 * - localDomain: A DatabaseDomain or domain ID string
112 * - loadMonitor : Name of a class used to fetch server lag and load
113 * - readOnlyReason : Reason the master DB is read-only if so [optional]
114 * - waitTimeout : Maximum time to wait for replicas for consistency [optional]
115 * - maxLag: Try to avoid DB replicas with lag above this many seconds [optional]
116 * - srvCache : BagOStuff object for server cache [optional]
117 * - wanCache : WANObjectCache object [optional]
118 * - chronologyCallback: Callback to run before the first connection attempt [optional]
119 * - defaultGroup: Default query group; the generic group if not specified [optional]
120 * - hostname : The name of the current server [optional]
121 * - cliMode: Whether the execution context is a CLI script [optional]
122 * - profiler : Class name or instance with profileIn()/profileOut() methods [optional]
123 * - trxProfiler: TransactionProfiler instance [optional]
124 * - replLogger: PSR-3 logger instance [optional]
125 * - connLogger: PSR-3 logger instance [optional]
126 * - queryLogger: PSR-3 logger instance [optional]
127 * - perfLogger: PSR-3 logger instance [optional]
128 * - errorLogger : Callback that takes an Exception and logs it [optional]
129 * - deprecationLogger: Callback to log a deprecation warning [optional]
130 * - roundStage: STAGE_POSTCOMMIT_* class constant; for internal use [optional]
131 * - ownerId: integer ID of an LBFactory instance that manages this instance [optional]
132 * @throws InvalidArgumentException
133 */
134 public function __construct( array $params );
135
136 /**
137 * Get the local (and default) database domain ID of connection handles
138 *
139 * @see DatabaseDomain
140 * @return string Database domain ID; this specifies DB name, schema, and table prefix
141 * @since 1.31
142 */
143 public function getLocalDomainID();
144
145 /**
146 * @param DatabaseDomain|string|bool $domain Database domain
147 * @return string Value of $domain if it is foreign or the local domain otherwise
148 * @since 1.32
149 */
150 public function resolveDomainID( $domain );
151
152 /**
153 * Close all connection and redefine the local domain for testing or schema creation
154 *
155 * @param DatabaseDomain|string $domain
156 * @since 1.33
157 */
158 public function redefineLocalDomain( $domain );
159
160 /**
161 * Indicate whether the tables on this domain are only temporary tables for testing
162 *
163 * In "temporary tables mode", the ILoadBalancer::CONN_TRX_AUTOCOMMIT flag is ignored
164 *
165 * @param bool $value
166 * @param string $domain
167 * @return bool Whether "temporary tables mode" was active
168 * @since 1.34
169 */
170 public function setTempTablesOnlyMode( $value, $domain );
171
172 /**
173 * Get the server index of the reader connection for a given group
174 *
175 * This takes into account load ratios and lag times. It should return a consistent
176 * index during the life time of the load balancer. This initially checks replica DBs
177 * for connectivity to avoid returning an unusable server. This means that connections
178 * might be attempted by calling this method (usally one at the most but possibly more).
179 * Subsequent calls with the same $group will not need to make new connection attempts
180 * since the acquired connection for each group is preserved.
181 *
182 * @param string|bool $group Query group or false for the generic group
183 * @param string|bool $domain DB domain ID or false for the local domain
184 * @return int|bool Returns false if no live handle can be obtained
185 */
186 public function getReaderIndex( $group = false, $domain = false );
187
188 /**
189 * Set the master position to reach before the next generic group DB handle query
190 *
191 * If a generic replica DB connection is already open then this immediately waits
192 * for that DB to catch up to the specified replication position. Otherwise, it will
193 * do so once such a connection is opened.
194 *
195 * If a timeout happens when waiting, then getLaggedReplicaMode()/laggedReplicaUsed()
196 * will return true.
197 *
198 * @param DBMasterPos|bool $pos Master position or false
199 */
200 public function waitFor( $pos );
201
202 /**
203 * Set the master wait position and wait for a generic replica DB to catch up to it
204 *
205 * This can be used a faster proxy for waitForAll()
206 *
207 * @param DBMasterPos|bool $pos Master position or false
208 * @param int|null $timeout Max seconds to wait; default is mWaitTimeout
209 * @return bool Success (able to connect and no timeouts reached)
210 */
211 public function waitForOne( $pos, $timeout = null );
212
213 /**
214 * Set the master wait position and wait for ALL replica DBs to catch up to it
215 *
216 * @param DBMasterPos|bool $pos Master position or false
217 * @param int|null $timeout Max seconds to wait; default is mWaitTimeout
218 * @return bool Success (able to connect and no timeouts reached)
219 */
220 public function waitForAll( $pos, $timeout = null );
221
222 /**
223 * Get any open connection to a given server index, local or foreign
224 *
225 * Use CONN_TRX_AUTOCOMMIT to only look for connections opened with that flag.
226 * Avoid the use of transaction methods like IDatabase::begin() or IDatabase::startAtomic()
227 * on any such connections.
228 *
229 * @param int $i Server index or DB_MASTER/DB_REPLICA
230 * @param int $flags Bitfield of CONN_* class constants
231 * @return Database|bool False if no such connection is open
232 */
233 public function getAnyOpenConnection( $i, $flags = 0 );
234
235 /**
236 * Get a live handle for a real or virtual (DB_MASTER/DB_REPLICA) server index
237 *
238 * The server index, $i, can be one of the following:
239 * - DB_REPLICA: a server index will be selected by the load balancer based on read
240 * weight, connectivity, and replication lag. Note that the master server might be
241 * configured with read weight. If $groups is empty then it means "the generic group",
242 * in which case all servers defined with read weight will be considered. Additional
243 * query groups can be configured, having their own list of server indexes and read
244 * weights. If a query group list is provided in $groups, then each recognized group
245 * will be tried, left-to-right, until server index selection succeeds or all groups
246 * have been tried, in which case the generic group will be tried.
247 * - DB_MASTER: the master server index will be used; the same as getWriterIndex().
248 * The value of $groups should be [] when using this server index.
249 * - Specific server index: a positive integer can be provided to use the server with
250 * that index. An error will be thrown in no such server index is recognized. This
251 * server selection method is usually only useful for internal load balancing logic.
252 * The value of $groups should be [] when using a specific server index.
253 *
254 * Handles acquired by this method, getConnectionRef(), getLazyConnectionRef(), and
255 * getMaintenanceConnectionRef() use the same set of shared connection pools. Callers that
256 * get a *local* DB domain handle for the same server will share one handle for all of those
257 * callers using CONN_TRX_AUTOCOMMIT (via $flags) and one handle for all of those callers not
258 * using CONN_TRX_AUTOCOMMIT. Callers that get a *foreign* DB domain handle (via $domain) will
259 * share any handle that has the right CONN_TRX_AUTOCOMMIT mode and is already on the right
260 * DB domain. Otherwise, one of the "free for reuse" handles will be claimed or a new handle
261 * will be made if there are none.
262 *
263 * Handle sharing is particularly useful when callers get local DB domain (the default),
264 * transaction round aware (the default), DB_MASTER handles. All such callers will operate
265 * within a single database transaction as a consequence. Handle sharing is also useful when
266 * callers get local DB domain (the default), transaction round aware (the default), samely
267 * query grouped (the default), DB_REPLICA handles. All such callers will operate within a
268 * single database transaction as a consequence.
269 *
270 * Calling functions that use $domain must call reuseConnection() once the last query of the
271 * function is executed. This lets the load balancer share this handle with other callers
272 * requesting connections on different database domains.
273 *
274 * Use CONN_TRX_AUTOCOMMIT to use a separate pool of only auto-commit handles. This flag
275 * is ignored for databases with ATTR_DB_LEVEL_LOCKING (e.g. sqlite) in order to avoid
276 * deadlocks. getServerAttributes() can be used to check such attributes beforehand. Avoid
277 * using IDatabase::begin() and IDatabase::commit() on such handles. If it is not possible
278 * to avoid using methods like IDatabase::startAtomic() and IDatabase::endAtomic(), callers
279 * should at least make sure that the atomic sections are closed on failure via try/catch
280 * and IDatabase::cancelAtomic().
281 *
282 * @see ILoadBalancer::reuseConnection()
283 * @see ILoadBalancer::getServerAttributes()
284 *
285 * @param int $i Server index (overrides $groups) or DB_MASTER/DB_REPLICA
286 * @param string[]|string $groups Query group(s) in preference order; [] for the default group
287 * @param string|bool $domain DB domain ID or false for the local domain
288 * @param int $flags Bitfield of CONN_* class constants
289 *
290 * @note This method throws DBAccessError if ILoadBalancer::disable() was called
291 *
292 * @return IDatabase|bool This returns false on failure if CONN_SILENCE_ERRORS is set
293 * @throws DBError If no live handle can be obtained and CONN_SILENCE_ERRORS is not set
294 * @throws DBAccessError If disable() was previously called
295 * @throws InvalidArgumentException
296 */
297 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 );
298
299 /**
300 * Get a live handle for a server index
301 *
302 * This is a simpler version of getConnection() that does not accept virtual server
303 * indexes (e.g. DB_MASTER/DB_REPLICA), does not assure that master DB handles have
304 * read-only mode when there is high replication lag, and can only trigger attempts
305 * to connect to a single server (the one with the specified server index).
306 *
307 * @see ILoadBalancer::getConnection()
308 *
309 * @param int $i Specific server index
310 * @param string $domain Resolved DB domain
311 * @param int $flags Bitfield of class CONN_* constants
312 * @return IDatabase|bool
313 */
314 public function getServerConnection( $i, $domain, $flags = 0 );
315
316 /**
317 * Mark a live handle as being available for reuse under a different database domain
318 *
319 * This mechanism is reference-counted, and must be called the same number of times as
320 * getConnection() to work. Never call this on handles acquired via getConnectionRef(),
321 * getLazyConnectionRef(), and getMaintenanceConnectionRef(), as they already manage
322 * the logic of calling this method when they fall out of scope in PHP.
323 *
324 * @see ILoadBalancer::getConnection()
325 *
326 * @param IDatabase $conn
327 * @throws LogicException
328 */
329 public function reuseConnection( IDatabase $conn );
330
331 /**
332 * Get a live database handle reference for a real or virtual (DB_MASTER/DB_REPLICA) server index
333 *
334 * The CONN_TRX_AUTOCOMMIT flag is ignored for databases with ATTR_DB_LEVEL_LOCKING
335 * (e.g. sqlite) in order to avoid deadlocks. getServerAttributes()
336 * can be used to check such flags beforehand. Avoid the use of begin() or startAtomic()
337 * on any CONN_TRX_AUTOCOMMIT connections.
338 *
339 * @see ILoadBalancer::getConnection() for parameter information
340 *
341 * @param int $i Server index or DB_MASTER/DB_REPLICA
342 * @param string[]|string $groups Query group(s) in preference order; [] for the default group
343 * @param string|bool $domain DB domain ID or false for the local domain
344 * @param int $flags Bitfield of CONN_* class constants (e.g. CONN_TRX_AUTOCOMMIT)
345 * @return DBConnRef
346 */
347 public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 );
348
349 /**
350 * Get a database handle reference for a real or virtual (DB_MASTER/DB_REPLICA) server index
351 *
352 * The handle's methods simply proxy to those of an underlying IDatabase handle which
353 * takes care of the actual connection and query logic.
354 *
355 * The CONN_TRX_AUTOCOMMIT flag is ignored for databases with ATTR_DB_LEVEL_LOCKING
356 * (e.g. sqlite) in order to avoid deadlocks. getServerAttributes()
357 * can be used to check such flags beforehand. Avoid the use of begin() or startAtomic()
358 * on any CONN_TRX_AUTOCOMMIT connections.
359 *
360 * @see ILoadBalancer::getConnection() for parameter information
361 *
362 * @param int $i Server index or DB_MASTER/DB_REPLICA
363 * @param string[]|string $groups Query group(s) in preference order; [] for the default group
364 * @param string|bool $domain DB domain ID or false for the local domain
365 * @param int $flags Bitfield of CONN_* class constants (e.g. CONN_TRX_AUTOCOMMIT)
366 * @return DBConnRef
367 */
368 public function getLazyConnectionRef( $i, $groups = [], $domain = false, $flags = 0 );
369
370 /**
371 * Get a live database handle for a real or virtual (DB_MASTER/DB_REPLICA) server index
372 * that can be used for data migrations and schema changes
373 *
374 * The handle's methods simply proxy to those of an underlying IDatabase handle which
375 * takes care of the actual connection and query logic.
376 *
377 * The CONN_TRX_AUTOCOMMIT flag is ignored for databases with ATTR_DB_LEVEL_LOCKING
378 * (e.g. sqlite) in order to avoid deadlocks. getServerAttributes()
379 * can be used to check such flags beforehand. Avoid the use of begin() or startAtomic()
380 * on any CONN_TRX_AUTOCOMMIT connections.
381 *
382 * @see ILoadBalancer::getConnection() for parameter information
383 *
384 * @param int $i Server index or DB_MASTER/DB_REPLICA
385 * @param string[]|string $groups Query group(s) in preference order; [] for the default group
386 * @param string|bool $domain DB domain ID or false for the local domain
387 * @param int $flags Bitfield of CONN_* class constants (e.g. CONN_TRX_AUTOCOMMIT)
388 * @return MaintainableDBConnRef
389 */
390 public function getMaintenanceConnectionRef( $i, $groups = [], $domain = false, $flags = 0 );
391
392 /**
393 * Get the server index of the master server
394 *
395 * @return int
396 */
397 public function getWriterIndex();
398
399 /**
400 * Get the number of servers defined in configuration
401 *
402 * @return int
403 */
404 public function getServerCount();
405
406 /**
407 * Whether there are any replica servers configured
408 *
409 * This counts both servers using streaming replication from the master server and
410 * servers that just have a clone of the static dataset found on the master server
411 *
412 * @return int
413 * @since 1.34
414 */
415 public function hasReplicaServers();
416
417 /**
418 * Whether any replica servers use streaming replication from the master server
419 *
420 * Generally this is one less than getServerCount(), though it might otherwise
421 * return a lower number if some of the servers are configured with "is static".
422 * That flag is used when both the server has no active replication setup and the
423 * dataset is either read-only or occasionally updated out-of-band. For example,
424 * a script might import a new geographic information dataset each week by writing
425 * it to each server and later directing the application to use the new version.
426 *
427 * It is possible for some replicas to be configured with "is static" but not
428 * others, though it generally should either be set for all or none of the replicas.
429 *
430 * If this returns zero, this means that there is generally no reason to execute
431 * replication wait logic for session consistency and lag reduction.
432 *
433 * @return int
434 * @since 1.34
435 */
436 public function hasStreamingReplicaServers();
437
438 /**
439 * Get the host name or IP address of the server with the specified index
440 *
441 * @param int $i
442 * @return string Readable name if available or IP/host otherwise
443 */
444 public function getServerName( $i );
445
446 /**
447 * Return the server info structure for a given index or false if the index is invalid.
448 * @param int $i
449 * @return array|bool
450 * @since 1.31
451 */
452 public function getServerInfo( $i );
453
454 /**
455 * Get DB type of the server with the specified index
456 *
457 * @param int $i
458 * @return string One of (mysql,postgres,sqlite,...) or "unknown" for bad indexes
459 * @since 1.30
460 */
461 public function getServerType( $i );
462
463 /**
464 * @param int $i Server index
465 * @return array (Database::ATTRIBUTE_* constant => value) for all such constants
466 * @since 1.31
467 */
468 public function getServerAttributes( $i );
469
470 /**
471 * Get the current master replication position
472 *
473 * @return DBMasterPos|bool Returns false if not applicable
474 * @throws DBError
475 */
476 public function getMasterPos();
477
478 /**
479 * Get the highest DB replication position for chronology control purposes
480 *
481 * If there is only a master server then this returns false. If replication is present
482 * and correctly configured, then this returns the highest replication position of any
483 * server with an open connection. That position can later be passed to waitFor() on a
484 * new load balancer instance to make sure that queries on the new connections see data
485 * at least as up-to-date as queries (prior to this method call) on the old connections.
486 *
487 * This can be useful for implementing session consistency, where the session
488 * will be resumed accross multiple HTTP requests or CLI script instances.
489 *
490 * @return DBMasterPos|bool Replication position or false if not applicable
491 * @since 1.34
492 */
493 public function getReplicaResumePos();
494
495 /**
496 * Close all connections and disable this load balancer
497 *
498 * Any attempt to open a new connection will result in a DBAccessError.
499 *
500 * @param string $fname Caller name
501 * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
502 */
503 public function disable( $fname = __METHOD__, $owner = null );
504
505 /**
506 * Close all open connections
507 *
508 * @param string $fname Caller name
509 * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
510 */
511 public function closeAll( $fname = __METHOD__, $owner = null );
512
513 /**
514 * Close a connection
515 *
516 * Using this function makes sure the LoadBalancer knows the connection is closed.
517 * If you use $conn->close() directly, the load balancer won't update its state.
518 *
519 * @param IDatabase $conn
520 */
521 public function closeConnection( IDatabase $conn );
522
523 /**
524 * Commit transactions on all open connections
525 * @param string $fname Caller name
526 * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
527 * @throws DBExpectedError
528 */
529 public function commitAll( $fname = __METHOD__, $owner = null );
530
531 /**
532 * Run pre-commit callbacks and defer execution of post-commit callbacks
533 *
534 * Use this only for mutli-database commits
535 *
536 * @param string $fname Caller name
537 * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
538 * @return int Number of pre-commit callbacks run (since 1.32)
539 */
540 public function finalizeMasterChanges( $fname = __METHOD__, $owner = null );
541
542 /**
543 * Perform all pre-commit checks for things like replication safety
544 *
545 * Use this only for mutli-database commits
546 *
547 * @param array $options Includes:
548 * - maxWriteDuration : max write query duration time in seconds
549 * @param string $fname Caller name
550 * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
551 * @throws DBTransactionError
552 */
553 public function approveMasterChanges( array $options, $fname, $owner = null );
554
555 /**
556 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
557 *
558 * The DBO_TRX setting will be reverted to the default in each of these methods:
559 * - commitMasterChanges()
560 * - rollbackMasterChanges()
561 * - commitAll()
562 * This allows for custom transaction rounds from any outer transaction scope.
563 *
564 * @param string $fname Caller name
565 * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
566 * @throws DBExpectedError
567 */
568 public function beginMasterChanges( $fname = __METHOD__, $owner = null );
569
570 /**
571 * Issue COMMIT on all open master connections to flush changes and view snapshots
572 * @param string $fname Caller name
573 * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
574 * @throws DBExpectedError
575 */
576 public function commitMasterChanges( $fname = __METHOD__, $owner = null );
577
578 /**
579 * Consume and run all pending post-COMMIT/ROLLBACK callbacks and commit dangling transactions
580 *
581 * @param string $fname Caller name
582 * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
583 * @return Exception|null The first exception or null if there were none
584 */
585 public function runMasterTransactionIdleCallbacks( $fname = __METHOD__, $owner = null );
586
587 /**
588 * Run all recurring post-COMMIT/ROLLBACK listener callbacks
589 *
590 * @param string $fname Caller name
591 * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
592 * @return Exception|null The first exception or null if there were none
593 */
594 public function runMasterTransactionListenerCallbacks( $fname = __METHOD__, $owner = null );
595
596 /**
597 * Issue ROLLBACK only on master, only if queries were done on connection
598 * @param string $fname Caller name
599 * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
600 * @throws DBExpectedError
601 */
602 public function rollbackMasterChanges( $fname = __METHOD__, $owner = null );
603
604 /**
605 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshots
606 *
607 * @param string $fname Caller name
608 * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
609 */
610 public function flushReplicaSnapshots( $fname = __METHOD__, $owner = null );
611
612 /**
613 * Commit all master DB transactions so as to flush any REPEATABLE-READ or SSI snapshots
614 *
615 * An error will be thrown if a connection has pending writes or callbacks
616 *
617 * @param string $fname Caller name
618 * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID)
619 */
620 public function flushMasterSnapshots( $fname = __METHOD__, $owner = null );
621
622 /**
623 * @return bool Whether a master connection is already open
624 */
625 public function hasMasterConnection();
626
627 /**
628 * Whether there are pending changes or callbacks in a transaction by this thread
629 * @return bool
630 */
631 public function hasMasterChanges();
632
633 /**
634 * Get the timestamp of the latest write query done by this thread
635 * @return float|bool UNIX timestamp or false
636 */
637 public function lastMasterChangeTimestamp();
638
639 /**
640 * Check if this load balancer object had any recent or still
641 * pending writes issued against it by this PHP thread
642 *
643 * @param float|null $age How many seconds ago is "recent" [defaults to mWaitTimeout]
644 * @return bool
645 */
646 public function hasOrMadeRecentMasterChanges( $age = null );
647
648 /**
649 * Get the list of callers that have pending master changes
650 *
651 * @return string[] List of method names
652 */
653 public function pendingMasterChangeCallers();
654
655 /**
656 * @note This method will trigger a DB connection if not yet done
657 * @param string|bool $domain DB domain ID or false for the local domain
658 * @return bool Whether the database for generic connections this request is highly "lagged"
659 */
660 public function getLaggedReplicaMode( $domain = false );
661
662 /**
663 * Checks whether the database for generic connections this request was both:
664 * - a) Already choosen due to a prior connection attempt
665 * - b) Considered highly "lagged"
666 *
667 * @note This method will never cause a new DB connection
668 * @return bool
669 */
670 public function laggedReplicaUsed();
671
672 /**
673 * @note This method may trigger a DB connection if not yet done
674 * @param string|bool $domain DB domain ID or false for the local domain
675 * @return string|bool Reason the master is read-only or false if it is not
676 */
677 public function getReadOnlyReason( $domain = false );
678
679 /**
680 * Disables/enables lag checks
681 * @param null|bool $mode
682 * @return bool
683 */
684 public function allowLagged( $mode = null );
685
686 /**
687 * @return bool
688 */
689 public function pingAll();
690
691 /**
692 * Call a function with each open connection object
693 * @param callable $callback
694 * @param array $params
695 */
696 public function forEachOpenConnection( $callback, array $params = [] );
697
698 /**
699 * Call a function with each open connection object to a master
700 * @param callable $callback
701 * @param array $params
702 */
703 public function forEachOpenMasterConnection( $callback, array $params = [] );
704
705 /**
706 * Call a function with each open replica DB connection object
707 * @param callable $callback
708 * @param array $params
709 */
710 public function forEachOpenReplicaConnection( $callback, array $params = [] );
711
712 /**
713 * Get the hostname and lag time of the most-lagged replica server
714 *
715 * This is useful for maintenance scripts that need to throttle their updates.
716 * May attempt to open connections to replica DBs on the default DB. If there is
717 * no lag, the maximum lag will be reported as -1.
718 *
719 * @param bool|string $domain Domain ID or false for the default database
720 * @return array ( host, max lag, index of max lagged host )
721 */
722 public function getMaxLag( $domain = false );
723
724 /**
725 * Get an estimate of replication lag (in seconds) for each server
726 *
727 * Results are cached for a short time in memcached/process cache
728 *
729 * Values may be "false" if replication is too broken to estimate
730 *
731 * @param string|bool $domain
732 * @return int[] Map of (server index => float|int|bool)
733 */
734 public function getLagTimes( $domain = false );
735
736 /**
737 * Wait for a replica DB to reach a specified master position
738 *
739 * If $conn is not a replica server connection, then this will return true.
740 * Otherwise, if $pos is not provided, this will connect to the master server
741 * to get an accurate position.
742 *
743 * @param IDatabase $conn Replica DB
744 * @param DBMasterPos|bool $pos Master position; default: current position
745 * @param int $timeout Timeout in seconds [optional]
746 * @return bool Success
747 * @since 1.34
748 */
749 public function waitForMasterPos( IDatabase $conn, $pos = false, $timeout = 10 );
750
751 /**
752 * Set a callback via IDatabase::setTransactionListener() on
753 * all current and future master connections of this load balancer
754 *
755 * @param string $name Callback name
756 * @param callable|null $callback
757 */
758 public function setTransactionListener( $name, callable $callback = null );
759
760 /**
761 * Set a new table prefix for the existing local domain ID for testing
762 *
763 * @param string $prefix
764 * @since 1.33
765 */
766 public function setLocalDomainPrefix( $prefix );
767
768 /**
769 * Make certain table names use their own database, schema, and table prefix
770 * when passed into SQL queries pre-escaped and without a qualified database name
771 *
772 * For example, "user" can be converted to "myschema.mydbname.user" for convenience.
773 * Appearances like `user`, somedb.user, somedb.someschema.user will used literally.
774 *
775 * Calling this twice will completely clear any old table aliases. Also, note that
776 * callers are responsible for making sure the schemas and databases actually exist.
777 *
778 * @param array[] $aliases Map of (table => (dbname, schema, prefix) map)
779 */
780 public function setTableAliases( array $aliases );
781
782 /**
783 * Convert certain index names to alternative names before querying the DB
784 *
785 * Note that this applies to indexes regardless of the table they belong to.
786 *
787 * This can be employed when an index was renamed X => Y in code, but the new Y-named
788 * indexes were not yet built on all DBs. After all the Y-named ones are added by the DBA,
789 * the aliases can be removed, and then the old X-named indexes dropped.
790 *
791 * @param string[] $aliases
792 * @since 1.31
793 */
794 public function setIndexAliases( array $aliases );
795 }