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::newAccelerator( $fallbackType )
46 * Purpose: Cache for very hot keys.
47 * Stored only on the individual web server.
48 * Not associated with other servers.
50 * - ObjectCache::getMainWANInstance()
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.
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.
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.
68 * - wfGetCache( $cacheType )
69 * Get a specific cache type by key in $wgObjectCaches.
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.
78 /** @var BagOStuff[] Map of (id => BagOStuff) */
79 public static $instances = array();
80 /** @var WANObjectCache[] Map of (id => WANObjectCache) */
81 public static $wanInstances = array();
84 * Get a cached instance of the specified type of cache object.
86 * @param string $id A key in $wgObjectCaches.
89 public static function getInstance( $id ) {
90 if ( !isset( self
::$instances[$id] ) ) {
91 self
::$instances[$id] = self
::newFromId( $id );
94 return self
::$instances[$id];
98 * Get a cached instance of the specified type of WAN cache object.
101 * @param string $id A key in $wgWANObjectCaches.
102 * @return WANObjectCache
104 public static function getWANInstance( $id ) {
105 if ( !isset( self
::$wanInstances[$id] ) ) {
106 self
::$wanInstances[$id] = self
::newWANCacheFromId( $id );
109 return self
::$wanInstances[$id];
113 * Create a new cache object of the specified type.
115 * @param string $id A key in $wgObjectCaches.
117 * @throws MWException
119 public static function newFromId( $id ) {
120 global $wgObjectCaches;
122 if ( !isset( $wgObjectCaches[$id] ) ) {
123 throw new MWException( "Invalid object cache type \"$id\" requested. " .
124 "It is not present in \$wgObjectCaches." );
127 return self
::newFromParams( $wgObjectCaches[$id] );
131 * Get the default keyspace for this wiki.
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).
139 public static function getDefaultKeyspace() {
140 global $wgCachePrefix, $wgDBname, $wgDBprefix;
142 $keyspace = $wgCachePrefix;
143 if ( is_string( $keyspace ) && $keyspace !== '' ) {
147 $keyspace = $wgDBname;
148 if ( is_string( $wgDBprefix ) && $wgDBprefix !== '' ) {
149 $keyspace .= '-' . $wgDBprefix;
156 * Create a new cache object from parameters.
158 * @param array $params Must have 'factory' or 'class' property.
159 * - factory: Callback passed $params that returns BagOStuff.
160 * - class: BagOStuff subclass constructed with $params.
161 * - loggroup: Alias to set 'logger' key with LoggerFactory group.
162 * - .. Other parameters passed to factory or class.
164 * @throws MWException
166 public static function newFromParams( $params ) {
167 if ( isset( $params['loggroup'] ) ) {
168 $params['logger'] = LoggerFactory
::getInstance( $params['loggroup'] );
170 $params['logger'] = LoggerFactory
::getInstance( 'objectcache' );
172 if ( !isset( $params['keyspace'] ) ) {
173 $params['keyspace'] = self
::getDefaultKeyspace();
175 if ( isset( $params['factory'] ) ) {
176 return call_user_func( $params['factory'], $params );
177 } elseif ( isset( $params['class'] ) ) {
178 $class = $params['class'];
179 // Automatically set the 'async' update handler
180 if ( $class === 'MultiWriteBagOStuff' ) {
181 $params['asyncHandler'] = isset( $params['asyncHandler'] )
182 ?
$params['asyncHandler']
183 : 'DeferredUpdates::addCallableUpdate';
185 // Do b/c logic for MemcachedBagOStuff
186 if ( is_subclass_of( $class, 'MemcachedBagOStuff' ) ) {
187 if ( !isset( $params['servers'] ) ) {
188 $params['servers'] = $GLOBALS['wgMemCachedServers'];
190 if ( !isset( $params['debug'] ) ) {
191 $params['debug'] = $GLOBALS['wgMemCachedDebug'];
193 if ( !isset( $params['persistent'] ) ) {
194 $params['persistent'] = $GLOBALS['wgMemCachedPersistent'];
196 if ( !isset( $params['timeout'] ) ) {
197 $params['timeout'] = $GLOBALS['wgMemCachedTimeout'];
200 return new $class( $params );
202 throw new MWException( "The definition of cache type \""
203 . print_r( $params, true ) . "\" lacks both "
204 . "factory and class parameters." );
209 * Factory function for CACHE_ANYTHING (referenced from DefaultSettings.php)
211 * CACHE_ANYTHING means that stuff has to be cached, not caching is not an option.
212 * If a caching method is configured for any of the main caches ($wgMainCacheType,
213 * $wgMessageCacheType, $wgParserCacheType), then CACHE_ANYTHING will effectively
214 * be an alias to the configured cache choice for that.
215 * If no cache choice is configured (by default $wgMainCacheType is CACHE_NONE),
216 * then CACHE_ANYTHING will forward to CACHE_DB.
218 * @param array $params
221 public static function newAnything( $params ) {
222 global $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType;
223 $candidates = array( $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType );
224 foreach ( $candidates as $candidate ) {
225 if ( $candidate !== CACHE_NONE
&& $candidate !== CACHE_ANYTHING
) {
226 return self
::getInstance( $candidate );
229 return self
::getInstance( CACHE_DB
);
233 * Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
235 * This will look for any APC style server-local cache.
236 * A fallback cache can be specified if none is found.
239 * ObjectCache::newAccelerator( $fallbackType );
241 * // From $wgObjectCaches via newFromParams()
242 * ObjectCache::newAccelerator( array( 'fallback' => $fallbackType ) );
244 * @param array $params [optional] Array key 'fallback' for $fallback.
245 * @param int|string $fallback Fallback cache, e.g. (CACHE_NONE, "hash") (since 1.24)
247 * @throws MWException
249 public static function newAccelerator( $params = array(), $fallback = null ) {
250 if ( $fallback === null ) {
251 // The is_array check here is needed because in PHP 5.3:
252 // $a = 'hash'; isset( $params['fallback'] ); yields true
253 if ( is_array( $params ) && isset( $params['fallback'] ) ) {
254 $fallback = $params['fallback'];
255 } elseif ( !is_array( $params ) ) {
259 if ( function_exists( 'apc_fetch' ) ) {
261 } elseif ( function_exists( 'xcache_get' ) && wfIniGetBool( 'xcache.var_size' ) ) {
263 } elseif ( function_exists( 'wincache_ucache_get' ) ) {
266 if ( $fallback === null ) {
267 throw new MWException( 'CACHE_ACCEL requested but no suitable object ' .
268 'cache is present. You may want to install APC.' );
272 return self
::getInstance( $id );
276 * Create a new cache object of the specified type.
279 * @param string $id A key in $wgWANObjectCaches.
280 * @return WANObjectCache
281 * @throws MWException
283 public static function newWANCacheFromId( $id ) {
284 global $wgWANObjectCaches;
286 if ( !isset( $wgWANObjectCaches[$id] ) ) {
287 throw new MWException( "Invalid object cache type \"$id\" requested. " .
288 "It is not present in \$wgWANObjectCaches." );
291 $params = $wgWANObjectCaches[$id];
292 $class = $params['relayerConfig']['class'];
293 $params['relayer'] = new $class( $params['relayerConfig'] );
294 $params['cache'] = self
::newFromId( $params['cacheId'] );
295 if ( isset( $params['loggroup'] ) ) {
296 $params['logger'] = LoggerFactory
::getInstance( $params['loggroup'] );
298 $params['logger'] = LoggerFactory
::getInstance( 'objectcache' );
300 $class = $params['class'];
302 return new $class( $params );
306 * Get the main cluster-local cache object.
311 public static function getLocalClusterInstance() {
312 global $wgMainCacheType;
314 return self
::getInstance( $wgMainCacheType );
318 * Get the main WAN cache object.
321 * @return WANObjectCache
323 public static function getMainWANInstance() {
324 global $wgMainWANCache;
326 return self
::getWANInstance( $wgMainWANCache );
330 * Get the cache object for the main stash.
332 * Stash objects are BagOStuff instances suitable for storing light
333 * weight data that is not canonically stored elsewhere (such as RDBMS).
334 * Stashes should be configured to propagate changes to all data-centers.
336 * Callers should be prepared for:
337 * - a) Writes to be slower in non-"primary" (e.g. HTTP GET/HEAD only) DCs
338 * - b) Reads to be eventually consistent, e.g. for get()/getMulti()
339 * In general, this means avoiding updates on idempotent HTTP requests and
340 * avoiding an assumption of perfect serializability (or accepting anomalies).
341 * Reads may be eventually consistent or data might rollback as nodes flap.
342 * Callers can use BagOStuff:READ_LATEST to see the latest available data.
347 public static function getMainStashInstance() {
350 return self
::getInstance( $wgMainStash );
354 * Clear all the cached instances.
356 public static function clear() {
357 self
::$instances = array();
358 self
::$wanInstances = array();