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