Merge "Fix SQLite $wgObjectCaches definition + b/c handling"
[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 use MediaWiki\Services\ServiceDisabledException;
27
28 /**
29 * Functions to get cache objects
30 *
31 * The word "cache" has two main dictionary meanings, and both
32 * are used in this factory class. They are:
33 *
34 * - a) Cache (the computer science definition).
35 * A place to store copies or computations on existing data for
36 * higher access speeds.
37 * - b) Storage.
38 * A place to store lightweight data that is not canonically
39 * stored anywhere else (e.g. a "hoard" of objects).
40 *
41 * The former should always use strongly consistent stores, so callers don't
42 * have to deal with stale reads. The latter may be eventually consistent, but
43 * callers can use BagOStuff:READ_LATEST to see the latest available data.
44 *
45 * Primary entry points:
46 *
47 * - ObjectCache::getMainWANInstance()
48 * Purpose: Memory cache.
49 * Stored in the local data-center's main cache (keyspace different from local-cluster cache).
50 * Delete events are broadcasted to other DCs main cache. See WANObjectCache for details.
51 *
52 * - ObjectCache::getLocalServerInstance( $fallbackType )
53 * Purpose: Memory cache for very hot keys.
54 * Stored only on the individual web server (typically APC for web requests,
55 * and EmptyBagOStuff in CLI mode).
56 * Not replicated to the other servers.
57 *
58 * - ObjectCache::getLocalClusterInstance()
59 * Purpose: Memory storage for per-cluster coordination and tracking.
60 * A typical use case would be a rate limit counter or cache regeneration mutex.
61 * Stored centrally within the local data-center. Not replicated to other DCs.
62 * Configured by $wgMainCacheType.
63 *
64 * - ObjectCache::getMainStashInstance()
65 * Purpose: Ephemeral global storage.
66 * Stored centrally within the primary data-center.
67 * Changes are applied there first and replicated to other DCs (best-effort).
68 * To retrieve the latest value (e.g. not from a replica DB), use BagOStuff::READ_LATEST.
69 * This store may be subject to LRU style evictions.
70 *
71 * - ObjectCache::getInstance( $cacheType )
72 * Purpose: Special cases (like tiered memory/disk caches).
73 * Get a specific cache type by key in $wgObjectCaches.
74 *
75 * All the above cache instances (BagOStuff and WANObjectCache) have their makeKey()
76 * method scoped to the *current* wiki ID. Use makeGlobalKey() to avoid this scoping
77 * when using keys that need to be shared amongst wikis.
78 *
79 * @ingroup Cache
80 */
81 class ObjectCache {
82 /** @var BagOStuff[] Map of (id => BagOStuff) */
83 public static $instances = [];
84 /** @var WANObjectCache[] Map of (id => WANObjectCache) */
85 public static $wanInstances = [];
86
87 /**
88 * Get a cached instance of the specified type of cache object.
89 *
90 * @param string $id A key in $wgObjectCaches.
91 * @return BagOStuff
92 */
93 public static function getInstance( $id ) {
94 if ( !isset( self::$instances[$id] ) ) {
95 self::$instances[$id] = self::newFromId( $id );
96 }
97
98 return self::$instances[$id];
99 }
100
101 /**
102 * Get a cached instance of the specified type of WAN cache object.
103 *
104 * @since 1.26
105 * @param string $id A key in $wgWANObjectCaches.
106 * @return WANObjectCache
107 */
108 public static function getWANInstance( $id ) {
109 if ( !isset( self::$wanInstances[$id] ) ) {
110 self::$wanInstances[$id] = self::newWANCacheFromId( $id );
111 }
112
113 return self::$wanInstances[$id];
114 }
115
116 /**
117 * Create a new cache object of the specified type.
118 *
119 * @param string $id A key in $wgObjectCaches.
120 * @return BagOStuff
121 * @throws MWException
122 */
123 public static function newFromId( $id ) {
124 global $wgObjectCaches;
125
126 if ( !isset( $wgObjectCaches[$id] ) ) {
127 throw new MWException( "Invalid object cache type \"$id\" requested. " .
128 "It is not present in \$wgObjectCaches." );
129 }
130
131 return self::newFromParams( $wgObjectCaches[$id] );
132 }
133
134 /**
135 * Get the default keyspace for this wiki.
136 *
137 * This is either the value of the `CachePrefix` configuration variable,
138 * or (if the former is unset) the `DBname` configuration variable, with
139 * `DBprefix` (if defined).
140 *
141 * @return string
142 */
143 public static function getDefaultKeyspace() {
144 global $wgCachePrefix;
145
146 $keyspace = $wgCachePrefix;
147 if ( is_string( $keyspace ) && $keyspace !== '' ) {
148 return $keyspace;
149 }
150
151 return wfWikiID();
152 }
153
154 /**
155 * Create a new cache object from parameters.
156 *
157 * @param array $params Must have 'factory' or 'class' property.
158 * - factory: Callback passed $params that returns BagOStuff.
159 * - class: BagOStuff subclass constructed with $params.
160 * - loggroup: Alias to set 'logger' key with LoggerFactory group.
161 * - .. Other parameters passed to factory or class.
162 * @return BagOStuff
163 * @throws MWException
164 */
165 public static function newFromParams( $params ) {
166 if ( isset( $params['loggroup'] ) ) {
167 $params['logger'] = LoggerFactory::getInstance( $params['loggroup'] );
168 } else {
169 $params['logger'] = LoggerFactory::getInstance( 'objectcache' );
170 }
171 if ( !isset( $params['keyspace'] ) ) {
172 $params['keyspace'] = self::getDefaultKeyspace();
173 }
174 if ( isset( $params['factory'] ) ) {
175 return call_user_func( $params['factory'], $params );
176 } elseif ( isset( $params['class'] ) ) {
177 $class = $params['class'];
178 // Automatically set the 'async' update handler
179 $params['asyncHandler'] = isset( $params['asyncHandler'] )
180 ? $params['asyncHandler']
181 : 'DeferredUpdates::addCallableUpdate';
182 // Enable reportDupes by default
183 $params['reportDupes'] = isset( $params['reportDupes'] )
184 ? $params['reportDupes']
185 : true;
186 // Do b/c logic for SqlBagOStuff
187 if ( is_subclass_of( $class, SqlBagOStuff::class ) ) {
188 if ( isset( $params['server'] ) && !isset( $params['servers'] ) ) {
189 $params['servers'] = [ $params['server'] ];
190 unset( $param['server'] );
191 }
192 // In the past it was not required to set 'dbDirectory' in $wgObjectCaches
193 if ( isset( $params['servers'] ) ) {
194 foreach ( $params['servers'] as &$server ) {
195 if ( $server['type'] === 'sqlite' && !isset( $server['dbDirectory'] ) ) {
196 $server['dbDirectory'] = MediaWikiServices::getInstance()
197 ->getMainConfig()->get( 'SQLiteDataDir' );
198 }
199 }
200 }
201 }
202
203 // Do b/c logic for MemcachedBagOStuff
204 if ( is_subclass_of( $class, MemcachedBagOStuff::class ) ) {
205 if ( !isset( $params['servers'] ) ) {
206 $params['servers'] = $GLOBALS['wgMemCachedServers'];
207 }
208 if ( !isset( $params['debug'] ) ) {
209 $params['debug'] = $GLOBALS['wgMemCachedDebug'];
210 }
211 if ( !isset( $params['persistent'] ) ) {
212 $params['persistent'] = $GLOBALS['wgMemCachedPersistent'];
213 }
214 if ( !isset( $params['timeout'] ) ) {
215 $params['timeout'] = $GLOBALS['wgMemCachedTimeout'];
216 }
217 }
218 return new $class( $params );
219 } else {
220 throw new MWException( "The definition of cache type \""
221 . print_r( $params, true ) . "\" lacks both "
222 . "factory and class parameters." );
223 }
224 }
225
226 /**
227 * Factory function for CACHE_ANYTHING (referenced from DefaultSettings.php)
228 *
229 * CACHE_ANYTHING means that stuff has to be cached, not caching is not an option.
230 * If a caching method is configured for any of the main caches ($wgMainCacheType,
231 * $wgMessageCacheType, $wgParserCacheType), then CACHE_ANYTHING will effectively
232 * be an alias to the configured cache choice for that.
233 * If no cache choice is configured (by default $wgMainCacheType is CACHE_NONE),
234 * then CACHE_ANYTHING will forward to CACHE_DB.
235 *
236 * @param array $params
237 * @return BagOStuff
238 */
239 public static function newAnything( $params ) {
240 global $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType;
241 $candidates = [ $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType ];
242 foreach ( $candidates as $candidate ) {
243 if ( $candidate !== CACHE_NONE && $candidate !== CACHE_ANYTHING ) {
244 return self::getInstance( $candidate );
245 }
246 }
247
248 if ( MediaWikiServices::getInstance()->isServiceDisabled( 'DBLoadBalancer' ) ) {
249 // The LoadBalancer is disabled, probably because
250 // MediaWikiServices::disableStorageBackend was called.
251 $candidate = CACHE_NONE;
252 } else {
253 $candidate = CACHE_DB;
254 }
255
256 return self::getInstance( $candidate );
257 }
258
259 /**
260 * Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
261 *
262 * This will look for any APC style server-local cache.
263 * A fallback cache can be specified if none is found.
264 *
265 * // Direct calls
266 * ObjectCache::getLocalServerInstance( $fallbackType );
267 *
268 * // From $wgObjectCaches via newFromParams()
269 * ObjectCache::getLocalServerInstance( [ 'fallback' => $fallbackType ] );
270 *
271 * @param int|string|array $fallback Fallback cache or parameter map with 'fallback'
272 * @return BagOStuff
273 * @throws MWException
274 * @since 1.27
275 */
276 public static function getLocalServerInstance( $fallback = CACHE_NONE ) {
277 if ( function_exists( 'apc_fetch' ) ) {
278 $id = 'apc';
279 } elseif ( function_exists( 'xcache_get' ) && wfIniGetBool( 'xcache.var_size' ) ) {
280 $id = 'xcache';
281 } elseif ( function_exists( 'wincache_ucache_get' ) ) {
282 $id = 'wincache';
283 } else {
284 if ( is_array( $fallback ) ) {
285 $id = isset( $fallback['fallback'] ) ? $fallback['fallback'] : CACHE_NONE;
286 } else {
287 $id = $fallback;
288 }
289 }
290
291 return self::getInstance( $id );
292 }
293
294 /**
295 * @param array $params [optional] Array key 'fallback' for $fallback.
296 * @param int|string $fallback Fallback cache, e.g. (CACHE_NONE, "hash") (since 1.24)
297 * @return BagOStuff
298 * @deprecated since 1.27
299 */
300 public static function newAccelerator( $params = [], $fallback = null ) {
301 if ( $fallback === null ) {
302 if ( is_array( $params ) && isset( $params['fallback'] ) ) {
303 $fallback = $params['fallback'];
304 } elseif ( !is_array( $params ) ) {
305 $fallback = $params;
306 }
307 }
308
309 return self::getLocalServerInstance( $fallback );
310 }
311
312 /**
313 * Create a new cache object of the specified type.
314 *
315 * @since 1.26
316 * @param string $id A key in $wgWANObjectCaches.
317 * @return WANObjectCache
318 * @throws MWException
319 */
320 public static function newWANCacheFromId( $id ) {
321 global $wgWANObjectCaches;
322
323 if ( !isset( $wgWANObjectCaches[$id] ) ) {
324 throw new MWException( "Invalid object cache type \"$id\" requested. " .
325 "It is not present in \$wgWANObjectCaches." );
326 }
327
328 $params = $wgWANObjectCaches[$id];
329 foreach ( $params['channels'] as $action => $channel ) {
330 $params['relayers'][$action] = MediaWikiServices::getInstance()->getEventRelayerGroup()
331 ->getRelayer( $channel );
332 $params['channels'][$action] = $channel;
333 }
334 $params['cache'] = self::newFromId( $params['cacheId'] );
335 if ( isset( $params['loggroup'] ) ) {
336 $params['logger'] = LoggerFactory::getInstance( $params['loggroup'] );
337 } else {
338 $params['logger'] = LoggerFactory::getInstance( 'objectcache' );
339 }
340 $class = $params['class'];
341
342 return new $class( $params );
343 }
344
345 /**
346 * Get the main cluster-local cache object.
347 *
348 * @since 1.27
349 * @return BagOStuff
350 */
351 public static function getLocalClusterInstance() {
352 global $wgMainCacheType;
353
354 return self::getInstance( $wgMainCacheType );
355 }
356
357 /**
358 * Get the main WAN cache object.
359 *
360 * @since 1.26
361 * @return WANObjectCache
362 */
363 public static function getMainWANInstance() {
364 global $wgMainWANCache;
365
366 return self::getWANInstance( $wgMainWANCache );
367 }
368
369 /**
370 * Get the cache object for the main stash.
371 *
372 * Stash objects are BagOStuff instances suitable for storing light
373 * weight data that is not canonically stored elsewhere (such as RDBMS).
374 * Stashes should be configured to propagate changes to all data-centers.
375 *
376 * Callers should be prepared for:
377 * - a) Writes to be slower in non-"primary" (e.g. HTTP GET/HEAD only) DCs
378 * - b) Reads to be eventually consistent, e.g. for get()/getMulti()
379 * In general, this means avoiding updates on idempotent HTTP requests and
380 * avoiding an assumption of perfect serializability (or accepting anomalies).
381 * Reads may be eventually consistent or data might rollback as nodes flap.
382 * Callers can use BagOStuff:READ_LATEST to see the latest available data.
383 *
384 * @return BagOStuff
385 * @since 1.26
386 */
387 public static function getMainStashInstance() {
388 global $wgMainStash;
389
390 return self::getInstance( $wgMainStash );
391 }
392
393 /**
394 * Clear all the cached instances.
395 */
396 public static function clear() {
397 self::$instances = [];
398 self::$wanInstances = [];
399 }
400 }