Merge "Displaying search results for multiple wikis"
[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::newAccelerator( $fallbackType )
46 * Purpose: Cache for very hot keys.
47 * Stored only on the individual web server.
48 * Not associated with other servers.
49 *
50 * - ObjectCache::getMainWANInstance()
51 * Purpose: Cache.
52 * Stored in the local data-center's main cache (uses different cache keys).
53 * Delete events are broadcasted to other DCs. See WANObjectCache for details.
54 *
55 * - ObjectCache::getMainStashInstance()
56 * Purpose: Ephemeral storage.
57 * Stored centrally within the primary data-center.
58 * Changes are applied there first and replicated to other DCs (best-effort).
59 * To retrieve the latest value (e.g. not from a slave), use BagOStuff:READ_LATEST.
60 * This store may be subject to LRU style evictions.
61 *
62 * - ObjectCache::getLocalClusterInstance()
63 * Purpose: Memory storage for per-cluster coordination and tracking.
64 * A typical use case would be a rate limit counter or cache regeneration mutex.
65 * Stored centrally within the local data-center. Not replicated to other DCs.
66 * Also known as $wgMemc. Configured by $wgMainCacheType.
67 *
68 * - wfGetCache( $cacheType )
69 * Get a specific cache type by key in $wgObjectCaches.
70 *
71 * All the above cache instances (BagOStuff and WANObjectCache) have their makeKey()
72 * method scoped to the *current* wiki ID. Use makeGlobalKey() to avoid this scoping
73 * when using keys that need to be shared amongst wikis.
74 *
75 * @ingroup Cache
76 */
77 class ObjectCache {
78 /** @var BagOStuff[] Map of (id => BagOStuff) */
79 public static $instances = array();
80 /** @var WANObjectCache[] Map of (id => WANObjectCache) */
81 public static $wanInstances = array();
82
83 /**
84 * Get a cached instance of the specified type of cache object.
85 *
86 * @param string $id A key in $wgObjectCaches.
87 * @return BagOStuff
88 */
89 public static function getInstance( $id ) {
90 if ( !isset( self::$instances[$id] ) ) {
91 self::$instances[$id] = self::newFromId( $id );
92 }
93
94 return self::$instances[$id];
95 }
96
97 /**
98 * Get a cached instance of the specified type of WAN cache object.
99 *
100 * @since 1.26
101 * @param string $id A key in $wgWANObjectCaches.
102 * @return WANObjectCache
103 */
104 public static function getWANInstance( $id ) {
105 if ( !isset( self::$wanInstances[$id] ) ) {
106 self::$wanInstances[$id] = self::newWANCacheFromId( $id );
107 }
108
109 return self::$wanInstances[$id];
110 }
111
112 /**
113 * Create a new cache object of the specified type.
114 *
115 * @param string $id A key in $wgObjectCaches.
116 * @return BagOStuff
117 * @throws MWException
118 */
119 public static function newFromId( $id ) {
120 global $wgObjectCaches;
121
122 if ( !isset( $wgObjectCaches[$id] ) ) {
123 throw new MWException( "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 public static function getDefaultKeyspace() {
140 global $wgCachePrefix, $wgDBname, $wgDBprefix;
141
142 $keyspace = $wgCachePrefix;
143 if ( is_string( $keyspace ) && $keyspace !== '' ) {
144 return $keyspace;
145 }
146
147 $keyspace = $wgDBname;
148 if ( is_string( $wgDBprefix ) && $wgDBprefix !== '' ) {
149 $keyspace .= '-' . $wgDBprefix;
150 }
151
152 return $keyspace;
153 }
154
155 /**
156 * Create a new cache object from parameters.
157 *
158 * @param array $params Must have 'factory' or 'class' property.
159 * - factory: Callback passed $params that returns BagOStuff.
160 * - class: BagOStuff subclass constructed with $params.
161 * - loggroup: Alias to set 'logger' key with LoggerFactory group.
162 * - .. Other parameters passed to factory or class.
163 * @return BagOStuff
164 * @throws MWException
165 */
166 public static function newFromParams( $params ) {
167 if ( isset( $params['loggroup'] ) ) {
168 $params['logger'] = LoggerFactory::getInstance( $params['loggroup'] );
169 } else {
170 // For backwards-compatability with custom parameters, lets not
171 // have all logging suddenly disappear
172 $params['logger'] = LoggerFactory::getInstance( 'objectcache' );
173 }
174 if ( !isset( $params['keyspace'] ) ) {
175 $params['keyspace'] = self::getDefaultKeyspace();
176 }
177 if ( isset( $params['factory'] ) ) {
178 return call_user_func( $params['factory'], $params );
179 } elseif ( isset( $params['class'] ) ) {
180 $class = $params['class'];
181 // Automatically set the 'async' update handler
182 if ( $class === 'MultiWriteBagOStuff' ) {
183 $params['asyncHandler'] = isset( $params['asyncHandler'] )
184 ? $params['asyncHandler']
185 : 'DeferredUpdates::addCallableUpdate';
186 }
187 // Do b/c logic for MemcachedBagOStuff
188 if ( is_subclass_of( $class, 'MemcachedBagOStuff' ) ) {
189 if ( !isset( $params['servers'] ) ) {
190 $params['servers'] = $GLOBALS['wgMemCachedServers'];
191 }
192 if ( !isset( $params['debug'] ) ) {
193 $params['debug'] = $GLOBALS['wgMemCachedDebug'];
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 MWException( "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 = array( $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType );
226 foreach ( $candidates as $candidate ) {
227 if ( $candidate !== CACHE_NONE && $candidate !== CACHE_ANYTHING ) {
228 return self::getInstance( $candidate );
229 }
230 }
231 return self::getInstance( CACHE_DB );
232 }
233
234 /**
235 * Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
236 *
237 * This will look for any APC style server-local cache.
238 * A fallback cache can be specified if none is found.
239 *
240 * // Direct calls
241 * ObjectCache::newAccelerator( $fallbackType );
242 *
243 * // From $wgObjectCaches via newFromParams()
244 * ObjectCache::newAccelerator( array( 'fallback' => $fallbackType ) );
245 *
246 * @param array $params [optional] Array key 'fallback' for $fallback.
247 * @param int|string $fallback Fallback cache, e.g. (CACHE_NONE, "hash") (since 1.24)
248 * @return BagOStuff
249 * @throws MWException
250 */
251 public static function newAccelerator( $params = array(), $fallback = null ) {
252 if ( $fallback === null ) {
253 // The is_array check here is needed because in PHP 5.3:
254 // $a = 'hash'; isset( $params['fallback'] ); yields true
255 if ( is_array( $params ) && isset( $params['fallback'] ) ) {
256 $fallback = $params['fallback'];
257 } elseif ( !is_array( $params ) ) {
258 $fallback = $params;
259 }
260 }
261 if ( function_exists( 'apc_fetch' ) ) {
262 $id = 'apc';
263 } elseif ( function_exists( 'xcache_get' ) && wfIniGetBool( 'xcache.var_size' ) ) {
264 $id = 'xcache';
265 } elseif ( function_exists( 'wincache_ucache_get' ) ) {
266 $id = 'wincache';
267 } else {
268 if ( $fallback === null ) {
269 throw new MWException( 'CACHE_ACCEL requested but no suitable object ' .
270 'cache is present. You may want to install APC.' );
271 }
272 $id = $fallback;
273 }
274 return self::newFromId( $id );
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 MWException
284 */
285 public static function newWANCacheFromId( $id ) {
286 global $wgWANObjectCaches;
287
288 if ( !isset( $wgWANObjectCaches[$id] ) ) {
289 throw new MWException( "Invalid object cache type \"$id\" requested. " .
290 "It is not present in \$wgWANObjectCaches." );
291 }
292
293 $params = $wgWANObjectCaches[$id];
294 $class = $params['relayerConfig']['class'];
295 $params['relayer'] = new $class( $params['relayerConfig'] );
296 $params['cache'] = self::newFromId( $params['cacheId'] );
297 $class = $params['class'];
298
299 return new $class( $params );
300 }
301
302 /**
303 * Get the main cluster-local cache object.
304 *
305 * @since 1.27
306 * @return BagOStuff
307 */
308 public static function getLocalClusterInstance() {
309 global $wgMainCacheType;
310
311 return self::getInstance( $wgMainCacheType );
312 }
313
314 /**
315 * Get the main WAN cache object.
316 *
317 * @since 1.26
318 * @return WANObjectCache
319 */
320 public static function getMainWANInstance() {
321 global $wgMainWANCache;
322
323 return self::getWANInstance( $wgMainWANCache );
324 }
325
326 /**
327 * Get the cache object for the main stash.
328 *
329 * Stash objects are BagOStuff instances suitable for storing light
330 * weight data that is not canonically stored elsewhere (such as RDBMS).
331 * Stashes should be configured to propagate changes to all data-centers.
332 *
333 * Callers should be prepared for:
334 * - a) Writes to be slower in non-"primary" (e.g. HTTP GET/HEAD only) DCs
335 * - b) Reads to be eventually consistent, e.g. for get()/getMulti()
336 * In general, this means avoiding updates on idempotent HTTP requests and
337 * avoiding an assumption of perfect serializability (or accepting anomalies).
338 * Reads may be eventually consistent or data might rollback as nodes flap.
339 * Callers can use BagOStuff:READ_LATEST to see the latest available data.
340 *
341 * @return BagOStuff
342 * @since 1.26
343 */
344 public static function getMainStashInstance() {
345 global $wgMainStash;
346
347 return self::getInstance( $wgMainStash );
348 }
349
350 /**
351 * Clear all the cached instances.
352 */
353 public static function clear() {
354 self::$instances = array();
355 self::$wanInstances = array();
356 }
357 }