objectcache: Log debug message for backend of MainObjectStash
[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 * @deprecated since 1.34 Use MediaWikiServices::getMainWANObjectCache instead
95 */
96 public static function getWANInstance( $id ) {
97 wfDeprecated( __METHOD__, '1.34' );
98 if ( !isset( self::$wanInstances[$id] ) ) {
99 self::$wanInstances[$id] = self::newWANCacheFromId( $id );
100 }
101
102 return self::$wanInstances[$id];
103 }
104
105 /**
106 * Create a new cache object of the specified type.
107 *
108 * @param string $id A key in $wgObjectCaches.
109 * @return BagOStuff
110 * @throws InvalidArgumentException
111 */
112 private static function newFromId( $id ) {
113 global $wgObjectCaches;
114
115 if ( !isset( $wgObjectCaches[$id] ) ) {
116 // Always recognize these ones
117 if ( $id === CACHE_NONE ) {
118 return new EmptyBagOStuff();
119 } elseif ( $id === 'hash' ) {
120 return new HashBagOStuff();
121 }
122
123 throw new InvalidArgumentException( "Invalid object cache type \"$id\" requested. " .
124 "It is not present in \$wgObjectCaches." );
125 }
126
127 return self::newFromParams( $wgObjectCaches[$id] );
128 }
129
130 /**
131 * Get the default keyspace for this wiki.
132 *
133 * This is either the value of the `CachePrefix` configuration variable,
134 * or (if the former is unset) the `DBname` configuration variable, with
135 * `DBprefix` (if defined).
136 *
137 * @return string
138 */
139 private static function getDefaultKeyspace() {
140 global $wgCachePrefix;
141
142 $keyspace = $wgCachePrefix;
143 if ( is_string( $keyspace ) && $keyspace !== '' ) {
144 return $keyspace;
145 }
146
147 return WikiMap::getCurrentWikiDbDomain()->getId();
148 }
149
150 /**
151 * Create a new cache object from parameters.
152 *
153 * @param array $params Must have 'factory' or 'class' property.
154 * - factory: Callback passed $params that returns BagOStuff.
155 * - class: BagOStuff subclass constructed with $params.
156 * - loggroup: Alias to set 'logger' key with LoggerFactory group.
157 * - .. Other parameters passed to factory or class.
158 * @return BagOStuff
159 * @throws InvalidArgumentException
160 */
161 public static function newFromParams( $params ) {
162 $params['logger'] = $params['logger'] ??
163 LoggerFactory::getInstance( $params['loggroup'] ?? 'objectcache' );
164 if ( !isset( $params['keyspace'] ) ) {
165 $params['keyspace'] = self::getDefaultKeyspace();
166 }
167 if ( isset( $params['factory'] ) ) {
168 return call_user_func( $params['factory'], $params );
169 } elseif ( isset( $params['class'] ) ) {
170 $class = $params['class'];
171 // Automatically set the 'async' update handler
172 $params['asyncHandler'] = $params['asyncHandler']
173 ?? [ DeferredUpdates::class, 'addCallableUpdate' ];
174 // Enable reportDupes by default
175 $params['reportDupes'] = $params['reportDupes'] ?? true;
176 // Do b/c logic for SqlBagOStuff
177 if ( is_a( $class, SqlBagOStuff::class, true ) ) {
178 if ( isset( $params['server'] ) && !isset( $params['servers'] ) ) {
179 $params['servers'] = [ $params['server'] ];
180 unset( $params['server'] );
181 }
182 // In the past it was not required to set 'dbDirectory' in $wgObjectCaches
183 if ( isset( $params['servers'] ) ) {
184 foreach ( $params['servers'] as &$server ) {
185 if ( $server['type'] === 'sqlite' && !isset( $server['dbDirectory'] ) ) {
186 $server['dbDirectory'] = MediaWikiServices::getInstance()
187 ->getMainConfig()->get( 'SQLiteDataDir' );
188 }
189 }
190 }
191 }
192
193 // Do b/c logic for MemcachedBagOStuff
194 if ( is_subclass_of( $class, MemcachedBagOStuff::class ) ) {
195 if ( !isset( $params['servers'] ) ) {
196 $params['servers'] = $GLOBALS['wgMemCachedServers'];
197 }
198 if ( !isset( $params['persistent'] ) ) {
199 $params['persistent'] = $GLOBALS['wgMemCachedPersistent'];
200 }
201 if ( !isset( $params['timeout'] ) ) {
202 $params['timeout'] = $GLOBALS['wgMemCachedTimeout'];
203 }
204 }
205 return new $class( $params );
206 } else {
207 throw new InvalidArgumentException( "The definition of cache type \""
208 . print_r( $params, true ) . "\" lacks both "
209 . "factory and class parameters." );
210 }
211 }
212
213 /**
214 * Factory function for CACHE_ANYTHING (referenced from DefaultSettings.php)
215 *
216 * CACHE_ANYTHING means that stuff has to be cached, not caching is not an option.
217 * If a caching method is configured for any of the main caches ($wgMainCacheType,
218 * $wgMessageCacheType, $wgParserCacheType), then CACHE_ANYTHING will effectively
219 * be an alias to the configured cache choice for that.
220 * If no cache choice is configured (by default $wgMainCacheType is CACHE_NONE),
221 * then CACHE_ANYTHING will forward to CACHE_DB.
222 *
223 * @param array $params
224 * @return BagOStuff
225 */
226 public static function newAnything( $params ) {
227 global $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType;
228 $candidates = [ $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType ];
229 foreach ( $candidates as $candidate ) {
230 if ( $candidate !== CACHE_NONE && $candidate !== CACHE_ANYTHING ) {
231 $cache = self::getInstance( $candidate );
232 // CACHE_ACCEL might default to nothing if no APCu
233 // See includes/ServiceWiring.php
234 if ( !( $cache instanceof EmptyBagOStuff ) ) {
235 return $cache;
236 }
237 }
238 }
239
240 if ( MediaWikiServices::getInstance()->isServiceDisabled( 'DBLoadBalancer' ) ) {
241 // The LoadBalancer is disabled, probably because
242 // MediaWikiServices::disableStorageBackend was called.
243 $candidate = CACHE_NONE;
244 } else {
245 $candidate = CACHE_DB;
246 }
247
248 return self::getInstance( $candidate );
249 }
250
251 /**
252 * Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
253 *
254 * This will look for any APC or APCu style server-local cache.
255 * A fallback cache can be specified if none is found.
256 *
257 * // Direct calls
258 * ObjectCache::getLocalServerInstance( $fallbackType );
259 *
260 * // From $wgObjectCaches via newFromParams()
261 * ObjectCache::getLocalServerInstance( [ 'fallback' => $fallbackType ] );
262 *
263 * @param int|string|array $fallback Fallback cache or parameter map with 'fallback'
264 * @return BagOStuff
265 * @throws InvalidArgumentException
266 * @since 1.27
267 */
268 public static function getLocalServerInstance( $fallback = CACHE_NONE ) {
269 $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
270 if ( $cache instanceof EmptyBagOStuff ) {
271 if ( is_array( $fallback ) ) {
272 $fallback = $fallback['fallback'] ?? CACHE_NONE;
273 }
274 $cache = self::getInstance( $fallback );
275 }
276
277 return $cache;
278 }
279
280 /**
281 * Create a new cache object of the specified type.
282 *
283 * @since 1.26
284 * @param string $id A key in $wgWANObjectCaches.
285 * @return WANObjectCache
286 * @throws UnexpectedValueException
287 */
288 private static function newWANCacheFromId( $id ) {
289 global $wgWANObjectCaches, $wgObjectCaches;
290
291 if ( !isset( $wgWANObjectCaches[$id] ) ) {
292 throw new UnexpectedValueException(
293 "Cache type \"$id\" requested is not present in \$wgWANObjectCaches." );
294 }
295
296 $params = $wgWANObjectCaches[$id];
297 if ( !isset( $wgObjectCaches[$params['cacheId']] ) ) {
298 throw new UnexpectedValueException(
299 "Cache type \"{$params['cacheId']}\" is not present in \$wgObjectCaches." );
300 }
301 $params['store'] = $wgObjectCaches[$params['cacheId']];
302
303 return self::newWANCacheFromParams( $params );
304 }
305
306 /**
307 * Create a new cache object of the specified type.
308 *
309 * @since 1.28
310 * @param array $params
311 * @return WANObjectCache
312 * @throws UnexpectedValueException
313 * @suppress PhanTypeMismatchReturn
314 * @deprecated since 1.34 Use MediaWikiServices::getMainWANObjectCache
315 * instead or use WANObjectCache::__construct directly
316 */
317 public static function newWANCacheFromParams( array $params ) {
318 wfDeprecated( __METHOD__, '1.34' );
319 global $wgCommandLineMode, $wgSecretKey;
320
321 $services = MediaWikiServices::getInstance();
322 $params['cache'] = self::newFromParams( $params['store'] );
323 $params['logger'] = LoggerFactory::getInstance( $params['loggroup'] ?? 'objectcache' );
324 if ( !$wgCommandLineMode ) {
325 // Send the statsd data post-send on HTTP requests; avoid in CLI mode (T181385)
326 $params['stats'] = $services->getStatsdDataFactory();
327 // Let pre-emptive refreshes happen post-send on HTTP requests
328 $params['asyncHandler'] = [ DeferredUpdates::class, 'addCallableUpdate' ];
329 }
330 $params['secret'] = $params['secret'] ?? $wgSecretKey;
331 $class = $params['class'];
332
333 return new $class( $params );
334 }
335
336 /**
337 * Get the main cluster-local cache object.
338 *
339 * @since 1.27
340 * @return BagOStuff
341 */
342 public static function getLocalClusterInstance() {
343 global $wgMainCacheType;
344
345 return self::getInstance( $wgMainCacheType );
346 }
347
348 /**
349 * Clear all the cached instances.
350 */
351 public static function clear() {
352 self::$instances = [];
353 self::$wanInstances = [];
354 }
355
356 /**
357 * Detects which local server cache library is present and returns a configuration for it
358 * @since 1.32
359 *
360 * @return int|string Index to cache in $wgObjectCaches
361 */
362 public static function detectLocalServerCache() {
363 if ( function_exists( 'apcu_fetch' ) ) {
364 // Make sure the APCu methods actually store anything
365 if ( PHP_SAPI !== 'cli' || ini_get( 'apc.enable_cli' ) ) {
366 return 'apcu';
367 }
368 } elseif ( function_exists( 'apc_fetch' ) ) {
369 // Make sure the APC methods actually store anything
370 if ( PHP_SAPI !== 'cli' || ini_get( 'apc.enable_cli' ) ) {
371 return 'apc';
372 }
373 } elseif ( function_exists( 'wincache_ucache_get' ) ) {
374 return 'wincache';
375 }
376
377 return CACHE_NONE;
378 }
379 }