Move ILoadBalancer to Rdbms namespace
[lhc/web/wiklou.git] / includes / libs / rdbms / lbfactory / ILBFactory.php
1 <?php
2 /**
3 * Generator and manager of database load balancing objects
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
24 namespace Wikimedia\Rdbms;
25
26 use InvalidArgumentException;
27 use LoadBalancer;
28 use DBTransactionError;
29 use DBReplicationWaitError;
30
31 /**
32 * An interface for generating database load balancers
33 * @ingroup Database
34 * @since 1.28
35 */
36 interface ILBFactory {
37 const SHUTDOWN_NO_CHRONPROT = 0; // don't save DB positions at all
38 const SHUTDOWN_CHRONPROT_ASYNC = 1; // save DB positions, but don't wait on remote DCs
39 const SHUTDOWN_CHRONPROT_SYNC = 2; // save DB positions, waiting on all DCs
40
41 /**
42 * Construct a manager of ILoadBalancer objects
43 *
44 * Sub-classes will extend the required keys in $conf with additional parameters
45 *
46 * @param $conf $params Array with keys:
47 * - localDomain: A DatabaseDomain or domain ID string.
48 * - readOnlyReason : Reason the master DB is read-only if so [optional]
49 * - srvCache : BagOStuff object for server cache [optional]
50 * - memCache : BagOStuff object for cluster memory cache [optional]
51 * - wanCache : WANObjectCache object [optional]
52 * - hostname : The name of the current server [optional]
53 * - cliMode: Whether the execution context is a CLI script. [optional]
54 * - profiler : Class name or instance with profileIn()/profileOut() methods. [optional]
55 * - trxProfiler: TransactionProfiler instance. [optional]
56 * - replLogger: PSR-3 logger instance. [optional]
57 * - connLogger: PSR-3 logger instance. [optional]
58 * - queryLogger: PSR-3 logger instance. [optional]
59 * - perfLogger: PSR-3 logger instance. [optional]
60 * - errorLogger : Callback that takes an Exception and logs it. [optional]
61 * @throws InvalidArgumentException
62 */
63 public function __construct( array $conf );
64
65 /**
66 * Disables all load balancers. All connections are closed, and any attempt to
67 * open a new connection will result in a DBAccessError.
68 * @see ILoadBalancer::disable()
69 */
70 public function destroy();
71
72 /**
73 * Create a new load balancer object. The resulting object will be untracked,
74 * not chronology-protected, and the caller is responsible for cleaning it up.
75 *
76 * This method is for only advanced usage and callers should almost always use
77 * getMainLB() instead. This method can be useful when a table is used as a key/value
78 * store. In that cases, one might want to query it in autocommit mode (DBO_TRX off)
79 * but still use DBO_TRX transaction rounds on other tables.
80 *
81 * @param bool|string $domain Domain ID, or false for the current domain
82 * @return ILoadBalancer
83 */
84 public function newMainLB( $domain = false );
85
86 /**
87 * Get a cached (tracked) load balancer object.
88 *
89 * @param bool|string $domain Domain ID, or false for the current domain
90 * @return ILoadBalancer
91 */
92 public function getMainLB( $domain = false );
93
94 /**
95 * Create a new load balancer for external storage. The resulting object will be
96 * untracked, not chronology-protected, and the caller is responsible for cleaning it up.
97 *
98 * This method is for only advanced usage and callers should almost always use
99 * getExternalLB() instead. This method can be useful when a table is used as a
100 * key/value store. In that cases, one might want to query it in autocommit mode
101 * (DBO_TRX off) but still use DBO_TRX transaction rounds on other tables.
102 *
103 * @param string $cluster External storage cluster name
104 * @return ILoadBalancer
105 */
106 public function newExternalLB( $cluster );
107
108 /**
109 * Get a cached (tracked) load balancer for external storage
110 *
111 * @param string $cluster External storage cluster name
112 * @return ILoadBalancer
113 */
114 public function getExternalLB( $cluster );
115
116 /**
117 * Get cached (tracked) load balancers for all main database clusters
118 *
119 * @return LoadBalancer[] Map of (cluster name => LoadBalancer)
120 * @since 1.29
121 */
122 public function getAllMainLBs();
123
124 /**
125 * Get cached (tracked) load balancers for all external database clusters
126 *
127 * @return LoadBalancer[] Map of (cluster name => LoadBalancer)
128 * @since 1.29
129 */
130 public function getAllExternalLBs();
131
132 /**
133 * Execute a function for each tracked load balancer
134 * The callback is called with the load balancer as the first parameter,
135 * and $params passed as the subsequent parameters.
136 *
137 * @param callable $callback
138 * @param array $params
139 */
140 public function forEachLB( $callback, array $params = [] );
141
142 /**
143 * Prepare all tracked load balancers for shutdown
144 * @param integer $mode One of the class SHUTDOWN_* constants
145 * @param callable|null $workCallback Work to mask ChronologyProtector writes
146 */
147 public function shutdown(
148 $mode = self::SHUTDOWN_CHRONPROT_SYNC, callable $workCallback = null
149 );
150
151 /**
152 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
153 *
154 * @param string $fname Caller name
155 */
156 public function flushReplicaSnapshots( $fname = __METHOD__ );
157
158 /**
159 * Commit open transactions on all connections. This is useful for two main cases:
160 * - a) To commit changes to the masters.
161 * - b) To release the snapshot on all connections, master and replica DBs.
162 * @param string $fname Caller name
163 * @param array $options Options map:
164 * - maxWriteDuration: abort if more than this much time was spent in write queries
165 */
166 public function commitAll( $fname = __METHOD__, array $options = [] );
167
168 /**
169 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
170 *
171 * The DBO_TRX setting will be reverted to the default in each of these methods:
172 * - commitMasterChanges()
173 * - rollbackMasterChanges()
174 * - commitAll()
175 *
176 * This allows for custom transaction rounds from any outer transaction scope.
177 *
178 * @param string $fname
179 * @throws DBTransactionError
180 */
181 public function beginMasterChanges( $fname = __METHOD__ );
182
183 /**
184 * Commit changes on all master connections
185 * @param string $fname Caller name
186 * @param array $options Options map:
187 * - maxWriteDuration: abort if more than this much time was spent in write queries
188 * @throws DBTransactionError
189 */
190 public function commitMasterChanges( $fname = __METHOD__, array $options = [] );
191
192 /**
193 * Rollback changes on all master connections
194 * @param string $fname Caller name
195 */
196 public function rollbackMasterChanges( $fname = __METHOD__ );
197
198 /**
199 * Determine if any master connection has pending changes
200 * @return bool
201 */
202 public function hasMasterChanges();
203
204 /**
205 * Detemine if any lagged replica DB connection was used
206 * @return bool
207 */
208 public function laggedReplicaUsed();
209
210 /**
211 * Determine if any master connection has pending/written changes from this request
212 * @param float $age How many seconds ago is "recent" [defaults to LB lag wait timeout]
213 * @return bool
214 */
215 public function hasOrMadeRecentMasterChanges( $age = null );
216
217 /**
218 * Waits for the replica DBs to catch up to the current master position
219 *
220 * Use this when updating very large numbers of rows, as in maintenance scripts,
221 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
222 *
223 * By default this waits on all DB clusters actually used in this request.
224 * This makes sense when lag being waiting on is caused by the code that does this check.
225 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
226 * that were not changed since the last wait check. To forcefully wait on a specific cluster
227 * for a given domain, use the 'domain' parameter. To forcefully wait on an "external" cluster,
228 * use the "cluster" parameter.
229 *
230 * Never call this function after a large DB write that is *still* in a transaction.
231 * It only makes sense to call this after the possible lag inducing changes were committed.
232 *
233 * @param array $opts Optional fields that include:
234 * - domain : wait on the load balancer DBs that handles the given domain ID
235 * - cluster : wait on the given external load balancer DBs
236 * - timeout : Max wait time. Default: ~60 seconds
237 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
238 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
239 */
240 public function waitForReplication( array $opts = [] );
241
242 /**
243 * Add a callback to be run in every call to waitForReplication() before waiting
244 *
245 * Callbacks must clear any transactions that they start
246 *
247 * @param string $name Callback name
248 * @param callable|null $callback Use null to unset a callback
249 */
250 public function setWaitForReplicationListener( $name, callable $callback = null );
251
252 /**
253 * Get a token asserting that no transaction writes are active
254 *
255 * @param string $fname Caller name (e.g. __METHOD__)
256 * @return mixed A value to pass to commitAndWaitForReplication()
257 */
258 public function getEmptyTransactionTicket( $fname );
259
260 /**
261 * Convenience method for safely running commitMasterChanges()/waitForReplication()
262 *
263 * This will commit and wait unless $ticket indicates it is unsafe to do so
264 *
265 * @param string $fname Caller name (e.g. __METHOD__)
266 * @param mixed $ticket Result of getEmptyTransactionTicket()
267 * @param array $opts Options to waitForReplication()
268 * @throws DBReplicationWaitError
269 */
270 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] );
271
272 /**
273 * @param string $dbName DB master name (e.g. "db1052")
274 * @return float|bool UNIX timestamp when client last touched the DB or false if not recent
275 */
276 public function getChronologyProtectorTouched( $dbName );
277
278 /**
279 * Disable the ChronologyProtector for all load balancers
280 *
281 * This can be called at the start of special API entry points
282 */
283 public function disableChronologyProtection();
284
285 /**
286 * Set a new table prefix for the existing local domain ID for testing
287 *
288 * @param string $prefix
289 */
290 public function setDomainPrefix( $prefix );
291
292 /**
293 * Close all open database connections on all open load balancers.
294 */
295 public function closeAll();
296
297 /**
298 * @param string $agent Agent name for query profiling
299 */
300 public function setAgentName( $agent );
301
302 /**
303 * Append ?cpPosTime parameter to a URL for ChronologyProtector purposes if needed
304 *
305 * Note that unlike cookies, this works accross domains
306 *
307 * @param string $url
308 * @param float $time UNIX timestamp just before shutdown() was called
309 * @return string
310 */
311 public function appendPreShutdownTimeAsQuery( $url, $time );
312
313 /**
314 * @param array $info Map of fields, including:
315 * - IPAddress : IP address
316 * - UserAgent : User-Agent HTTP header
317 * - ChronologyProtection : cookie/header value specifying ChronologyProtector usage
318 */
319 public function setRequestInfo( array $info );
320 }