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