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
;
25 use MediaWiki\MediaWikiServices
;
28 * Functions to get cache objects
30 * The word "cache" has two main dictionary meanings, and both
31 * are used in this factory class. They are:
33 * - a) Cache (the computer science definition).
34 * A place to store copies or computations on existing data for
35 * higher access speeds.
37 * A place to store lightweight data that is not canonically
38 * stored anywhere else (e.g. a "hoard" of objects).
40 * The former should always use strongly consistent stores, so callers don't
41 * have to deal with stale reads. The latter may be eventually consistent, but
42 * callers can use BagOStuff:READ_LATEST to see the latest available data.
44 * Primary entry points:
46 * - ObjectCache::getMainWANInstance()
47 * Purpose: Memory cache.
48 * Stored in the local data-center's main cache (keyspace different from local-cluster cache).
49 * Delete events are broadcasted to other DCs main cache. See WANObjectCache for details.
51 * - ObjectCache::getLocalServerInstance( $fallbackType )
52 * Purpose: Memory cache for very hot keys.
53 * Stored only on the individual web server (typically APC or APCu for web requests,
54 * and EmptyBagOStuff in CLI mode).
55 * Not replicated to the other servers.
57 * - ObjectCache::getLocalClusterInstance()
58 * Purpose: Memory storage for per-cluster coordination and tracking.
59 * A typical use case would be a rate limit counter or cache regeneration mutex.
60 * Stored centrally within the local data-center. Not replicated to other DCs.
61 * Configured by $wgMainCacheType.
63 * - ObjectCache::getMainStashInstance()
64 * Purpose: Ephemeral global storage.
65 * Stored centrally within the primary data-center.
66 * Changes are applied there first and replicated to other DCs (best-effort).
67 * To retrieve the latest value (e.g. not from a replica DB), use BagOStuff::READ_LATEST.
68 * This store may be subject to LRU style evictions.
70 * - ObjectCache::getInstance( $cacheType )
71 * Purpose: Special cases (like tiered memory/disk caches).
72 * Get a specific cache type by key in $wgObjectCaches.
74 * All the above cache instances (BagOStuff and WANObjectCache) have their makeKey()
75 * method scoped to the *current* wiki ID. Use makeGlobalKey() to avoid this scoping
76 * when using keys that need to be shared amongst wikis.
81 /** @var BagOStuff[] Map of (id => BagOStuff) */
82 public static $instances = [];
83 /** @var WANObjectCache[] Map of (id => WANObjectCache) */
84 public static $wanInstances = [];
87 * Get a cached instance of the specified type of cache object.
89 * @param string $id A key in $wgObjectCaches.
92 public static function getInstance( $id ) {
93 if ( !isset( self
::$instances[$id] ) ) {
94 self
::$instances[$id] = self
::newFromId( $id );
97 return self
::$instances[$id];
101 * Get a cached instance of the specified type of WAN cache object.
104 * @param string $id A key in $wgWANObjectCaches.
105 * @return WANObjectCache
107 public static function getWANInstance( $id ) {
108 if ( !isset( self
::$wanInstances[$id] ) ) {
109 self
::$wanInstances[$id] = self
::newWANCacheFromId( $id );
112 return self
::$wanInstances[$id];
116 * Create a new cache object of the specified type.
118 * @param string $id A key in $wgObjectCaches.
120 * @throws InvalidArgumentException
122 public static function newFromId( $id ) {
123 global $wgObjectCaches;
125 if ( !isset( $wgObjectCaches[$id] ) ) {
126 // Always recognize these ones
127 if ( $id === CACHE_NONE
) {
128 return new EmptyBagOStuff();
129 } elseif ( $id === 'hash' ) {
130 return new HashBagOStuff();
133 throw new InvalidArgumentException( "Invalid object cache type \"$id\" requested. " .
134 "It is not present in \$wgObjectCaches." );
137 return self
::newFromParams( $wgObjectCaches[$id] );
141 * Get the default keyspace for this wiki.
143 * This is either the value of the `CachePrefix` configuration variable,
144 * or (if the former is unset) the `DBname` configuration variable, with
145 * `DBprefix` (if defined).
149 public static function getDefaultKeyspace() {
150 global $wgCachePrefix;
152 $keyspace = $wgCachePrefix;
153 if ( is_string( $keyspace ) && $keyspace !== '' ) {
161 * Create a new cache object from parameters.
163 * @param array $params Must have 'factory' or 'class' property.
164 * - factory: Callback passed $params that returns BagOStuff.
165 * - class: BagOStuff subclass constructed with $params.
166 * - loggroup: Alias to set 'logger' key with LoggerFactory group.
167 * - .. Other parameters passed to factory or class.
169 * @throws InvalidArgumentException
171 public static function newFromParams( $params ) {
172 if ( isset( $params['loggroup'] ) ) {
173 $params['logger'] = LoggerFactory
::getInstance( $params['loggroup'] );
175 $params['logger'] = LoggerFactory
::getInstance( 'objectcache' );
177 if ( !isset( $params['keyspace'] ) ) {
178 $params['keyspace'] = self
::getDefaultKeyspace();
180 if ( isset( $params['factory'] ) ) {
181 return call_user_func( $params['factory'], $params );
182 } elseif ( isset( $params['class'] ) ) {
183 $class = $params['class'];
184 // Automatically set the 'async' update handler
185 $params['asyncHandler'] = $params['asyncHandler'] ??
'DeferredUpdates::addCallableUpdate';
186 // Enable reportDupes by default
187 $params['reportDupes'] = $params['reportDupes'] ??
true;
188 // Do b/c logic for SqlBagOStuff
189 if ( is_a( $class, SqlBagOStuff
::class, true ) ) {
190 if ( isset( $params['server'] ) && !isset( $params['servers'] ) ) {
191 $params['servers'] = [ $params['server'] ];
192 unset( $params['server'] );
194 // In the past it was not required to set 'dbDirectory' in $wgObjectCaches
195 if ( isset( $params['servers'] ) ) {
196 foreach ( $params['servers'] as &$server ) {
197 if ( $server['type'] === 'sqlite' && !isset( $server['dbDirectory'] ) ) {
198 $server['dbDirectory'] = MediaWikiServices
::getInstance()
199 ->getMainConfig()->get( 'SQLiteDataDir' );
205 // Do b/c logic for MemcachedBagOStuff
206 if ( is_subclass_of( $class, MemcachedBagOStuff
::class ) ) {
207 if ( !isset( $params['servers'] ) ) {
208 $params['servers'] = $GLOBALS['wgMemCachedServers'];
210 if ( !isset( $params['debug'] ) ) {
211 $params['debug'] = $GLOBALS['wgMemCachedDebug'];
213 if ( !isset( $params['persistent'] ) ) {
214 $params['persistent'] = $GLOBALS['wgMemCachedPersistent'];
216 if ( !isset( $params['timeout'] ) ) {
217 $params['timeout'] = $GLOBALS['wgMemCachedTimeout'];
220 return new $class( $params );
222 throw new InvalidArgumentException( "The definition of cache type \""
223 . print_r( $params, true ) . "\" lacks both "
224 . "factory and class parameters." );
229 * Factory function for CACHE_ANYTHING (referenced from DefaultSettings.php)
231 * CACHE_ANYTHING means that stuff has to be cached, not caching is not an option.
232 * If a caching method is configured for any of the main caches ($wgMainCacheType,
233 * $wgMessageCacheType, $wgParserCacheType), then CACHE_ANYTHING will effectively
234 * be an alias to the configured cache choice for that.
235 * If no cache choice is configured (by default $wgMainCacheType is CACHE_NONE),
236 * then CACHE_ANYTHING will forward to CACHE_DB.
238 * @param array $params
241 public static function newAnything( $params ) {
242 global $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType;
243 $candidates = [ $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType ];
244 foreach ( $candidates as $candidate ) {
246 if ( $candidate !== CACHE_NONE
&& $candidate !== CACHE_ANYTHING
) {
247 $cache = self
::getInstance( $candidate );
248 // CACHE_ACCEL might default to nothing if no APCu
249 // See includes/ServiceWiring.php
250 if ( !( $cache instanceof EmptyBagOStuff
) ) {
256 if ( MediaWikiServices
::getInstance()->isServiceDisabled( 'DBLoadBalancer' ) ) {
257 // The LoadBalancer is disabled, probably because
258 // MediaWikiServices::disableStorageBackend was called.
259 $candidate = CACHE_NONE
;
261 $candidate = CACHE_DB
;
264 return self
::getInstance( $candidate );
268 * Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
270 * This will look for any APC or APCu style server-local cache.
271 * A fallback cache can be specified if none is found.
274 * ObjectCache::getLocalServerInstance( $fallbackType );
276 * // From $wgObjectCaches via newFromParams()
277 * ObjectCache::getLocalServerInstance( [ 'fallback' => $fallbackType ] );
279 * @param int|string|array $fallback Fallback cache or parameter map with 'fallback'
281 * @throws InvalidArgumentException
284 public static function getLocalServerInstance( $fallback = CACHE_NONE
) {
285 $cache = MediaWikiServices
::getInstance()->getLocalServerObjectCache();
286 if ( $cache instanceof EmptyBagOStuff
) {
287 if ( is_array( $fallback ) ) {
288 $fallback = $fallback['fallback'] ?? CACHE_NONE
;
290 $cache = self
::getInstance( $fallback );
297 * Create a new cache object of the specified type.
300 * @param string $id A key in $wgWANObjectCaches.
301 * @return WANObjectCache
302 * @throws UnexpectedValueException
304 public static function newWANCacheFromId( $id ) {
305 global $wgWANObjectCaches, $wgObjectCaches;
307 if ( !isset( $wgWANObjectCaches[$id] ) ) {
308 throw new UnexpectedValueException(
309 "Cache type \"$id\" requested is not present in \$wgWANObjectCaches." );
312 $params = $wgWANObjectCaches[$id];
313 if ( !isset( $wgObjectCaches[$params['cacheId']] ) ) {
314 throw new UnexpectedValueException(
315 "Cache type \"{$params['cacheId']}\" is not present in \$wgObjectCaches." );
317 $params['store'] = $wgObjectCaches[$params['cacheId']];
319 return self
::newWANCacheFromParams( $params );
323 * Create a new cache object of the specified type.
326 * @param array $params
327 * @return WANObjectCache
328 * @throws UnexpectedValueException
330 public static function newWANCacheFromParams( array $params ) {
331 global $wgCommandLineMode;
333 $services = MediaWikiServices
::getInstance();
335 $erGroup = $services->getEventRelayerGroup();
336 if ( isset( $params['channels'] ) ) {
337 foreach ( $params['channels'] as $action => $channel ) {
338 $params['relayers'][$action] = $erGroup->getRelayer( $channel );
339 $params['channels'][$action] = $channel;
342 $params['cache'] = self
::newFromParams( $params['store'] );
343 if ( isset( $params['loggroup'] ) ) {
344 $params['logger'] = LoggerFactory
::getInstance( $params['loggroup'] );
346 $params['logger'] = LoggerFactory
::getInstance( 'objectcache' );
348 if ( !$wgCommandLineMode ) {
349 // Send the statsd data post-send on HTTP requests; avoid in CLI mode (T181385)
350 $params['stats'] = $services->getStatsdDataFactory();
351 // Let pre-emptive refreshes happen post-send on HTTP requests
352 $params['asyncHandler'] = [ DeferredUpdates
::class, 'addCallableUpdate' ];
354 $class = $params['class'];
356 return new $class( $params );
360 * Get the main cluster-local cache object.
365 public static function getLocalClusterInstance() {
366 global $wgMainCacheType;
368 return self
::getInstance( $wgMainCacheType );
372 * Get the main WAN cache object.
375 * @return WANObjectCache
376 * @deprecated Since 1.28 Use MediaWikiServices::getMainWANObjectCache()
378 public static function getMainWANInstance() {
379 return MediaWikiServices
::getInstance()->getMainWANObjectCache();
383 * Get the cache object for the main stash.
385 * Stash objects are BagOStuff instances suitable for storing light
386 * weight data that is not canonically stored elsewhere (such as RDBMS).
387 * Stashes should be configured to propagate changes to all data-centers.
389 * Callers should be prepared for:
390 * - a) Writes to be slower in non-"primary" (e.g. HTTP GET/HEAD only) DCs
391 * - b) Reads to be eventually consistent, e.g. for get()/getMulti()
392 * In general, this means avoiding updates on idempotent HTTP requests and
393 * avoiding an assumption of perfect serializability (or accepting anomalies).
394 * Reads may be eventually consistent or data might rollback as nodes flap.
395 * Callers can use BagOStuff:READ_LATEST to see the latest available data.
399 * @deprecated Since 1.28 Use MediaWikiServices::getMainObjectStash
401 public static function getMainStashInstance() {
402 return MediaWikiServices
::getInstance()->getMainObjectStash();
406 * Clear all the cached instances.
408 public static function clear() {
409 self
::$instances = [];
410 self
::$wanInstances = [];
414 * Detects which local server cache library is present and returns a configuration for it
417 * @return int|string Index to cache in $wgObjectCaches
419 public static function detectLocalServerCache() {
420 if ( function_exists( 'apc_fetch' ) ) {
422 } elseif ( function_exists( 'apcu_fetch' ) ) {
424 } elseif ( function_exists( 'wincache_ucache_get' ) ) {