e49feae881f81ab712d84458a2adf5145531e7e9
[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::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.
51 *
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.
57 *
58 * - ObjectCache::getInstance( $cacheType )
59 * Purpose: Special cases (like tiered memory/disk caches).
60 * Get a specific cache type by key in $wgObjectCaches.
61 *
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.
65 *
66 * @ingroup Cache
67 */
68 class ObjectCache {
69 /** @var BagOStuff[] Map of (id => BagOStuff) */
70 public static $instances = [];
71 /** @var WANObjectCache[] Map of (id => WANObjectCache) */
72 public static $wanInstances = [];
73
74 /**
75 * Get a cached instance of the specified type of cache object.
76 *
77 * @param string $id A key in $wgObjectCaches.
78 * @return BagOStuff
79 */
80 public static function getInstance( $id ) {
81 if ( !isset( self::$instances[$id] ) ) {
82 self::$instances[$id] = self::newFromId( $id );
83 }
84
85 return self::$instances[$id];
86 }
87
88 /**
89 * Get a cached instance of the specified type of WAN cache object.
90 *
91 * @since 1.26
92 * @param string $id A key in $wgWANObjectCaches.
93 * @return WANObjectCache
94 */
95 public static function getWANInstance( $id ) {
96 if ( !isset( self::$wanInstances[$id] ) ) {
97 self::$wanInstances[$id] = self::newWANCacheFromId( $id );
98 }
99
100 return self::$wanInstances[$id];
101 }
102
103 /**
104 * Create a new cache object of the specified type.
105 *
106 * @param string $id A key in $wgObjectCaches.
107 * @return BagOStuff
108 * @throws InvalidArgumentException
109 */
110 private static function newFromId( $id ) {
111 global $wgObjectCaches;
112
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();
119 }
120
121 throw new InvalidArgumentException( "Invalid object cache type \"$id\" requested. " .
122 "It is not present in \$wgObjectCaches." );
123 }
124
125 return self::newFromParams( $wgObjectCaches[$id] );
126 }
127
128 /**
129 * Get the default keyspace for this wiki.
130 *
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).
134 *
135 * @return string
136 */
137 private static function getDefaultKeyspace() {
138 global $wgCachePrefix;
139
140 $keyspace = $wgCachePrefix;
141 if ( is_string( $keyspace ) && $keyspace !== '' ) {
142 return $keyspace;
143 }
144
145 return WikiMap::getCurrentWikiDbDomain()->getId();
146 }
147
148 /**
149 * Create a new cache object from parameters.
150 *
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.
156 * @return BagOStuff
157 * @throws InvalidArgumentException
158 */
159 public static function newFromParams( $params ) {
160 $params['logger'] = LoggerFactory::getInstance( $params['loggroup'] ?? 'objectcache' );
161 if ( !isset( $params['keyspace'] ) ) {
162 $params['keyspace'] = self::getDefaultKeyspace();
163 }
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'] );
178 }
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' );
185 }
186 }
187 }
188 }
189
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'];
194 }
195 if ( !isset( $params['persistent'] ) ) {
196 $params['persistent'] = $GLOBALS['wgMemCachedPersistent'];
197 }
198 if ( !isset( $params['timeout'] ) ) {
199 $params['timeout'] = $GLOBALS['wgMemCachedTimeout'];
200 }
201 }
202 return new $class( $params );
203 } else {
204 throw new InvalidArgumentException( "The definition of cache type \""
205 . print_r( $params, true ) . "\" lacks both "
206 . "factory and class parameters." );
207 }
208 }
209
210 /**
211 * Factory function for CACHE_ANYTHING (referenced from DefaultSettings.php)
212 *
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.
219 *
220 * @param array $params
221 * @return BagOStuff
222 */
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 ) ) {
232 return $cache;
233 }
234 }
235 }
236
237 if ( MediaWikiServices::getInstance()->isServiceDisabled( 'DBLoadBalancer' ) ) {
238 // The LoadBalancer is disabled, probably because
239 // MediaWikiServices::disableStorageBackend was called.
240 $candidate = CACHE_NONE;
241 } else {
242 $candidate = CACHE_DB;
243 }
244
245 return self::getInstance( $candidate );
246 }
247
248 /**
249 * Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
250 *
251 * This will look for any APC or APCu style server-local cache.
252 * A fallback cache can be specified if none is found.
253 *
254 * // Direct calls
255 * ObjectCache::getLocalServerInstance( $fallbackType );
256 *
257 * // From $wgObjectCaches via newFromParams()
258 * ObjectCache::getLocalServerInstance( [ 'fallback' => $fallbackType ] );
259 *
260 * @param int|string|array $fallback Fallback cache or parameter map with 'fallback'
261 * @return BagOStuff
262 * @throws InvalidArgumentException
263 * @since 1.27
264 */
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;
270 }
271 $cache = self::getInstance( $fallback );
272 }
273
274 return $cache;
275 }
276
277 /**
278 * Create a new cache object of the specified type.
279 *
280 * @since 1.26
281 * @param string $id A key in $wgWANObjectCaches.
282 * @return WANObjectCache
283 * @throws UnexpectedValueException
284 */
285 private static function newWANCacheFromId( $id ) {
286 global $wgWANObjectCaches, $wgObjectCaches;
287
288 if ( !isset( $wgWANObjectCaches[$id] ) ) {
289 throw new UnexpectedValueException(
290 "Cache type \"$id\" requested is not present in \$wgWANObjectCaches." );
291 }
292
293 $params = $wgWANObjectCaches[$id];
294 if ( !isset( $wgObjectCaches[$params['cacheId']] ) ) {
295 throw new UnexpectedValueException(
296 "Cache type \"{$params['cacheId']}\" is not present in \$wgObjectCaches." );
297 }
298 $params['store'] = $wgObjectCaches[$params['cacheId']];
299
300 return self::newWANCacheFromParams( $params );
301 }
302
303 /**
304 * Create a new cache object of the specified type.
305 *
306 * @since 1.28
307 * @param array $params
308 * @return WANObjectCache
309 * @throws UnexpectedValueException
310 * @suppress PhanTypeMismatchReturn
311 */
312 public static function newWANCacheFromParams( array $params ) {
313 global $wgCommandLineMode, $wgSecretKey;
314
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' ];
323 }
324 $params['secret'] = $params['secret'] ?? $wgSecretKey;
325 $class = $params['class'];
326
327 return new $class( $params );
328 }
329
330 /**
331 * Get the main cluster-local cache object.
332 *
333 * @since 1.27
334 * @return BagOStuff
335 */
336 public static function getLocalClusterInstance() {
337 global $wgMainCacheType;
338
339 return self::getInstance( $wgMainCacheType );
340 }
341
342 /**
343 * Clear all the cached instances.
344 */
345 public static function clear() {
346 self::$instances = [];
347 self::$wanInstances = [];
348 }
349
350 /**
351 * Detects which local server cache library is present and returns a configuration for it
352 * @since 1.32
353 *
354 * @return int|string Index to cache in $wgObjectCaches
355 */
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' ) ) {
360 return 'apcu';
361 }
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' ) ) {
365 return 'apc';
366 }
367 } elseif ( function_exists( 'wincache_ucache_get' ) ) {
368 return 'wincache';
369 }
370
371 return CACHE_NONE;
372 }
373 }