Merge "Add `makeKey` and `makeGlobalKey` to BagOStuff"
[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::getMainClusterInstance()
51 * Purpose: Memory storage for per-cluster coordination and tracking.
52 * Stored centrally within the local data-center.
53 * Not replicated to other DCs.
54 * Also known as $wgMemc. Configured by $wgMainCacheType.
55 *
56 * - ObjectCache::getMainWANInstance()
57 * Purpose: Cache.
58 * Stored in the local data-center's main cache (uses different cache keys).
59 * Delete events are broadcasted to other DCs. See WANObjectCache for details.
60 *
61 * - ObjectCache::getMainStashInstance()
62 * Purpose: Ephemeral storage.
63 * Stored centrally within the local data-center.
64 * Changes are replicated to other DCs (eventually consistent).
65 * To retrieve the latest value (e.g. not from a slave), use BagOStuff:READ_LATEST.
66 * This store may be subject to LRU style evictions.
67 *
68 * - wfGetCache( $cacheType )
69 * Get a specific cache type by key in $wgObjectCaches.
70 *
71 * @ingroup Cache
72 */
73 class ObjectCache {
74 /** @var BagOStuff[] Map of (id => BagOStuff) */
75 public static $instances = array();
76 /** @var WANObjectCache[] Map of (id => WANObjectCache) */
77 public static $wanInstances = array();
78
79 /**
80 * Get a cached instance of the specified type of cache object.
81 *
82 * @param string $id A key in $wgObjectCaches.
83 * @return BagOStuff
84 */
85 public static function getInstance( $id ) {
86 if ( !isset( self::$instances[$id] ) ) {
87 self::$instances[$id] = self::newFromId( $id );
88 }
89
90 return self::$instances[$id];
91 }
92
93 /**
94 * Get a cached instance of the specified type of WAN cache object.
95 *
96 * @since 1.26
97 * @param string $id A key in $wgWANObjectCaches.
98 * @return WANObjectCache
99 */
100 public static function getWANInstance( $id ) {
101 if ( !isset( self::$wanInstances[$id] ) ) {
102 self::$wanInstances[$id] = self::newWANCacheFromId( $id );
103 }
104
105 return self::$wanInstances[$id];
106 }
107
108 /**
109 * Create a new cache object of the specified type.
110 *
111 * @param string $id A key in $wgObjectCaches.
112 * @return BagOStuff
113 * @throws MWException
114 */
115 public static function newFromId( $id ) {
116 global $wgObjectCaches;
117
118 if ( !isset( $wgObjectCaches[$id] ) ) {
119 throw new MWException( "Invalid object cache type \"$id\" requested. " .
120 "It is not present in \$wgObjectCaches." );
121 }
122
123 return self::newFromParams( $wgObjectCaches[$id] );
124 }
125
126 /**
127 * Get the default keyspace for this wiki.
128 *
129 * This is either the value of the `CachePrefix` configuration variable,
130 * or (if the former is unset) the `DBname` configuration variable, with
131 * `DBprefix` (if defined).
132 *
133 * @return string
134 */
135 public static function getDefaultKeyspace() {
136 global $wgCachePrefix, $wgDBname, $wgDBprefix;
137
138 $keyspace = $wgCachePrefix;
139 if ( is_string( $keyspace ) && $keyspace !== '' ) {
140 return $keyspace;
141 }
142
143 $keyspace = $wgDBname;
144 if ( is_string( $wgDBprefix ) && $wgDBprefix !== '' ) {
145 $keyspace .= '-' . $wgDBprefix;
146 }
147
148 return $keyspace;
149 }
150
151 /**
152 * Create a new cache object from parameters.
153 *
154 * @param array $params Must have 'factory' or 'class' property.
155 * - factory: Callback passed $params that returns BagOStuff.
156 * - class: BagOStuff subclass constructed with $params.
157 * - loggroup: Alias to set 'logger' key with LoggerFactory group.
158 * - .. Other parameters passed to factory or class.
159 * @return BagOStuff
160 * @throws MWException
161 */
162 public static function newFromParams( $params ) {
163 if ( isset( $params['loggroup'] ) ) {
164 $params['logger'] = LoggerFactory::getInstance( $params['loggroup'] );
165 } else {
166 // For backwards-compatability with custom parameters, lets not
167 // have all logging suddenly disappear
168 $params['logger'] = LoggerFactory::getInstance( 'objectcache' );
169 }
170 if ( !isset( $params['keyspace'] ) ) {
171 $params['keyspace'] = self::getDefaultKeyspace();
172 }
173 if ( isset( $params['factory'] ) ) {
174 return call_user_func( $params['factory'], $params );
175 } elseif ( isset( $params['class'] ) ) {
176 $class = $params['class'];
177 return new $class( $params );
178 } else {
179 throw new MWException( "The definition of cache type \""
180 . print_r( $params, true ) . "\" lacks both "
181 . "factory and class parameters." );
182 }
183 }
184
185 /**
186 * Factory function for CACHE_ANYTHING (referenced from DefaultSettings.php)
187 *
188 * CACHE_ANYTHING means that stuff has to be cached, not caching is not an option.
189 * If a caching method is configured for any of the main caches ($wgMainCacheType,
190 * $wgMessageCacheType, $wgParserCacheType), then CACHE_ANYTHING will effectively
191 * be an alias to the configured cache choice for that.
192 * If no cache choice is configured (by default $wgMainCacheType is CACHE_NONE),
193 * then CACHE_ANYTHING will forward to CACHE_DB.
194 *
195 * @param array $params
196 * @return BagOStuff
197 */
198 public static function newAnything( $params ) {
199 global $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType;
200 $candidates = array( $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType );
201 foreach ( $candidates as $candidate ) {
202 if ( $candidate !== CACHE_NONE && $candidate !== CACHE_ANYTHING ) {
203 return self::getInstance( $candidate );
204 }
205 }
206 return self::getInstance( CACHE_DB );
207 }
208
209 /**
210 * Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
211 *
212 * This will look for any APC style server-local cache.
213 * A fallback cache can be specified if none is found.
214 *
215 * // Direct calls
216 * ObjectCache::newAccelerator( $fallbackType );
217 *
218 * // From $wgObjectCaches via newFromParams()
219 * ObjectCache::newAccelerator( array( 'fallback' => $fallbackType ) );
220 *
221 * @param array $params [optional] Array key 'fallback' for $fallback.
222 * @param int|string $fallback Fallback cache, e.g. (CACHE_NONE, "hash") (since 1.24)
223 * @return BagOStuff
224 * @throws MWException
225 */
226 public static function newAccelerator( $params = array(), $fallback = null ) {
227 if ( $fallback === null ) {
228 // The is_array check here is needed because in PHP 5.3:
229 // $a = 'hash'; isset( $params['fallback'] ); yields true
230 if ( is_array( $params ) && isset( $params['fallback'] ) ) {
231 $fallback = $params['fallback'];
232 } elseif ( !is_array( $params ) ) {
233 $fallback = $params;
234 }
235 }
236 if ( function_exists( 'apc_fetch' ) ) {
237 $id = 'apc';
238 } elseif ( function_exists( 'xcache_get' ) && wfIniGetBool( 'xcache.var_size' ) ) {
239 $id = 'xcache';
240 } elseif ( function_exists( 'wincache_ucache_get' ) ) {
241 $id = 'wincache';
242 } else {
243 if ( $fallback === null ) {
244 throw new MWException( 'CACHE_ACCEL requested but no suitable object ' .
245 'cache is present. You may want to install APC.' );
246 }
247 $id = $fallback;
248 }
249 return self::newFromId( $id );
250 }
251
252 /**
253 * Factory function that creates a memcached client object.
254 *
255 * This always uses the PHP client, since the PECL client has a different
256 * hashing scheme and a different interpretation of the flags bitfield, so
257 * switching between the two clients randomly would be disastrous.
258 *
259 * @param array $params
260 * @return MemcachedPhpBagOStuff
261 */
262 public static function newMemcached( $params ) {
263 return new MemcachedPhpBagOStuff( $params );
264 }
265
266 /**
267 * Create a new cache object of the specified type.
268 *
269 * @since 1.26
270 * @param string $id A key in $wgWANObjectCaches.
271 * @return WANObjectCache
272 * @throws MWException
273 */
274 public static function newWANCacheFromId( $id ) {
275 global $wgWANObjectCaches;
276
277 if ( !isset( $wgWANObjectCaches[$id] ) ) {
278 throw new MWException( "Invalid object cache type \"$id\" requested. " .
279 "It is not present in \$wgWANObjectCaches." );
280 }
281
282 $params = $wgWANObjectCaches[$id];
283 $class = $params['relayerConfig']['class'];
284 $params['relayer'] = new $class( $params['relayerConfig'] );
285 $params['cache'] = self::newFromId( $params['cacheId'] );
286 $class = $params['class'];
287
288 return new $class( $params );
289 }
290
291 /**
292 * Get the main cluster-local cache object.
293 *
294 * @since 1.27
295 * @return BagOStuff
296 */
297 public static function getMainClusterInstance() {
298 global $wgMainCacheType;
299
300 return self::getInstance( $wgMainCacheType );
301 }
302
303 /**
304 * Get the main WAN cache object.
305 *
306 * @since 1.26
307 * @return WANObjectCache
308 */
309 public static function getMainWANInstance() {
310 global $wgMainWANCache;
311
312 return self::getWANInstance( $wgMainWANCache );
313 }
314
315 /**
316 * Get the cache object for the main stash.
317 *
318 * Stash objects are BagOStuff instances suitable for storing light
319 * weight data that is not canonically stored elsewhere (such as RDBMS).
320 * Stashes should be configured to propagate changes to all data-centers.
321 *
322 * Callers should be prepared for:
323 * - a) Writes to be slower in non-"primary" (e.g. HTTP GET/HEAD only) DCs
324 * - b) Reads to be eventually consistent, e.g. for get()/getMulti()
325 * In general, this means avoiding updates on idempotent HTTP requests and
326 * avoiding an assumption of perfect serializability (or accepting anomalies).
327 * Reads may be eventually consistent or data might rollback as nodes flap.
328 * Callers can use BagOStuff:READ_LATEST to see the latest available data.
329 *
330 * @return BagOStuff
331 * @since 1.26
332 */
333 public static function getMainStashInstance() {
334 global $wgMainStash;
335
336 return self::getInstance( $wgMainStash );
337 }
338
339 /**
340 * Clear all the cached instances.
341 */
342 public static function clear() {
343 self::$instances = array();
344 self::$wanInstances = array();
345 }
346 }