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::getLocalServerInstance( $fallbackType )
47 * Purpose: Memory cache for very hot keys.
48 * Stored only on the individual web server (typically APC or APCu for web requests,
49 * and EmptyBagOStuff in CLI mode).
50 * Not replicated to the other servers.
52 * - ObjectCache::getLocalClusterInstance()
53 * Purpose: Memory storage for per-cluster coordination and tracking.
54 * A typical use case would be a rate limit counter or cache regeneration mutex.
55 * Stored centrally within the local data-center. Not replicated to other DCs.
56 * Configured by $wgMainCacheType.
58 * - ObjectCache::getInstance( $cacheType )
59 * Purpose: Special cases (like tiered memory/disk caches).
60 * Get a specific cache type by key in $wgObjectCaches.
62 * All the above cache instances (BagOStuff and WANObjectCache) have their makeKey()
63 * method scoped to the *current* wiki ID. Use makeGlobalKey() to avoid this scoping
64 * when using keys that need to be shared amongst wikis.
69 /** @var BagOStuff[] Map of (id => BagOStuff) */
70 public static $instances = [];
71 /** @var WANObjectCache[] Map of (id => WANObjectCache) */
72 public static $wanInstances = [];
75 * Get a cached instance of the specified type of cache object.
77 * @param string $id A key in $wgObjectCaches.
80 public static function getInstance( $id ) {
81 if ( !isset( self
::$instances[$id] ) ) {
82 self
::$instances[$id] = self
::newFromId( $id );
85 return self
::$instances[$id];
89 * Get a cached instance of the specified type of WAN cache object.
92 * @param string $id A key in $wgWANObjectCaches.
93 * @return WANObjectCache
95 public static function getWANInstance( $id ) {
96 if ( !isset( self
::$wanInstances[$id] ) ) {
97 self
::$wanInstances[$id] = self
::newWANCacheFromId( $id );
100 return self
::$wanInstances[$id];
104 * Create a new cache object of the specified type.
106 * @param string $id A key in $wgObjectCaches.
108 * @throws InvalidArgumentException
110 private static function newFromId( $id ) {
111 global $wgObjectCaches;
113 if ( !isset( $wgObjectCaches[$id] ) ) {
114 // Always recognize these ones
115 if ( $id === CACHE_NONE
) {
116 return new EmptyBagOStuff();
117 } elseif ( $id === 'hash' ) {
118 return new HashBagOStuff();
121 throw new InvalidArgumentException( "Invalid object cache type \"$id\" requested. " .
122 "It is not present in \$wgObjectCaches." );
125 return self
::newFromParams( $wgObjectCaches[$id] );
129 * Get the default keyspace for this wiki.
131 * This is either the value of the `CachePrefix` configuration variable,
132 * or (if the former is unset) the `DBname` configuration variable, with
133 * `DBprefix` (if defined).
137 private static function getDefaultKeyspace() {
138 global $wgCachePrefix;
140 $keyspace = $wgCachePrefix;
141 if ( is_string( $keyspace ) && $keyspace !== '' ) {
145 return WikiMap
::getCurrentWikiDbDomain()->getId();
149 * Create a new cache object from parameters.
151 * @param array $params Must have 'factory' or 'class' property.
152 * - factory: Callback passed $params that returns BagOStuff.
153 * - class: BagOStuff subclass constructed with $params.
154 * - loggroup: Alias to set 'logger' key with LoggerFactory group.
155 * - .. Other parameters passed to factory or class.
157 * @throws InvalidArgumentException
159 public static function newFromParams( $params ) {
160 $params['logger'] = LoggerFactory
::getInstance( $params['loggroup'] ??
'objectcache' );
161 if ( !isset( $params['keyspace'] ) ) {
162 $params['keyspace'] = self
::getDefaultKeyspace();
164 if ( isset( $params['factory'] ) ) {
165 return call_user_func( $params['factory'], $params );
166 } elseif ( isset( $params['class'] ) ) {
167 $class = $params['class'];
168 // Automatically set the 'async' update handler
169 $params['asyncHandler'] = $params['asyncHandler']
170 ??
[ DeferredUpdates
::class, 'addCallableUpdate' ];
171 // Enable reportDupes by default
172 $params['reportDupes'] = $params['reportDupes'] ??
true;
173 // Do b/c logic for SqlBagOStuff
174 if ( is_a( $class, SqlBagOStuff
::class, true ) ) {
175 if ( isset( $params['server'] ) && !isset( $params['servers'] ) ) {
176 $params['servers'] = [ $params['server'] ];
177 unset( $params['server'] );
179 // In the past it was not required to set 'dbDirectory' in $wgObjectCaches
180 if ( isset( $params['servers'] ) ) {
181 foreach ( $params['servers'] as &$server ) {
182 if ( $server['type'] === 'sqlite' && !isset( $server['dbDirectory'] ) ) {
183 $server['dbDirectory'] = MediaWikiServices
::getInstance()
184 ->getMainConfig()->get( 'SQLiteDataDir' );
190 // Do b/c logic for MemcachedBagOStuff
191 if ( is_subclass_of( $class, MemcachedBagOStuff
::class ) ) {
192 if ( !isset( $params['servers'] ) ) {
193 $params['servers'] = $GLOBALS['wgMemCachedServers'];
195 if ( !isset( $params['persistent'] ) ) {
196 $params['persistent'] = $GLOBALS['wgMemCachedPersistent'];
198 if ( !isset( $params['timeout'] ) ) {
199 $params['timeout'] = $GLOBALS['wgMemCachedTimeout'];
202 return new $class( $params );
204 throw new InvalidArgumentException( "The definition of cache type \""
205 . print_r( $params, true ) . "\" lacks both "
206 . "factory and class parameters." );
211 * Factory function for CACHE_ANYTHING (referenced from DefaultSettings.php)
213 * CACHE_ANYTHING means that stuff has to be cached, not caching is not an option.
214 * If a caching method is configured for any of the main caches ($wgMainCacheType,
215 * $wgMessageCacheType, $wgParserCacheType), then CACHE_ANYTHING will effectively
216 * be an alias to the configured cache choice for that.
217 * If no cache choice is configured (by default $wgMainCacheType is CACHE_NONE),
218 * then CACHE_ANYTHING will forward to CACHE_DB.
220 * @param array $params
223 public static function newAnything( $params ) {
224 global $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType;
225 $candidates = [ $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType ];
226 foreach ( $candidates as $candidate ) {
227 if ( $candidate !== CACHE_NONE
&& $candidate !== CACHE_ANYTHING
) {
228 $cache = self
::getInstance( $candidate );
229 // CACHE_ACCEL might default to nothing if no APCu
230 // See includes/ServiceWiring.php
231 if ( !( $cache instanceof EmptyBagOStuff
) ) {
237 if ( MediaWikiServices
::getInstance()->isServiceDisabled( 'DBLoadBalancer' ) ) {
238 // The LoadBalancer is disabled, probably because
239 // MediaWikiServices::disableStorageBackend was called.
240 $candidate = CACHE_NONE
;
242 $candidate = CACHE_DB
;
245 return self
::getInstance( $candidate );
249 * Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
251 * This will look for any APC or APCu style server-local cache.
252 * A fallback cache can be specified if none is found.
255 * ObjectCache::getLocalServerInstance( $fallbackType );
257 * // From $wgObjectCaches via newFromParams()
258 * ObjectCache::getLocalServerInstance( [ 'fallback' => $fallbackType ] );
260 * @param int|string|array $fallback Fallback cache or parameter map with 'fallback'
262 * @throws InvalidArgumentException
265 public static function getLocalServerInstance( $fallback = CACHE_NONE
) {
266 $cache = MediaWikiServices
::getInstance()->getLocalServerObjectCache();
267 if ( $cache instanceof EmptyBagOStuff
) {
268 if ( is_array( $fallback ) ) {
269 $fallback = $fallback['fallback'] ?? CACHE_NONE
;
271 $cache = self
::getInstance( $fallback );
278 * Create a new cache object of the specified type.
281 * @param string $id A key in $wgWANObjectCaches.
282 * @return WANObjectCache
283 * @throws UnexpectedValueException
285 private static function newWANCacheFromId( $id ) {
286 global $wgWANObjectCaches, $wgObjectCaches;
288 if ( !isset( $wgWANObjectCaches[$id] ) ) {
289 throw new UnexpectedValueException(
290 "Cache type \"$id\" requested is not present in \$wgWANObjectCaches." );
293 $params = $wgWANObjectCaches[$id];
294 if ( !isset( $wgObjectCaches[$params['cacheId']] ) ) {
295 throw new UnexpectedValueException(
296 "Cache type \"{$params['cacheId']}\" is not present in \$wgObjectCaches." );
298 $params['store'] = $wgObjectCaches[$params['cacheId']];
300 return self
::newWANCacheFromParams( $params );
304 * Create a new cache object of the specified type.
307 * @param array $params
308 * @return WANObjectCache
309 * @throws UnexpectedValueException
310 * @suppress PhanTypeMismatchReturn
312 public static function newWANCacheFromParams( array $params ) {
313 global $wgCommandLineMode, $wgSecretKey;
315 $services = MediaWikiServices
::getInstance();
316 $params['cache'] = self
::newFromParams( $params['store'] );
317 $params['logger'] = LoggerFactory
::getInstance( $params['loggroup'] ??
'objectcache' );
318 if ( !$wgCommandLineMode ) {
319 // Send the statsd data post-send on HTTP requests; avoid in CLI mode (T181385)
320 $params['stats'] = $services->getStatsdDataFactory();
321 // Let pre-emptive refreshes happen post-send on HTTP requests
322 $params['asyncHandler'] = [ DeferredUpdates
::class, 'addCallableUpdate' ];
324 $params['secret'] = $params['secret'] ??
$wgSecretKey;
325 $class = $params['class'];
327 return new $class( $params );
331 * Get the main cluster-local cache object.
336 public static function getLocalClusterInstance() {
337 global $wgMainCacheType;
339 return self
::getInstance( $wgMainCacheType );
343 * Clear all the cached instances.
345 public static function clear() {
346 self
::$instances = [];
347 self
::$wanInstances = [];
351 * Detects which local server cache library is present and returns a configuration for it
354 * @return int|string Index to cache in $wgObjectCaches
356 public static function detectLocalServerCache() {
357 if ( function_exists( 'apcu_fetch' ) ) {
358 // Make sure the APCu methods actually store anything
359 if ( PHP_SAPI
!== 'cli' ||
ini_get( 'apc.enable_cli' ) ) {
362 } elseif ( function_exists( 'apc_fetch' ) ) {
363 // Make sure the APC methods actually store anything
364 if ( PHP_SAPI
!== 'cli' ||
ini_get( 'apc.enable_cli' ) ) {
367 } elseif ( function_exists( 'wincache_ucache_get' ) ) {