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