PHPSessionHandler: Implement SessionHandlerInterface
[mediawiki.git] / includes / objectcache / ObjectCache.php
blob90a9f7c84235465b708f31d25c793f4a32ad86d4
1 <?php
2 /**
3 * Functions to get cache objects.
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.
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.
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
20 * @file
21 * @ingroup Cache
24 use MediaWiki\Logger\LoggerFactory;
26 /**
27 * Functions to get cache objects
29 * The word "cache" has two main dictionary meanings, and both
30 * are used in this factory class. They are:
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).
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.
43 * Primary entry points:
45 * - ObjectCache::getMainWANInstance()
46 * Purpose: Memory cache.
47 * Stored in the local data-center's main cache (keyspace different from local-cluster cache).
48 * Delete events are broadcasted to other DCs main cache. See WANObjectCache for details.
50 * - ObjectCache::getLocalServerInstance( $fallbackType )
51 * Purpose: Memory cache for very hot keys.
52 * Stored only on the individual web server (typically APC for web requests,
53 * and EmptyBagOStuff in CLI mode).
54 * Not replicated to the other servers.
56 * - ObjectCache::getLocalClusterInstance()
57 * Purpose: Memory storage for per-cluster coordination and tracking.
58 * A typical use case would be a rate limit counter or cache regeneration mutex.
59 * Stored centrally within the local data-center. Not replicated to other DCs.
60 * Configured by $wgMainCacheType.
62 * - ObjectCache::getMainStashInstance()
63 * Purpose: Ephemeral global storage.
64 * Stored centrally within the primary data-center.
65 * Changes are applied there first and replicated to other DCs (best-effort).
66 * To retrieve the latest value (e.g. not from a slave), use BagOStuff::READ_LATEST.
67 * This store may be subject to LRU style evictions.
69 * - ObjectCache::getInstance( $cacheType )
70 * Purpose: Special cases (like tiered memory/disk caches).
71 * Get a specific cache type by key in $wgObjectCaches.
73 * All the above cache instances (BagOStuff and WANObjectCache) have their makeKey()
74 * method scoped to the *current* wiki ID. Use makeGlobalKey() to avoid this scoping
75 * when using keys that need to be shared amongst wikis.
77 * @ingroup Cache
79 class ObjectCache {
80 /** @var BagOStuff[] Map of (id => BagOStuff) */
81 public static $instances = array();
82 /** @var WANObjectCache[] Map of (id => WANObjectCache) */
83 public static $wanInstances = array();
85 /**
86 * Get a cached instance of the specified type of cache object.
88 * @param string $id A key in $wgObjectCaches.
89 * @return BagOStuff
91 public static function getInstance( $id ) {
92 if ( !isset( self::$instances[$id] ) ) {
93 self::$instances[$id] = self::newFromId( $id );
96 return self::$instances[$id];
99 /**
100 * Get a cached instance of the specified type of WAN cache object.
102 * @since 1.26
103 * @param string $id A key in $wgWANObjectCaches.
104 * @return WANObjectCache
106 public static function getWANInstance( $id ) {
107 if ( !isset( self::$wanInstances[$id] ) ) {
108 self::$wanInstances[$id] = self::newWANCacheFromId( $id );
111 return self::$wanInstances[$id];
115 * Create a new cache object of the specified type.
117 * @param string $id A key in $wgObjectCaches.
118 * @return BagOStuff
119 * @throws MWException
121 public static function newFromId( $id ) {
122 global $wgObjectCaches;
124 if ( !isset( $wgObjectCaches[$id] ) ) {
125 throw new MWException( "Invalid object cache type \"$id\" requested. " .
126 "It is not present in \$wgObjectCaches." );
129 return self::newFromParams( $wgObjectCaches[$id] );
133 * Get the default keyspace for this wiki.
135 * This is either the value of the `CachePrefix` configuration variable,
136 * or (if the former is unset) the `DBname` configuration variable, with
137 * `DBprefix` (if defined).
139 * @return string
141 public static function getDefaultKeyspace() {
142 global $wgCachePrefix;
144 $keyspace = $wgCachePrefix;
145 if ( is_string( $keyspace ) && $keyspace !== '' ) {
146 return $keyspace;
149 return wfWikiID();
153 * Create a new cache object from parameters.
155 * @param array $params Must have 'factory' or 'class' property.
156 * - factory: Callback passed $params that returns BagOStuff.
157 * - class: BagOStuff subclass constructed with $params.
158 * - loggroup: Alias to set 'logger' key with LoggerFactory group.
159 * - .. Other parameters passed to factory or class.
160 * @return BagOStuff
161 * @throws MWException
163 public static function newFromParams( $params ) {
164 if ( isset( $params['loggroup'] ) ) {
165 $params['logger'] = LoggerFactory::getInstance( $params['loggroup'] );
166 } else {
167 $params['logger'] = LoggerFactory::getInstance( 'objectcache' );
169 if ( !isset( $params['keyspace'] ) ) {
170 $params['keyspace'] = self::getDefaultKeyspace();
172 if ( isset( $params['factory'] ) ) {
173 return call_user_func( $params['factory'], $params );
174 } elseif ( isset( $params['class'] ) ) {
175 $class = $params['class'];
176 // Automatically set the 'async' update handler
177 if ( $class === 'MultiWriteBagOStuff' ) {
178 $params['asyncHandler'] = isset( $params['asyncHandler'] )
179 ? $params['asyncHandler']
180 : 'DeferredUpdates::addCallableUpdate';
182 // Do b/c logic for MemcachedBagOStuff
183 if ( is_subclass_of( $class, 'MemcachedBagOStuff' ) ) {
184 if ( !isset( $params['servers'] ) ) {
185 $params['servers'] = $GLOBALS['wgMemCachedServers'];
187 if ( !isset( $params['debug'] ) ) {
188 $params['debug'] = $GLOBALS['wgMemCachedDebug'];
190 if ( !isset( $params['persistent'] ) ) {
191 $params['persistent'] = $GLOBALS['wgMemCachedPersistent'];
193 if ( !isset( $params['timeout'] ) ) {
194 $params['timeout'] = $GLOBALS['wgMemCachedTimeout'];
197 return new $class( $params );
198 } else {
199 throw new MWException( "The definition of cache type \""
200 . print_r( $params, true ) . "\" lacks both "
201 . "factory and class parameters." );
206 * Factory function for CACHE_ANYTHING (referenced from DefaultSettings.php)
208 * CACHE_ANYTHING means that stuff has to be cached, not caching is not an option.
209 * If a caching method is configured for any of the main caches ($wgMainCacheType,
210 * $wgMessageCacheType, $wgParserCacheType), then CACHE_ANYTHING will effectively
211 * be an alias to the configured cache choice for that.
212 * If no cache choice is configured (by default $wgMainCacheType is CACHE_NONE),
213 * then CACHE_ANYTHING will forward to CACHE_DB.
215 * @param array $params
216 * @return BagOStuff
218 public static function newAnything( $params ) {
219 global $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType;
220 $candidates = array( $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType );
221 foreach ( $candidates as $candidate ) {
222 if ( $candidate !== CACHE_NONE && $candidate !== CACHE_ANYTHING ) {
223 return self::getInstance( $candidate );
226 return self::getInstance( CACHE_DB );
230 * Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
232 * This will look for any APC style server-local cache.
233 * A fallback cache can be specified if none is found.
235 * // Direct calls
236 * ObjectCache::getLocalServerInstance( $fallbackType );
238 * // From $wgObjectCaches via newFromParams()
239 * ObjectCache::getLocalServerInstance( array( 'fallback' => $fallbackType ) );
241 * @param int|string|array $fallback Fallback cache or parameter map with 'fallback'
242 * @return BagOStuff
243 * @throws MWException
244 * @since 1.27
246 public static function getLocalServerInstance( $fallback = CACHE_NONE ) {
247 if ( function_exists( 'apc_fetch' ) ) {
248 $id = 'apc';
249 } elseif ( function_exists( 'xcache_get' ) && wfIniGetBool( 'xcache.var_size' ) ) {
250 $id = 'xcache';
251 } elseif ( function_exists( 'wincache_ucache_get' ) ) {
252 $id = 'wincache';
253 } else {
254 if ( is_array( $fallback ) ) {
255 $id = isset( $fallback['fallback'] ) ? $fallback['fallback'] : CACHE_NONE;
256 } else {
257 $id = $fallback;
261 return self::getInstance( $id );
265 * @param array $params [optional] Array key 'fallback' for $fallback.
266 * @param int|string $fallback Fallback cache, e.g. (CACHE_NONE, "hash") (since 1.24)
267 * @return BagOStuff
268 * @deprecated 1.27
270 public static function newAccelerator( $params = array(), $fallback = null ) {
271 if ( $fallback === null ) {
272 // The is_array check here is needed because in PHP 5.3:
273 // $a = 'hash'; isset( $params['fallback'] ); yields true
274 if ( is_array( $params ) && isset( $params['fallback'] ) ) {
275 $fallback = $params['fallback'];
276 } elseif ( !is_array( $params ) ) {
277 $fallback = $params;
281 return self::getLocalServerInstance( $fallback );
285 * Create a new cache object of the specified type.
287 * @since 1.26
288 * @param string $id A key in $wgWANObjectCaches.
289 * @return WANObjectCache
290 * @throws MWException
292 public static function newWANCacheFromId( $id ) {
293 global $wgWANObjectCaches;
295 if ( !isset( $wgWANObjectCaches[$id] ) ) {
296 throw new MWException( "Invalid object cache type \"$id\" requested. " .
297 "It is not present in \$wgWANObjectCaches." );
300 $params = $wgWANObjectCaches[$id];
301 $class = $params['relayerConfig']['class'];
302 $params['relayer'] = new $class( $params['relayerConfig'] );
303 $params['cache'] = self::newFromId( $params['cacheId'] );
304 if ( isset( $params['loggroup'] ) ) {
305 $params['logger'] = LoggerFactory::getInstance( $params['loggroup'] );
306 } else {
307 $params['logger'] = LoggerFactory::getInstance( 'objectcache' );
309 $class = $params['class'];
311 return new $class( $params );
315 * Get the main cluster-local cache object.
317 * @since 1.27
318 * @return BagOStuff
320 public static function getLocalClusterInstance() {
321 global $wgMainCacheType;
323 return self::getInstance( $wgMainCacheType );
327 * Get the main WAN cache object.
329 * @since 1.26
330 * @return WANObjectCache
332 public static function getMainWANInstance() {
333 global $wgMainWANCache;
335 return self::getWANInstance( $wgMainWANCache );
339 * Get the cache object for the main stash.
341 * Stash objects are BagOStuff instances suitable for storing light
342 * weight data that is not canonically stored elsewhere (such as RDBMS).
343 * Stashes should be configured to propagate changes to all data-centers.
345 * Callers should be prepared for:
346 * - a) Writes to be slower in non-"primary" (e.g. HTTP GET/HEAD only) DCs
347 * - b) Reads to be eventually consistent, e.g. for get()/getMulti()
348 * In general, this means avoiding updates on idempotent HTTP requests and
349 * avoiding an assumption of perfect serializability (or accepting anomalies).
350 * Reads may be eventually consistent or data might rollback as nodes flap.
351 * Callers can use BagOStuff:READ_LATEST to see the latest available data.
353 * @return BagOStuff
354 * @since 1.26
356 public static function getMainStashInstance() {
357 global $wgMainStash;
359 return self::getInstance( $wgMainStash );
363 * Clear all the cached instances.
365 public static function clear() {
366 self::$instances = array();
367 self::$wanInstances = array();