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::getMainClusterInstance()
51 * Purpose: Memory storage for per-cluster coordination and tracking.
52 * Stored centrally within the local data-center.
53 * Not replicated to other DCs.
54 * Also known as $wgMemc. Configured by $wgMainCacheType.
56 * - ObjectCache::getMainWANInstance()
58 * Stored in the local data-center's main cache (uses different cache keys).
59 * Delete events are broadcasted to other DCs. See WANObjectCache for details.
61 * - ObjectCache::getMainStashInstance()
62 * Purpose: Ephemeral storage.
63 * Stored centrally within the local data-center.
64 * Changes are replicated to other DCs (eventually consistent).
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 * - wfGetCache( $cacheType )
69 * Get a specific cache type by key in $wgObjectCaches.
74 /** @var BagOStuff[] Map of (id => BagOStuff) */
75 public static $instances = array();
76 /** @var WANObjectCache[] Map of (id => WANObjectCache) */
77 public static $wanInstances = array();
80 * Get a cached instance of the specified type of cache object.
82 * @param string $id A key in $wgObjectCaches.
85 public static function getInstance( $id ) {
86 if ( !isset( self
::$instances[$id] ) ) {
87 self
::$instances[$id] = self
::newFromId( $id );
90 return self
::$instances[$id];
94 * Get a cached instance of the specified type of WAN cache object.
97 * @param string $id A key in $wgWANObjectCaches.
98 * @return WANObjectCache
100 public static function getWANInstance( $id ) {
101 if ( !isset( self
::$wanInstances[$id] ) ) {
102 self
::$wanInstances[$id] = self
::newWANCacheFromId( $id );
105 return self
::$wanInstances[$id];
109 * Create a new cache object of the specified type.
111 * @param string $id A key in $wgObjectCaches.
113 * @throws MWException
115 public static function newFromId( $id ) {
116 global $wgObjectCaches;
118 if ( !isset( $wgObjectCaches[$id] ) ) {
119 throw new MWException( "Invalid object cache type \"$id\" requested. " .
120 "It is not present in \$wgObjectCaches." );
123 return self
::newFromParams( $wgObjectCaches[$id] );
127 * Create a new cache object from parameters.
129 * @param array $params Must have 'factory' or 'class' property.
130 * - factory: Callback passed $params that returns BagOStuff.
131 * - class: BagOStuff subclass constructed with $params.
132 * - loggroup: Alias to set 'logger' key with LoggerFactory group.
133 * - .. Other parameters passed to factory or class.
135 * @throws MWException
137 public static function newFromParams( $params ) {
138 if ( isset( $params['loggroup'] ) ) {
139 $params['logger'] = LoggerFactory
::getInstance( $params['loggroup'] );
141 // For backwards-compatability with custom parameters, lets not
142 // have all logging suddenly disappear
143 $params['logger'] = LoggerFactory
::getInstance( 'objectcache' );
145 if ( isset( $params['factory'] ) ) {
146 return call_user_func( $params['factory'], $params );
147 } elseif ( isset( $params['class'] ) ) {
148 $class = $params['class'];
149 return new $class( $params );
151 throw new MWException( "The definition of cache type \""
152 . print_r( $params, true ) . "\" lacks both "
153 . "factory and class parameters." );
158 * Factory function for CACHE_ANYTHING (referenced from DefaultSettings.php)
160 * CACHE_ANYTHING means that stuff has to be cached, not caching is not an option.
161 * If a caching method is configured for any of the main caches ($wgMainCacheType,
162 * $wgMessageCacheType, $wgParserCacheType), then CACHE_ANYTHING will effectively
163 * be an alias to the configured cache choice for that.
164 * If no cache choice is configured (by default $wgMainCacheType is CACHE_NONE),
165 * then CACHE_ANYTHING will forward to CACHE_DB.
167 * @param array $params
170 public static function newAnything( $params ) {
171 global $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType;
172 $candidates = array( $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType );
173 foreach ( $candidates as $candidate ) {
174 if ( $candidate !== CACHE_NONE
&& $candidate !== CACHE_ANYTHING
) {
175 return self
::getInstance( $candidate );
178 return self
::getInstance( CACHE_DB
);
182 * Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
184 * This will look for any APC style server-local cache.
185 * A fallback cache can be specified if none is found.
188 * ObjectCache::newAccelerator( $fallbackType );
190 * // From $wgObjectCaches via newFromParams()
191 * ObjectCache::newAccelerator( array( 'fallback' => $fallbackType ) );
193 * @param array $params [optional] Array key 'fallback' for $fallback.
194 * @param int|string $fallback Fallback cache, e.g. (CACHE_NONE, "hash") (since 1.24)
196 * @throws MWException
198 public static function newAccelerator( $params = array(), $fallback = null ) {
199 if ( $fallback === null ) {
200 // The is_array check here is needed because in PHP 5.3:
201 // $a = 'hash'; isset( $params['fallback'] ); yields true
202 if ( is_array( $params ) && isset( $params['fallback'] ) ) {
203 $fallback = $params['fallback'];
204 } elseif ( !is_array( $params ) ) {
208 if ( function_exists( 'apc_fetch' ) ) {
210 } elseif ( function_exists( 'xcache_get' ) && wfIniGetBool( 'xcache.var_size' ) ) {
212 } elseif ( function_exists( 'wincache_ucache_get' ) ) {
215 if ( $fallback === null ) {
216 throw new MWException( 'CACHE_ACCEL requested but no suitable object ' .
217 'cache is present. You may want to install APC.' );
221 return self
::newFromId( $id );
225 * Factory function that creates a memcached client object.
227 * This always uses the PHP client, since the PECL client has a different
228 * hashing scheme and a different interpretation of the flags bitfield, so
229 * switching between the two clients randomly would be disastrous.
231 * @param array $params
232 * @return MemcachedPhpBagOStuff
234 public static function newMemcached( $params ) {
235 return new MemcachedPhpBagOStuff( $params );
239 * Create a new cache object of the specified type.
242 * @param string $id A key in $wgWANObjectCaches.
243 * @return WANObjectCache
244 * @throws MWException
246 public static function newWANCacheFromId( $id ) {
247 global $wgWANObjectCaches;
249 if ( !isset( $wgWANObjectCaches[$id] ) ) {
250 throw new MWException( "Invalid object cache type \"$id\" requested. " .
251 "It is not present in \$wgWANObjectCaches." );
254 $params = $wgWANObjectCaches[$id];
255 $class = $params['relayerConfig']['class'];
256 $params['relayer'] = new $class( $params['relayerConfig'] );
257 $params['cache'] = self
::newFromId( $params['cacheId'] );
258 $class = $params['class'];
260 return new $class( $params );
264 * Get the main cluster-local cache object.
269 public static function getMainClusterInstance() {
270 $config = RequestContext
::getMain()->getConfig();
271 $id = $config->get( 'MainCacheType' );
272 return self
::getInstance( $id );
276 * Get the main WAN cache object.
279 * @return WANObjectCache
281 public static function getMainWANInstance() {
282 global $wgMainWANCache;
284 return self
::getWANInstance( $wgMainWANCache );
288 * Get the cache object for the main stash.
290 * Stash objects are BagOStuff instances suitable for storing light
291 * weight data that is not canonically stored elsewhere (such as RDBMS).
292 * Stashes should be configured to propagate changes to all data-centers.
294 * Callers should be prepared for:
295 * - a) Writes to be slower in non-"primary" (e.g. HTTP GET/HEAD only) DCs
296 * - b) Reads to be eventually consistent, e.g. for get()/getMulti()
297 * In general, this means avoiding updates on idempotent HTTP requests and
298 * avoiding an assumption of perfect serializability (or accepting anomalies).
299 * Reads may be eventually consistent or data might rollback as nodes flap.
300 * Callers can use BagOStuff:READ_LATEST to see the latest available data.
305 public static function getMainStashInstance() {
308 return self
::getInstance( $wgMainStash );
312 * Clear all the cached instances.
314 public static function clear() {
315 self
::$instances = array();
316 self
::$wanInstances = array();