3 * Database load balancing interface
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.
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.
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
22 * @author Aaron Schulz
24 namespace Wikimedia\Rdbms
;
29 use MaintainableDBConnRef
;
32 use DBTransactionError
;
35 use InvalidArgumentException
;
38 * Database cluster connection, tracking, load balancing, and transaction manager interface
40 * A "cluster" is considered to be one master database and zero or more replica databases.
41 * Typically, the replica DBs replicate from the master asynchronously. The first node in the
42 * "servers" configuration array is always considered the "master". However, this class can still
43 * be used when all or some of the "replica" DBs are multi-master peers of the master or even
44 * when all the DBs are non-replicating clones of each other holding read-only data. Thus, the
45 * role of "master" is in some cases merely nominal.
47 * By default, each DB server uses DBO_DEFAULT for its 'flags' setting, unless explicitly set
48 * otherwise in configuration. DBO_DEFAULT behavior depends on whether 'cliMode' is set:
49 * - In CLI mode, the flag has no effect with regards to LoadBalancer.
50 * - In non-CLI mode, the flag causes implicit transactions to be used; the first query on
51 * a database starts a transaction on that database. The transactions are meant to remain
52 * pending until either commitMasterChanges() or rollbackMasterChanges() is called. The
53 * application must have some point where it calls commitMasterChanges() near the end of
55 * Every iteration of beginMasterChanges()/commitMasterChanges() is called a "transaction round".
56 * Rounds are useful on the master DB connections because they make single-DB (and by and large
57 * multi-DB) updates in web requests all-or-nothing. Also, transactions on replica DBs are useful
58 * when REPEATABLE-READ or SERIALIZABLE isolation is used because all foriegn keys and constraints
59 * hold across separate queries in the DB transaction since the data appears within a consistent
60 * point-in-time snapshot.
62 * The typical caller will use LoadBalancer::getConnection( DB_* ) to yield a live database
63 * connection handle. The choice of which DB server to use is based on pre-defined loads for
64 * weighted random selection, adjustments thereof by LoadMonitor, and the amount of replication
65 * lag on each DB server. Lag checks might cause problems in certain setups, so they should be
66 * tuned in the server configuration maps as follows:
67 * - Master + N Replica(s): set 'max lag' to an appropriate threshold for avoiding any database
68 * lagged by this much or more. If all DBs are this lagged, then the load balancer considers
69 * the cluster to be read-only.
70 * - Galera Cluster: Seconds_Behind_Master will be 0, so there probably is nothing to tune.
71 * Note that lag is still possible depending on how wsrep-sync-wait is set server-side.
72 * - Read-only archive clones: set 'is static' in the server configuration maps. This will
73 * treat all such DBs as having 0 lag.
74 * - SQL load balancing proxy: any proxy should handle lag checks on its own, so the 'max lag'
75 * parameter should probably be set to INF in the server configuration maps. This will make
76 * the load balancer ignore whatever it detects as the lag of the logical replica is (which
77 * would probably just randomly bounce around).
79 * If using a SQL proxy service, it would probably be best to have two proxy hosts for the
80 * load balancer to talk to. One would be the 'host' of the master server entry and another for
81 * the (logical) replica server entry. The proxy could map the load balancer's "replica" DB to
82 * any number of physical replica DBs.
87 interface ILoadBalancer
{
88 /** @var integer Request a replica DB connection */
89 const DB_REPLICA
= -1;
90 /** @var integer Request a master DB connection */
93 /** @var string Domain specifier when no specific database needs to be selected */
94 const DOMAIN_ANY
= '';
97 * Construct a manager of IDatabase connection objects
99 * @param array $params Parameter map with keys:
100 * - servers : Required. Array of server info structures.
101 * - localDomain: A DatabaseDomain or domain ID string.
102 * - loadMonitor : Name of a class used to fetch server lag and load.
103 * - readOnlyReason : Reason the master DB is read-only if so [optional]
104 * - waitTimeout : Maximum time to wait for replicas for consistency [optional]
105 * - srvCache : BagOStuff object for server cache [optional]
106 * - memCache : BagOStuff object for cluster memory cache [optional]
107 * - wanCache : WANObjectCache object [optional]
108 * - hostname : The name of the current server [optional]
109 * - cliMode: Whether the execution context is a CLI script. [optional]
110 * - profiler : Class name or instance with profileIn()/profileOut() methods. [optional]
111 * - trxProfiler: TransactionProfiler instance. [optional]
112 * - replLogger: PSR-3 logger instance. [optional]
113 * - connLogger: PSR-3 logger instance. [optional]
114 * - queryLogger: PSR-3 logger instance. [optional]
115 * - perfLogger: PSR-3 logger instance. [optional]
116 * - errorLogger : Callback that takes an Exception and logs it. [optional]
117 * @throws InvalidArgumentException
119 public function __construct( array $params );
122 * Get the index of the reader connection, which may be a replica DB
124 * This takes into account load ratios and lag times. It should
125 * always return a consistent index during a given invocation.
127 * Side effect: opens connections to databases
128 * @param string|bool $group Query group, or false for the generic reader
129 * @param string|bool $domain Domain ID, or false for the current domain
131 * @return bool|int|string
133 public function getReaderIndex( $group = false, $domain = false );
136 * Set the master wait position
138 * If a DB_REPLICA connection has been opened already, then wait immediately.
139 * Otherwise sets a variable telling it to wait if such a connection is opened.
141 * @param DBMasterPos $pos
143 public function waitFor( $pos );
146 * Set the master wait position and wait for a "generic" replica DB to catch up to it
148 * This can be used a faster proxy for waitForAll()
150 * @param DBMasterPos $pos
151 * @param int $timeout Max seconds to wait; default is mWaitTimeout
152 * @return bool Success (able to connect and no timeouts reached)
154 public function waitForOne( $pos, $timeout = null );
157 * Set the master wait position and wait for ALL replica DBs to catch up to it
159 * @param DBMasterPos $pos
160 * @param int $timeout Max seconds to wait; default is mWaitTimeout
161 * @return bool Success (able to connect and no timeouts reached)
163 public function waitForAll( $pos, $timeout = null );
166 * Get any open connection to a given server index, local or foreign
168 * @param int $i Server index or DB_MASTER/DB_REPLICA
169 * @return Database|bool False if no such connection is open
171 public function getAnyOpenConnection( $i );
174 * Get a connection by index
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
183 public function getConnection( $i, $groups = [], $domain = false );
186 * Mark a foreign connection as being available for reuse under a different DB domain
188 * This mechanism is reference-counted, and must be called the same number of times
189 * as getConnection() to work.
191 * @param IDatabase $conn
192 * @throws InvalidArgumentException
194 public function reuseConnection( $conn );
197 * Get a database connection handle reference
199 * The handle's methods simply wrap those of a Database handle
201 * @see ILoadBalancer::getConnection() for parameter information
203 * @param int $i Server index or DB_MASTER/DB_REPLICA
204 * @param array|string|bool $groups Query group(s), or false for the generic reader
205 * @param string|bool $domain Domain ID, or false for the current domain
208 public function getConnectionRef( $i, $groups = [], $domain = false );
211 * Get a database connection handle reference without connecting yet
213 * The handle's methods simply wrap those of a Database handle
215 * @see ILoadBalancer::getConnection() for parameter information
217 * @param int $i Server index or DB_MASTER/DB_REPLICA
218 * @param array|string|bool $groups Query group(s), or false for the generic reader
219 * @param string|bool $domain Domain ID, or false for the current domain
222 public function getLazyConnectionRef( $i, $groups = [], $domain = false );
225 * Get a maintenance database connection handle reference for migrations and schema changes
227 * The handle's methods simply wrap those of a Database handle
229 * @see ILoadBalancer::getConnection() for parameter information
231 * @param int $db Server index or DB_MASTER/DB_REPLICA
232 * @param array|string|bool $groups Query group(s), or false for the generic reader
233 * @param string|bool $domain Domain ID, or false for the current domain
234 * @return MaintainableDBConnRef
236 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false );
239 * Open a connection to the server given by the specified index
240 * Index must be an actual index into the array.
241 * If the server is already open, returns it.
243 * On error, returns false, and the connection which caused the
244 * error will be available via $this->mErrorConnection.
246 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
248 * @param int $i Server index or DB_MASTER/DB_REPLICA
249 * @param string|bool $domain Domain ID, or false for the current domain
250 * @return Database|bool Returns false on errors
251 * @throws DBAccessError
253 public function openConnection( $i, $domain = false );
258 public function getWriterIndex();
261 * Returns true if the specified index is a valid server index
266 public function haveIndex( $i );
269 * Returns true if the specified index is valid and has non-zero load
274 public function isNonZeroLoad( $i );
277 * Get the number of defined servers (not the number of open connections)
281 public function getServerCount();
284 * Get the host name or IP address of the server with the specified index
285 * Prefer a readable name if available.
289 public function getServerName( $i );
292 * Return the server info structure for a given index, or false if the index is invalid.
296 public function getServerInfo( $i );
299 * Sets the server info structure for the given index. Entry at index $i
300 * is created if it doesn't exist
302 * @param array $serverInfo
304 public function setServerInfo( $i, array $serverInfo );
307 * Get the current master position for chronology control purposes
308 * @return DBMasterPos|bool Returns false if not applicable
310 public function getMasterPos();
313 * Disable this load balancer. All connections are closed, and any attempt to
314 * open a new connection will result in a DBAccessError.
316 public function disable();
319 * Close all open connections
321 public function closeAll();
326 * Using this function makes sure the LoadBalancer knows the connection is closed.
327 * If you use $conn->close() directly, the load balancer won't update its state.
329 * @param IDatabase $conn
331 public function closeConnection( IDatabase
$conn );
334 * Commit transactions on all open connections
335 * @param string $fname Caller name
336 * @throws DBExpectedError
338 public function commitAll( $fname = __METHOD__
);
341 * Perform all pre-commit callbacks that remain part of the atomic transactions
342 * and disable any post-commit callbacks until runMasterPostTrxCallbacks()
344 * Use this only for mutli-database commits
346 public function finalizeMasterChanges();
349 * Perform all pre-commit checks for things like replication safety
351 * Use this only for mutli-database commits
353 * @param array $options Includes:
354 * - maxWriteDuration : max write query duration time in seconds
355 * @throws DBTransactionError
357 public function approveMasterChanges( array $options );
360 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
362 * The DBO_TRX setting will be reverted to the default in each of these methods:
363 * - commitMasterChanges()
364 * - rollbackMasterChanges()
366 * This allows for custom transaction rounds from any outer transaction scope.
368 * @param string $fname
369 * @throws DBExpectedError
371 public function beginMasterChanges( $fname = __METHOD__
);
374 * Issue COMMIT on all master connections where writes where done
375 * @param string $fname Caller name
376 * @throws DBExpectedError
378 public function commitMasterChanges( $fname = __METHOD__
);
381 * Issue all pending post-COMMIT/ROLLBACK callbacks
383 * Use this only for mutli-database commits
385 * @param int $type IDatabase::TRIGGER_* constant
386 * @return Exception|null The first exception or null if there were none
388 public function runMasterPostTrxCallbacks( $type );
391 * Issue ROLLBACK only on master, only if queries were done on connection
392 * @param string $fname Caller name
393 * @throws DBExpectedError
395 public function rollbackMasterChanges( $fname = __METHOD__
);
398 * Suppress all pending post-COMMIT/ROLLBACK callbacks
400 * Use this only for mutli-database commits
402 * @return Exception|null The first exception or null if there were none
404 public function suppressTransactionEndCallbacks();
407 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
409 * @param string $fname Caller name
411 public function flushReplicaSnapshots( $fname = __METHOD__
);
414 * @return bool Whether a master connection is already open
416 public function hasMasterConnection();
419 * Determine if there are pending changes in a transaction by this thread
422 public function hasMasterChanges();
425 * Get the timestamp of the latest write query done by this thread
426 * @return float|bool UNIX timestamp or false
428 public function lastMasterChangeTimestamp();
431 * Check if this load balancer object had any recent or still
432 * pending writes issued against it by this PHP thread
434 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
437 public function hasOrMadeRecentMasterChanges( $age = null );
440 * Get the list of callers that have pending master changes
442 * @return string[] List of method names
444 public function pendingMasterChangeCallers();
447 * @note This method will trigger a DB connection if not yet done
448 * @param string|bool $domain Domain ID, or false for the current domain
449 * @return bool Whether the generic connection for reads is highly "lagged"
451 public function getLaggedReplicaMode( $domain = false );
454 * @note This method will never cause a new DB connection
455 * @return bool Whether any generic connection used for reads was highly "lagged"
457 public function laggedReplicaUsed();
460 * @note This method may trigger a DB connection if not yet done
461 * @param string|bool $domain Domain ID, or false for the current domain
462 * @param IDatabase|null $conn DB master connection; used to avoid loops [optional]
463 * @return string|bool Reason the master is read-only or false if it is not
465 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null );
468 * Disables/enables lag checks
469 * @param null|bool $mode
472 public function allowLagged( $mode = null );
477 public function pingAll();
480 * Call a function with each open connection object
481 * @param callable $callback
482 * @param array $params
484 public function forEachOpenConnection( $callback, array $params = [] );
487 * Call a function with each open connection object to a master
488 * @param callable $callback
489 * @param array $params
491 public function forEachOpenMasterConnection( $callback, array $params = [] );
494 * Call a function with each open replica DB connection object
495 * @param callable $callback
496 * @param array $params
498 public function forEachOpenReplicaConnection( $callback, array $params = [] );
501 * Get the hostname and lag time of the most-lagged replica DB
503 * This is useful for maintenance scripts that need to throttle their updates.
504 * May attempt to open connections to replica DBs on the default DB. If there is
505 * no lag, the maximum lag will be reported as -1.
507 * @param bool|string $domain Domain ID, or false for the default database
508 * @return array ( host, max lag, index of max lagged host )
510 public function getMaxLag( $domain = false );
513 * Get an estimate of replication lag (in seconds) for each server
515 * Results are cached for a short time in memcached/process cache
517 * Values may be "false" if replication is too broken to estimate
519 * @param string|bool $domain
520 * @return int[] Map of (server index => float|int|bool)
522 public function getLagTimes( $domain = false );
525 * Get the lag in seconds for a given connection, or zero if this load
526 * balancer does not have replication enabled.
528 * This should be used in preference to Database::getLag() in cases where
529 * replication may not be in use, since there is no way to determine if
530 * replication is in use at the connection level without running
531 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
532 * function instead of Database::getLag() avoids a fatal error in this
533 * case on many installations.
535 * @param IDatabase $conn
536 * @return int|bool Returns false on error
538 public function safeGetLag( IDatabase
$conn );
541 * Wait for a replica DB to reach a specified master position
543 * This will connect to the master to get an accurate position if $pos is not given
545 * @param IDatabase $conn Replica DB
546 * @param DBMasterPos|bool $pos Master position; default: current position
547 * @param int $timeout Timeout in seconds [optional]
548 * @return bool Success
550 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 );
553 * Set a callback via IDatabase::setTransactionListener() on
554 * all current and future master connections of this load balancer
556 * @param string $name Callback name
557 * @param callable|null $callback
559 public function setTransactionListener( $name, callable
$callback = null );
562 * Set a new table prefix for the existing local domain ID for testing
564 * @param string $prefix
566 public function setDomainPrefix( $prefix );
569 * Make certain table names use their own database, schema, and table prefix
570 * when passed into SQL queries pre-escaped and without a qualified database name
572 * For example, "user" can be converted to "myschema.mydbname.user" for convenience.
573 * Appearances like `user`, somedb.user, somedb.someschema.user will used literally.
575 * Calling this twice will completely clear any old table aliases. Also, note that
576 * callers are responsible for making sure the schemas and databases actually exist.
578 * @param array[] $aliases Map of (table => (dbname, schema, prefix) map)
580 public function setTableAliases( array $aliases );