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