Merge "Exclude redirects from Special:Fewestrevisions"
[lhc/web/wiklou.git] / includes / objectcache / ObjectCache.php
1 <?php
2 /**
3 * Functions to get cache objects.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Cache
22 */
23
24 use MediaWiki\Logger\LoggerFactory;
25 use MediaWiki\MediaWikiServices;
26
27 /**
28 * Functions to get cache objects
29 *
30 * The word "cache" has two main dictionary meanings, and both
31 * are used in this factory class. They are:
32 *
33 * - a) Cache (the computer science definition).
34 * A place to store copies or computations on existing data for
35 * higher access speeds.
36 * - b) Storage.
37 * A place to store lightweight data that is not canonically
38 * stored anywhere else (e.g. a "hoard" of objects).
39 *
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.
43 *
44 * Primary entry points:
45 *
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.
50 *
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.
56 *
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.
62 *
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.
69 *
70 * - ObjectCache::getInstance( $cacheType )
71 * Purpose: Special cases (like tiered memory/disk caches).
72 * Get a specific cache type by key in $wgObjectCaches.
73 *
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.
77 *
78 * @ingroup Cache
79 */
80 class ObjectCache {
81 /** @var BagOStuff[] Map of (id => BagOStuff) */
82 public static $instances = [];
83 /** @var WANObjectCache[] Map of (id => WANObjectCache) */
84 public static $wanInstances = [];
85
86 /**
87 * Get a cached instance of the specified type of cache object.
88 *
89 * @param string $id A key in $wgObjectCaches.
90 * @return BagOStuff
91 */
92 public static function getInstance( $id ) {
93 if ( !isset( self::$instances[$id] ) ) {
94 self::$instances[$id] = self::newFromId( $id );
95 }
96
97 return self::$instances[$id];
98 }
99
100 /**
101 * Get a cached instance of the specified type of WAN cache object.
102 *
103 * @since 1.26
104 * @param string $id A key in $wgWANObjectCaches.
105 * @return WANObjectCache
106 */
107 public static function getWANInstance( $id ) {
108 if ( !isset( self::$wanInstances[$id] ) ) {
109 self::$wanInstances[$id] = self::newWANCacheFromId( $id );
110 }
111
112 return self::$wanInstances[$id];
113 }
114
115 /**
116 * Create a new cache object of the specified type.
117 *
118 * @param string $id A key in $wgObjectCaches.
119 * @return BagOStuff
120 * @throws InvalidArgumentException
121 */
122 public static function newFromId( $id ) {
123 global $wgObjectCaches;
124
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();
131 }
132
133 throw new InvalidArgumentException( "Invalid object cache type \"$id\" requested. " .
134 "It is not present in \$wgObjectCaches." );
135 }
136
137 return self::newFromParams( $wgObjectCaches[$id] );
138 }
139
140 /**
141 * Get the default keyspace for this wiki.
142 *
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).
146 *
147 * @return string
148 */
149 public static function getDefaultKeyspace() {
150 global $wgCachePrefix;
151
152 $keyspace = $wgCachePrefix;
153 if ( is_string( $keyspace ) && $keyspace !== '' ) {
154 return $keyspace;
155 }
156
157 return WikiMap::getCurrentWikiDbDomain()->getId();
158 }
159
160 /**
161 * Create a new cache object from parameters.
162 *
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.
168 * @return BagOStuff
169 * @throws InvalidArgumentException
170 */
171 public static function newFromParams( $params ) {
172 $params['logger'] = LoggerFactory::getInstance( $params['loggroup'] ?? 'objectcache' );
173 if ( !isset( $params['keyspace'] ) ) {
174 $params['keyspace'] = self::getDefaultKeyspace();
175 }
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 $params['asyncHandler'] = $params['asyncHandler'] ?? 'DeferredUpdates::addCallableUpdate';
182 // Enable reportDupes by default
183 $params['reportDupes'] = $params['reportDupes'] ?? true;
184 // Do b/c logic for SqlBagOStuff
185 if ( is_a( $class, SqlBagOStuff::class, true ) ) {
186 if ( isset( $params['server'] ) && !isset( $params['servers'] ) ) {
187 $params['servers'] = [ $params['server'] ];
188 unset( $params['server'] );
189 }
190 // In the past it was not required to set 'dbDirectory' in $wgObjectCaches
191 if ( isset( $params['servers'] ) ) {
192 foreach ( $params['servers'] as &$server ) {
193 if ( $server['type'] === 'sqlite' && !isset( $server['dbDirectory'] ) ) {
194 $server['dbDirectory'] = MediaWikiServices::getInstance()
195 ->getMainConfig()->get( 'SQLiteDataDir' );
196 }
197 }
198 }
199 }
200
201 // Do b/c logic for MemcachedBagOStuff
202 if ( is_subclass_of( $class, MemcachedBagOStuff::class ) ) {
203 if ( !isset( $params['servers'] ) ) {
204 $params['servers'] = $GLOBALS['wgMemCachedServers'];
205 }
206 if ( !isset( $params['debug'] ) ) {
207 $params['debug'] = $GLOBALS['wgMemCachedDebug'];
208 }
209 if ( !isset( $params['persistent'] ) ) {
210 $params['persistent'] = $GLOBALS['wgMemCachedPersistent'];
211 }
212 if ( !isset( $params['timeout'] ) ) {
213 $params['timeout'] = $GLOBALS['wgMemCachedTimeout'];
214 }
215 }
216 return new $class( $params );
217 } else {
218 throw new InvalidArgumentException( "The definition of cache type \""
219 . print_r( $params, true ) . "\" lacks both "
220 . "factory and class parameters." );
221 }
222 }
223
224 /**
225 * Factory function for CACHE_ANYTHING (referenced from DefaultSettings.php)
226 *
227 * CACHE_ANYTHING means that stuff has to be cached, not caching is not an option.
228 * If a caching method is configured for any of the main caches ($wgMainCacheType,
229 * $wgMessageCacheType, $wgParserCacheType), then CACHE_ANYTHING will effectively
230 * be an alias to the configured cache choice for that.
231 * If no cache choice is configured (by default $wgMainCacheType is CACHE_NONE),
232 * then CACHE_ANYTHING will forward to CACHE_DB.
233 *
234 * @param array $params
235 * @return BagOStuff
236 */
237 public static function newAnything( $params ) {
238 global $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType;
239 $candidates = [ $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType ];
240 foreach ( $candidates as $candidate ) {
241 if ( $candidate !== CACHE_NONE && $candidate !== CACHE_ANYTHING ) {
242 $cache = self::getInstance( $candidate );
243 // CACHE_ACCEL might default to nothing if no APCu
244 // See includes/ServiceWiring.php
245 if ( !( $cache instanceof EmptyBagOStuff ) ) {
246 return $cache;
247 }
248 }
249 }
250
251 if ( MediaWikiServices::getInstance()->isServiceDisabled( 'DBLoadBalancer' ) ) {
252 // The LoadBalancer is disabled, probably because
253 // MediaWikiServices::disableStorageBackend was called.
254 $candidate = CACHE_NONE;
255 } else {
256 $candidate = CACHE_DB;
257 }
258
259 return self::getInstance( $candidate );
260 }
261
262 /**
263 * Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
264 *
265 * This will look for any APC or APCu style server-local cache.
266 * A fallback cache can be specified if none is found.
267 *
268 * // Direct calls
269 * ObjectCache::getLocalServerInstance( $fallbackType );
270 *
271 * // From $wgObjectCaches via newFromParams()
272 * ObjectCache::getLocalServerInstance( [ 'fallback' => $fallbackType ] );
273 *
274 * @param int|string|array $fallback Fallback cache or parameter map with 'fallback'
275 * @return BagOStuff
276 * @throws InvalidArgumentException
277 * @since 1.27
278 */
279 public static function getLocalServerInstance( $fallback = CACHE_NONE ) {
280 $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
281 if ( $cache instanceof EmptyBagOStuff ) {
282 if ( is_array( $fallback ) ) {
283 $fallback = $fallback['fallback'] ?? CACHE_NONE;
284 }
285 $cache = self::getInstance( $fallback );
286 }
287
288 return $cache;
289 }
290
291 /**
292 * Create a new cache object of the specified type.
293 *
294 * @since 1.26
295 * @param string $id A key in $wgWANObjectCaches.
296 * @return WANObjectCache
297 * @throws UnexpectedValueException
298 */
299 public static function newWANCacheFromId( $id ) {
300 global $wgWANObjectCaches, $wgObjectCaches;
301
302 if ( !isset( $wgWANObjectCaches[$id] ) ) {
303 throw new UnexpectedValueException(
304 "Cache type \"$id\" requested is not present in \$wgWANObjectCaches." );
305 }
306
307 $params = $wgWANObjectCaches[$id];
308 if ( !isset( $wgObjectCaches[$params['cacheId']] ) ) {
309 throw new UnexpectedValueException(
310 "Cache type \"{$params['cacheId']}\" is not present in \$wgObjectCaches." );
311 }
312 $params['store'] = $wgObjectCaches[$params['cacheId']];
313
314 return self::newWANCacheFromParams( $params );
315 }
316
317 /**
318 * Create a new cache object of the specified type.
319 *
320 * @since 1.28
321 * @param array $params
322 * @return WANObjectCache
323 * @throws UnexpectedValueException
324 */
325 public static function newWANCacheFromParams( array $params ) {
326 global $wgCommandLineMode, $wgSecretKey;
327
328 $services = MediaWikiServices::getInstance();
329 $params['cache'] = self::newFromParams( $params['store'] );
330 $params['logger'] = LoggerFactory::getInstance( $params['loggroup'] ?? 'objectcache' );
331 if ( !$wgCommandLineMode ) {
332 // Send the statsd data post-send on HTTP requests; avoid in CLI mode (T181385)
333 $params['stats'] = $services->getStatsdDataFactory();
334 // Let pre-emptive refreshes happen post-send on HTTP requests
335 $params['asyncHandler'] = [ DeferredUpdates::class, 'addCallableUpdate' ];
336 }
337 $params['secret'] = $params['secret'] ?? $wgSecretKey;
338 $class = $params['class'];
339
340 return new $class( $params );
341 }
342
343 /**
344 * Get the main cluster-local cache object.
345 *
346 * @since 1.27
347 * @return BagOStuff
348 */
349 public static function getLocalClusterInstance() {
350 global $wgMainCacheType;
351
352 return self::getInstance( $wgMainCacheType );
353 }
354
355 /**
356 * Get the main WAN cache object.
357 *
358 * @since 1.26
359 * @return WANObjectCache
360 * @deprecated Since 1.28 Use MediaWikiServices::getInstance()->getMainWANObjectCache()
361 */
362 public static function getMainWANInstance() {
363 wfDeprecated( __METHOD__, '1.28' );
364 return MediaWikiServices::getInstance()->getMainWANObjectCache();
365 }
366
367 /**
368 * Get the cache object for the main stash.
369 *
370 * @return BagOStuff
371 * @since 1.26
372 * @deprecated Since 1.28 Use MediaWikiServices::getInstance()->getMainObjectStash()
373 */
374 public static function getMainStashInstance() {
375 wfDeprecated( __METHOD__, '1.28' );
376 return MediaWikiServices::getInstance()->getMainObjectStash();
377 }
378
379 /**
380 * Clear all the cached instances.
381 */
382 public static function clear() {
383 self::$instances = [];
384 self::$wanInstances = [];
385 }
386
387 /**
388 * Detects which local server cache library is present and returns a configuration for it
389 * @since 1.32
390 *
391 * @return int|string Index to cache in $wgObjectCaches
392 */
393 public static function detectLocalServerCache() {
394 if ( function_exists( 'apcu_fetch' ) ) {
395 return 'apcu';
396 } elseif ( function_exists( 'apc_fetch' ) ) {
397 return 'apc';
398 } elseif ( function_exists( 'wincache_ucache_get' ) ) {
399 return 'wincache';
400 }
401 return CACHE_NONE;
402 }
403 }