Merge "Chinese Conversion Table Update 2016-3"
[lhc/web/wiklou.git] / includes / objectcache / ObjectCache.php
1 <?php
2 /**
3 * Functions to get cache 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 Cache
22 */
23
24 use MediaWiki\Logger\LoggerFactory;
25 use MediaWiki\MediaWikiServices;
26 use MediaWiki\Services\ServiceDisabledException;
27
28 /**
29 * Functions to get cache objects
30 *
31 * The word "cache" has two main dictionary meanings, and both
32 * are used in this factory class. They are:
33 *
34 * - a) Cache (the computer science definition).
35 * A place to store copies or computations on existing data for
36 * higher access speeds.
37 * - b) Storage.
38 * A place to store lightweight data that is not canonically
39 * stored anywhere else (e.g. a "hoard" of objects).
40 *
41 * The former should always use strongly consistent stores, so callers don't
42 * have to deal with stale reads. The later may be eventually consistent, but
43 * callers can use BagOStuff:READ_LATEST to see the latest available data.
44 *
45 * Primary entry points:
46 *
47 * - ObjectCache::getMainWANInstance()
48 * Purpose: Memory cache.
49 * Stored in the local data-center's main cache (keyspace different from local-cluster cache).
50 * Delete events are broadcasted to other DCs main cache. See WANObjectCache for details.
51 *
52 * - ObjectCache::getLocalServerInstance( $fallbackType )
53 * Purpose: Memory cache for very hot keys.
54 * Stored only on the individual web server (typically APC for web requests,
55 * and EmptyBagOStuff in CLI mode).
56 * Not replicated to the other servers.
57 *
58 * - ObjectCache::getLocalClusterInstance()
59 * Purpose: Memory storage for per-cluster coordination and tracking.
60 * A typical use case would be a rate limit counter or cache regeneration mutex.
61 * Stored centrally within the local data-center. Not replicated to other DCs.
62 * Configured by $wgMainCacheType.
63 *
64 * - ObjectCache::getMainStashInstance()
65 * Purpose: Ephemeral global storage.
66 * Stored centrally within the primary data-center.
67 * Changes are applied there first and replicated to other DCs (best-effort).
68 * To retrieve the latest value (e.g. not from a slave), use BagOStuff::READ_LATEST.
69 * This store may be subject to LRU style evictions.
70 *
71 * - ObjectCache::getInstance( $cacheType )
72 * Purpose: Special cases (like tiered memory/disk caches).
73 * Get a specific cache type by key in $wgObjectCaches.
74 *
75 * All the above cache instances (BagOStuff and WANObjectCache) have their makeKey()
76 * method scoped to the *current* wiki ID. Use makeGlobalKey() to avoid this scoping
77 * when using keys that need to be shared amongst wikis.
78 *
79 * @ingroup Cache
80 */
81 class ObjectCache {
82 /** @var BagOStuff[] Map of (id => BagOStuff) */
83 public static $instances = [];
84 /** @var WANObjectCache[] Map of (id => WANObjectCache) */
85 public static $wanInstances = [];
86
87 /**
88 * Get a cached instance of the specified type of cache object.
89 *
90 * @param string $id A key in $wgObjectCaches.
91 * @return BagOStuff
92 */
93 public static function getInstance( $id ) {
94 if ( !isset( self::$instances[$id] ) ) {
95 self::$instances[$id] = self::newFromId( $id );
96 }
97
98 return self::$instances[$id];
99 }
100
101 /**
102 * Get a cached instance of the specified type of WAN cache object.
103 *
104 * @since 1.26
105 * @param string $id A key in $wgWANObjectCaches.
106 * @return WANObjectCache
107 */
108 public static function getWANInstance( $id ) {
109 if ( !isset( self::$wanInstances[$id] ) ) {
110 self::$wanInstances[$id] = self::newWANCacheFromId( $id );
111 }
112
113 return self::$wanInstances[$id];
114 }
115
116 /**
117 * Create a new cache object of the specified type.
118 *
119 * @param string $id A key in $wgObjectCaches.
120 * @return BagOStuff
121 * @throws MWException
122 */
123 public static function newFromId( $id ) {
124 global $wgObjectCaches;
125
126 if ( !isset( $wgObjectCaches[$id] ) ) {
127 throw new MWException( "Invalid object cache type \"$id\" requested. " .
128 "It is not present in \$wgObjectCaches." );
129 }
130
131 return self::newFromParams( $wgObjectCaches[$id] );
132 }
133
134 /**
135 * Get the default keyspace for this wiki.
136 *
137 * This is either the value of the `CachePrefix` configuration variable,
138 * or (if the former is unset) the `DBname` configuration variable, with
139 * `DBprefix` (if defined).
140 *
141 * @return string
142 */
143 public static function getDefaultKeyspace() {
144 global $wgCachePrefix;
145
146 $keyspace = $wgCachePrefix;
147 if ( is_string( $keyspace ) && $keyspace !== '' ) {
148 return $keyspace;
149 }
150
151 return wfWikiID();
152 }
153
154 /**
155 * Create a new cache object from parameters.
156 *
157 * @param array $params Must have 'factory' or 'class' property.
158 * - factory: Callback passed $params that returns BagOStuff.
159 * - class: BagOStuff subclass constructed with $params.
160 * - loggroup: Alias to set 'logger' key with LoggerFactory group.
161 * - .. Other parameters passed to factory or class.
162 * @return BagOStuff
163 * @throws MWException
164 */
165 public static function newFromParams( $params ) {
166 if ( isset( $params['loggroup'] ) ) {
167 $params['logger'] = LoggerFactory::getInstance( $params['loggroup'] );
168 } else {
169 $params['logger'] = LoggerFactory::getInstance( 'objectcache' );
170 }
171 if ( !isset( $params['keyspace'] ) ) {
172 $params['keyspace'] = self::getDefaultKeyspace();
173 }
174 if ( isset( $params['factory'] ) ) {
175 return call_user_func( $params['factory'], $params );
176 } elseif ( isset( $params['class'] ) ) {
177 $class = $params['class'];
178 // Automatically set the 'async' update handler
179 $params['asyncHandler'] = isset( $params['asyncHandler'] )
180 ? $params['asyncHandler']
181 : 'DeferredUpdates::addCallableUpdate';
182 // Enable reportDupes by default
183 $params['reportDupes'] = isset( $params['reportDupes'] )
184 ? $params['reportDupes']
185 : true;
186 // Do b/c logic for MemcachedBagOStuff
187 if ( is_subclass_of( $class, 'MemcachedBagOStuff' ) ) {
188 if ( !isset( $params['servers'] ) ) {
189 $params['servers'] = $GLOBALS['wgMemCachedServers'];
190 }
191 if ( !isset( $params['debug'] ) ) {
192 $params['debug'] = $GLOBALS['wgMemCachedDebug'];
193 }
194 if ( !isset( $params['persistent'] ) ) {
195 $params['persistent'] = $GLOBALS['wgMemCachedPersistent'];
196 }
197 if ( !isset( $params['timeout'] ) ) {
198 $params['timeout'] = $GLOBALS['wgMemCachedTimeout'];
199 }
200 }
201 return new $class( $params );
202 } else {
203 throw new MWException( "The definition of cache type \""
204 . print_r( $params, true ) . "\" lacks both "
205 . "factory and class parameters." );
206 }
207 }
208
209 /**
210 * Factory function for CACHE_ANYTHING (referenced from DefaultSettings.php)
211 *
212 * CACHE_ANYTHING means that stuff has to be cached, not caching is not an option.
213 * If a caching method is configured for any of the main caches ($wgMainCacheType,
214 * $wgMessageCacheType, $wgParserCacheType), then CACHE_ANYTHING will effectively
215 * be an alias to the configured cache choice for that.
216 * If no cache choice is configured (by default $wgMainCacheType is CACHE_NONE),
217 * then CACHE_ANYTHING will forward to CACHE_DB.
218 *
219 * @param array $params
220 * @return BagOStuff
221 */
222 public static function newAnything( $params ) {
223 global $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType;
224 $candidates = [ $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType ];
225 foreach ( $candidates as $candidate ) {
226 if ( $candidate !== CACHE_NONE && $candidate !== CACHE_ANYTHING ) {
227 return self::getInstance( $candidate );
228 }
229 }
230
231 try {
232 // Make sure we actually have a DB backend before falling back to CACHE_DB
233 MediaWikiServices::getInstance()->getDBLoadBalancer();
234 $candidate = CACHE_DB;
235 } catch ( ServiceDisabledException $e ) {
236 // The LoadBalancer is disabled, probably because
237 // MediaWikiServices::disableStorageBackend was called.
238 $candidate = CACHE_NONE;
239 }
240
241 return self::getInstance( $candidate );
242 }
243
244 /**
245 * Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
246 *
247 * This will look for any APC style server-local cache.
248 * A fallback cache can be specified if none is found.
249 *
250 * // Direct calls
251 * ObjectCache::getLocalServerInstance( $fallbackType );
252 *
253 * // From $wgObjectCaches via newFromParams()
254 * ObjectCache::getLocalServerInstance( array( 'fallback' => $fallbackType ) );
255 *
256 * @param int|string|array $fallback Fallback cache or parameter map with 'fallback'
257 * @return BagOStuff
258 * @throws MWException
259 * @since 1.27
260 */
261 public static function getLocalServerInstance( $fallback = CACHE_NONE ) {
262 if ( function_exists( 'apc_fetch' ) ) {
263 $id = 'apc';
264 } elseif ( function_exists( 'xcache_get' ) && wfIniGetBool( 'xcache.var_size' ) ) {
265 $id = 'xcache';
266 } elseif ( function_exists( 'wincache_ucache_get' ) ) {
267 $id = 'wincache';
268 } else {
269 if ( is_array( $fallback ) ) {
270 $id = isset( $fallback['fallback'] ) ? $fallback['fallback'] : CACHE_NONE;
271 } else {
272 $id = $fallback;
273 }
274 }
275
276 return self::getInstance( $id );
277 }
278
279 /**
280 * @param array $params [optional] Array key 'fallback' for $fallback.
281 * @param int|string $fallback Fallback cache, e.g. (CACHE_NONE, "hash") (since 1.24)
282 * @return BagOStuff
283 * @deprecated 1.27
284 */
285 public static function newAccelerator( $params = [], $fallback = null ) {
286 if ( $fallback === null ) {
287 if ( is_array( $params ) && isset( $params['fallback'] ) ) {
288 $fallback = $params['fallback'];
289 } elseif ( !is_array( $params ) ) {
290 $fallback = $params;
291 }
292 }
293
294 return self::getLocalServerInstance( $fallback );
295 }
296
297 /**
298 * Create a new cache object of the specified type.
299 *
300 * @since 1.26
301 * @param string $id A key in $wgWANObjectCaches.
302 * @return WANObjectCache
303 * @throws MWException
304 */
305 public static function newWANCacheFromId( $id ) {
306 global $wgWANObjectCaches;
307
308 if ( !isset( $wgWANObjectCaches[$id] ) ) {
309 throw new MWException( "Invalid object cache type \"$id\" requested. " .
310 "It is not present in \$wgWANObjectCaches." );
311 }
312
313 $params = $wgWANObjectCaches[$id];
314 foreach ( $params['channels'] as $action => $channel ) {
315 $params['relayers'][$action] = MediaWikiServices::getInstance()->getEventRelayerGroup()
316 ->getRelayer( $channel );
317 $params['channels'][$action] = $channel;
318 }
319 $params['cache'] = self::newFromId( $params['cacheId'] );
320 if ( isset( $params['loggroup'] ) ) {
321 $params['logger'] = LoggerFactory::getInstance( $params['loggroup'] );
322 } else {
323 $params['logger'] = LoggerFactory::getInstance( 'objectcache' );
324 }
325 $class = $params['class'];
326
327 return new $class( $params );
328 }
329
330 /**
331 * Get the main cluster-local cache object.
332 *
333 * @since 1.27
334 * @return BagOStuff
335 */
336 public static function getLocalClusterInstance() {
337 global $wgMainCacheType;
338
339 return self::getInstance( $wgMainCacheType );
340 }
341
342 /**
343 * Get the main WAN cache object.
344 *
345 * @since 1.26
346 * @return WANObjectCache
347 */
348 public static function getMainWANInstance() {
349 global $wgMainWANCache;
350
351 return self::getWANInstance( $wgMainWANCache );
352 }
353
354 /**
355 * Get the cache object for the main stash.
356 *
357 * Stash objects are BagOStuff instances suitable for storing light
358 * weight data that is not canonically stored elsewhere (such as RDBMS).
359 * Stashes should be configured to propagate changes to all data-centers.
360 *
361 * Callers should be prepared for:
362 * - a) Writes to be slower in non-"primary" (e.g. HTTP GET/HEAD only) DCs
363 * - b) Reads to be eventually consistent, e.g. for get()/getMulti()
364 * In general, this means avoiding updates on idempotent HTTP requests and
365 * avoiding an assumption of perfect serializability (or accepting anomalies).
366 * Reads may be eventually consistent or data might rollback as nodes flap.
367 * Callers can use BagOStuff:READ_LATEST to see the latest available data.
368 *
369 * @return BagOStuff
370 * @since 1.26
371 */
372 public static function getMainStashInstance() {
373 global $wgMainStash;
374
375 return self::getInstance( $wgMainStash );
376 }
377
378 /**
379 * Clear all the cached instances.
380 */
381 public static function clear() {
382 self::$instances = [];
383 self::$wanInstances = [];
384 }
385 }