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
24 use MediaWiki\Logger\LoggerFactory
;
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.
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 (uses different cache keys).
48 * Delete events are broadcasted to other DCs. See WANObjectCache for details.
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.
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.
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.
68 * - ObjectCache::getInstance( $cacheType )
69 * Purpose: Special cases (like tiered memory/disk caches).
70 * Get a specific cache type by key in $wgObjectCaches.
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.
79 /** @var BagOStuff[] Map of (id => BagOStuff) */
80 public static $instances = array();
81 /** @var WANObjectCache[] Map of (id => WANObjectCache) */
82 public static $wanInstances = array();
85 * Get a cached instance of the specified type of cache object.
87 * @param string $id A key in $wgObjectCaches.
90 public static function getInstance( $id ) {
91 if ( !isset( self
::$instances[$id] ) ) {
92 self
::$instances[$id] = self
::newFromId( $id );
95 return self
::$instances[$id];
99 * Get a cached instance of the specified type of WAN cache object.
102 * @param string $id A key in $wgWANObjectCaches.
103 * @return WANObjectCache
105 public static function getWANInstance( $id ) {
106 if ( !isset( self
::$wanInstances[$id] ) ) {
107 self
::$wanInstances[$id] = self
::newWANCacheFromId( $id );
110 return self
::$wanInstances[$id];
114 * Create a new cache object of the specified type.
116 * @param string $id A key in $wgObjectCaches.
118 * @throws MWException
120 public static function newFromId( $id ) {
121 global $wgObjectCaches;
123 if ( !isset( $wgObjectCaches[$id] ) ) {
124 throw new MWException( "Invalid object cache type \"$id\" requested. " .
125 "It is not present in \$wgObjectCaches." );
128 return self
::newFromParams( $wgObjectCaches[$id] );
132 * Get the default keyspace for this wiki.
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).
140 public static function getDefaultKeyspace() {
141 global $wgCachePrefix, $wgDBname, $wgDBprefix;
143 $keyspace = $wgCachePrefix;
144 if ( is_string( $keyspace ) && $keyspace !== '' ) {
148 $keyspace = $wgDBname;
149 if ( is_string( $wgDBprefix ) && $wgDBprefix !== '' ) {
150 $keyspace .= '-' . $wgDBprefix;
157 * Create a new cache object from parameters.
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.
165 * @throws MWException
167 public static function newFromParams( $params ) {
168 if ( isset( $params['loggroup'] ) ) {
169 $params['logger'] = LoggerFactory
::getInstance( $params['loggroup'] );
171 $params['logger'] = LoggerFactory
::getInstance( 'objectcache' );
173 if ( !isset( $params['keyspace'] ) ) {
174 $params['keyspace'] = self
::getDefaultKeyspace();
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';
186 // Do b/c logic for MemcachedBagOStuff
187 if ( is_subclass_of( $class, 'MemcachedBagOStuff' ) ) {
188 if ( !isset( $params['servers'] ) ) {
189 $params['servers'] = $GLOBALS['wgMemCachedServers'];
191 if ( !isset( $params['debug'] ) ) {
192 $params['debug'] = $GLOBALS['wgMemCachedDebug'];
194 if ( !isset( $params['persistent'] ) ) {
195 $params['persistent'] = $GLOBALS['wgMemCachedPersistent'];
197 if ( !isset( $params['timeout'] ) ) {
198 $params['timeout'] = $GLOBALS['wgMemCachedTimeout'];
201 return new $class( $params );
203 throw new MWException( "The definition of cache type \""
204 . print_r( $params, true ) . "\" lacks both "
205 . "factory and class parameters." );
210 * Factory function for CACHE_ANYTHING (referenced from DefaultSettings.php)
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.
219 * @param array $params
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 );
230 return self
::getInstance( CACHE_DB
);
234 * Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
236 * This will look for any APC style server-local cache.
237 * A fallback cache can be specified if none is found.
240 * ObjectCache::getLocalServerInstance( $fallbackType );
242 * // From $wgObjectCaches via newFromParams()
243 * ObjectCache::getLocalServerInstance( array( 'fallback' => $fallbackType ) );
245 * @param int|string|array $fallback Fallback cache or parameter map with 'fallback'
247 * @throws MWException
250 public static function getLocalServerInstance( $fallback = CACHE_NONE
) {
251 if ( function_exists( 'apc_fetch' ) ) {
253 } elseif ( function_exists( 'xcache_get' ) && wfIniGetBool( 'xcache.var_size' ) ) {
255 } elseif ( function_exists( 'wincache_ucache_get' ) ) {
258 if ( is_array( $fallback ) ) {
259 $id = isset( $fallback['fallback'] ) ?
$fallback['fallback'] : CACHE_NONE
;
265 return self
::getInstance( $id );
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)
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 ) ) {
285 return self
::getLocalServerInstance( $fallback );
289 * Create a new cache object of the specified type.
292 * @param string $id A key in $wgWANObjectCaches.
293 * @return WANObjectCache
294 * @throws MWException
296 public static function newWANCacheFromId( $id ) {
297 global $wgWANObjectCaches;
299 if ( !isset( $wgWANObjectCaches[$id] ) ) {
300 throw new MWException( "Invalid object cache type \"$id\" requested. " .
301 "It is not present in \$wgWANObjectCaches." );
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'] );
311 $params['logger'] = LoggerFactory
::getInstance( 'objectcache' );
313 $class = $params['class'];
315 return new $class( $params );
319 * Get the main cluster-local cache object.
324 public static function getLocalClusterInstance() {
325 global $wgMainCacheType;
327 return self
::getInstance( $wgMainCacheType );
331 * Get the main WAN cache object.
334 * @return WANObjectCache
336 public static function getMainWANInstance() {
337 global $wgMainWANCache;
339 return self
::getWANInstance( $wgMainWANCache );
343 * Get the cache object for the main stash.
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.
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.
360 public static function getMainStashInstance() {
363 return self
::getInstance( $wgMainStash );
367 * Clear all the cached instances.
369 public static function clear() {
370 self
::$instances = array();
371 self
::$wanInstances = array();