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