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