Merge "Hide signup/login/logout links when they would not work"
[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 MemcachedBagOStuff
187 if ( is_subclass_of( $class, 'MemcachedBagOStuff' ) ) {
188 if ( !isset( $params['servers'] ) ) {
189 $params['servers'] = $GLOBALS['wgMemCachedServers'];
190 }
191 if ( !isset( $params['debug'] ) ) {
192 $params['debug'] = $GLOBALS['wgMemCachedDebug'];
193 }
194 if ( !isset( $params['persistent'] ) ) {
195 $params['persistent'] = $GLOBALS['wgMemCachedPersistent'];
196 }
197 if ( !isset( $params['timeout'] ) ) {
198 $params['timeout'] = $GLOBALS['wgMemCachedTimeout'];
199 }
200 }
201 return new $class( $params );
202 } else {
203 throw new MWException( "The definition of cache type \""
204 . print_r( $params, true ) . "\" lacks both "
205 . "factory and class parameters." );
206 }
207 }
208
209 /**
210 * Factory function for CACHE_ANYTHING (referenced from DefaultSettings.php)
211 *
212 * CACHE_ANYTHING means that stuff has to be cached, not caching is not an option.
213 * If a caching method is configured for any of the main caches ($wgMainCacheType,
214 * $wgMessageCacheType, $wgParserCacheType), then CACHE_ANYTHING will effectively
215 * be an alias to the configured cache choice for that.
216 * If no cache choice is configured (by default $wgMainCacheType is CACHE_NONE),
217 * then CACHE_ANYTHING will forward to CACHE_DB.
218 *
219 * @param array $params
220 * @return BagOStuff
221 */
222 public static function newAnything( $params ) {
223 global $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType;
224 $candidates = [ $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType ];
225 foreach ( $candidates as $candidate ) {
226 if ( $candidate !== CACHE_NONE && $candidate !== CACHE_ANYTHING ) {
227 return self::getInstance( $candidate );
228 }
229 }
230
231 if ( MediaWikiServices::getInstance()->isServiceDisabled( 'DBLoadBalancer' ) ) {
232 // The LoadBalancer is disabled, probably because
233 // MediaWikiServices::disableStorageBackend was called.
234 $candidate = CACHE_NONE;
235 } else {
236 $candidate = CACHE_DB;
237 }
238
239 return self::getInstance( $candidate );
240 }
241
242 /**
243 * Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
244 *
245 * This will look for any APC style server-local cache.
246 * A fallback cache can be specified if none is found.
247 *
248 * // Direct calls
249 * ObjectCache::getLocalServerInstance( $fallbackType );
250 *
251 * // From $wgObjectCaches via newFromParams()
252 * ObjectCache::getLocalServerInstance( [ 'fallback' => $fallbackType ] );
253 *
254 * @param int|string|array $fallback Fallback cache or parameter map with 'fallback'
255 * @return BagOStuff
256 * @throws MWException
257 * @since 1.27
258 */
259 public static function getLocalServerInstance( $fallback = CACHE_NONE ) {
260 if ( function_exists( 'apc_fetch' ) ) {
261 $id = 'apc';
262 } elseif ( function_exists( 'xcache_get' ) && wfIniGetBool( 'xcache.var_size' ) ) {
263 $id = 'xcache';
264 } elseif ( function_exists( 'wincache_ucache_get' ) ) {
265 $id = 'wincache';
266 } else {
267 if ( is_array( $fallback ) ) {
268 $id = isset( $fallback['fallback'] ) ? $fallback['fallback'] : CACHE_NONE;
269 } else {
270 $id = $fallback;
271 }
272 }
273
274 return self::getInstance( $id );
275 }
276
277 /**
278 * @param array $params [optional] Array key 'fallback' for $fallback.
279 * @param int|string $fallback Fallback cache, e.g. (CACHE_NONE, "hash") (since 1.24)
280 * @return BagOStuff
281 * @deprecated since 1.27
282 */
283 public static function newAccelerator( $params = [], $fallback = null ) {
284 if ( $fallback === null ) {
285 if ( is_array( $params ) && isset( $params['fallback'] ) ) {
286 $fallback = $params['fallback'];
287 } elseif ( !is_array( $params ) ) {
288 $fallback = $params;
289 }
290 }
291
292 return self::getLocalServerInstance( $fallback );
293 }
294
295 /**
296 * Create a new cache object of the specified type.
297 *
298 * @since 1.26
299 * @param string $id A key in $wgWANObjectCaches.
300 * @return WANObjectCache
301 * @throws MWException
302 */
303 public static function newWANCacheFromId( $id ) {
304 global $wgWANObjectCaches;
305
306 if ( !isset( $wgWANObjectCaches[$id] ) ) {
307 throw new MWException( "Invalid object cache type \"$id\" requested. " .
308 "It is not present in \$wgWANObjectCaches." );
309 }
310
311 $params = $wgWANObjectCaches[$id];
312 foreach ( $params['channels'] as $action => $channel ) {
313 $params['relayers'][$action] = MediaWikiServices::getInstance()->getEventRelayerGroup()
314 ->getRelayer( $channel );
315 $params['channels'][$action] = $channel;
316 }
317 $params['cache'] = self::newFromId( $params['cacheId'] );
318 if ( isset( $params['loggroup'] ) ) {
319 $params['logger'] = LoggerFactory::getInstance( $params['loggroup'] );
320 } else {
321 $params['logger'] = LoggerFactory::getInstance( 'objectcache' );
322 }
323 $class = $params['class'];
324
325 return new $class( $params );
326 }
327
328 /**
329 * Get the main cluster-local cache object.
330 *
331 * @since 1.27
332 * @return BagOStuff
333 */
334 public static function getLocalClusterInstance() {
335 global $wgMainCacheType;
336
337 return self::getInstance( $wgMainCacheType );
338 }
339
340 /**
341 * Get the main WAN cache object.
342 *
343 * @since 1.26
344 * @return WANObjectCache
345 */
346 public static function getMainWANInstance() {
347 global $wgMainWANCache;
348
349 return self::getWANInstance( $wgMainWANCache );
350 }
351
352 /**
353 * Get the cache object for the main stash.
354 *
355 * Stash objects are BagOStuff instances suitable for storing light
356 * weight data that is not canonically stored elsewhere (such as RDBMS).
357 * Stashes should be configured to propagate changes to all data-centers.
358 *
359 * Callers should be prepared for:
360 * - a) Writes to be slower in non-"primary" (e.g. HTTP GET/HEAD only) DCs
361 * - b) Reads to be eventually consistent, e.g. for get()/getMulti()
362 * In general, this means avoiding updates on idempotent HTTP requests and
363 * avoiding an assumption of perfect serializability (or accepting anomalies).
364 * Reads may be eventually consistent or data might rollback as nodes flap.
365 * Callers can use BagOStuff:READ_LATEST to see the latest available data.
366 *
367 * @return BagOStuff
368 * @since 1.26
369 */
370 public static function getMainStashInstance() {
371 global $wgMainStash;
372
373 return self::getInstance( $wgMainStash );
374 }
375
376 /**
377 * Clear all the cached instances.
378 */
379 public static function clear() {
380 self::$instances = [];
381 self::$wanInstances = [];
382 }
383 }