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