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