Merge "Removed LocalFile::purgeHistory method"
[lhc/web/wiklou.git] / includes / libs / objectcache / WANObjectCache.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @ingroup Cache
20 * @author Aaron Schulz
21 */
22
23 /**
24 * Multi-datacenter aware caching interface
25 *
26 * All operations go to the local cache, except the delete()
27 * and touchCheckKey(), which broadcast to all clusters.
28 * This class is intended for caching data from primary stores.
29 * If the get() method does not return a value, then the caller
30 * should query the new value and backfill the cache using set().
31 * When the source data changes, the delete() method should be called.
32 * Since delete() is expensive, it should be avoided. One can do so if:
33 * - a) The object cached is immutable; or
34 * - b) Validity is checked against the source after get(); or
35 * - c) Using a modest TTL is reasonably correct and performant
36 * Consider using getWithSetCallback() instead of the get()/set() cycle.
37 *
38 * Instances of this class must be configured to point to a valid
39 * PubSub endpoint, and there must be listeners on the cache servers
40 * that subscribe to the endpoint and update the caches.
41 *
42 * Broadcasted operations like delete() and touchCheckKey() are done
43 * synchronously in the local cluster, but are relayed asynchronously.
44 * This means that callers in other datacenters will see older values
45 * for a however many milliseconds the datacenters are apart. As with
46 * any cache, this should not be relied on for cases where reads are
47 * used to determine writes to source (e.g. non-cache) data stores.
48 *
49 * All values are wrapped in metadata arrays. Keys use a "WANCache:" prefix
50 * to avoid collisions with keys that are not wrapped as metadata arrays. The
51 * prefixes are as follows:
52 * - a) "WANCache:v" : used for regular value keys
53 * - b) "WANCache:s" : used for temporarily storing values of tombstoned keys
54 * - c) "WANCache:t" : used for storing timestamp "check" keys
55 *
56 * @ingroup Cache
57 * @since 1.26
58 */
59 class WANObjectCache {
60 /** @var BagOStuff The local cluster cache */
61 protected $cache;
62 /** @var string Cache pool name */
63 protected $pool;
64 /** @var EventRelayer */
65 protected $relayer;
66
67 /** @var int */
68 protected $lastRelayError = self::ERR_NONE;
69
70 /** Seconds to tombstone keys on delete() */
71 const HOLDOFF_TTL = 10;
72 /** Seconds to keep dependency purge keys around */
73 const CHECK_KEY_TTL = 31536000; // 1 year
74 /** Seconds to keep lock keys around */
75 const LOCK_TTL = 5;
76
77 /** Cache format version number */
78 const VERSION = 1;
79
80 /** Fields of value holder arrays */
81 const FLD_VERSION = 0;
82 const FLD_VALUE = 1;
83 const FLD_TTL = 2;
84 const FLD_TIME = 3;
85
86 /** Possible values for getLastError() */
87 const ERR_NONE = 0; // no error
88 const ERR_NO_RESPONSE = 1; // no response
89 const ERR_UNREACHABLE = 2; // can't connect
90 const ERR_UNEXPECTED = 3; // response gave some error
91 const ERR_RELAY = 4; // relay broadcast failed
92
93 const VALUE_KEY_PREFIX = 'WANCache:v:';
94 const STASH_KEY_PREFIX = 'WANCache:s:';
95 const TIME_KEY_PREFIX = 'WANCache:t:';
96
97 const PURGE_VAL_PREFIX = 'PURGED:';
98
99 /**
100 * @param array $params
101 * - cache : BagOStuff object
102 * - pool : pool name
103 * - relayer : EventRelayer object
104 */
105 public function __construct( array $params ) {
106 $this->cache = $params['cache'];
107 $this->pool = $params['pool'];
108 $this->relayer = $params['relayer'];
109 }
110
111 /**
112 * Fetch the value of a key from cache
113 *
114 * If passed in, $curTTL is set to the remaining TTL (current time left):
115 * - a) INF; if the key exists and has no TTL
116 * - b) float (>=0); if the key exists and has a TTL
117 * - c) float (<0); if the key is tombstoned or expired by $checkKeys
118 * - d) null; if the key does not exist and is not tombstoned
119 *
120 * If a key is tombstoned, $curTTL will reflect the time since delete().
121 *
122 * The timestamp of $key will be checked against the last-purge timestamp
123 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
124 * initialized to the current timestamp. If any of $checkKeys have a timestamp
125 * greater than that of $key, then $curTTL will reflect how long ago $key
126 * became invalid. Callers can use $curTTL to know when the value is stale.
127 * The $checkKeys parameter allow mass invalidations by updating a single key:
128 * - a) Each "check" key represents "last purged" of some source data
129 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
130 * - c) When the source data that "check" keys represent changes,
131 * the touchCheckKey() method is called on them
132 *
133 * For keys that are hot/expensive, consider using getWithSetCallback() instead.
134 *
135 * @param string $key Cache key
136 * @param mixed $curTTL Approximate TTL left on the key if present [returned]
137 * @param array $checkKeys List of "check" keys
138 * @return mixed Value of cache key or false on failure
139 */
140 final public function get( $key, &$curTTL = null, array $checkKeys = array() ) {
141 $curTTLs = array();
142 $values = $this->getMulti( array( $key ), $curTTLs, $checkKeys );
143 $curTTL = isset( $curTTLs[$key] ) ? $curTTLs[$key] : null;
144
145 return isset( $values[$key] ) ? $values[$key] : false;
146 }
147
148 /**
149 * Fetch the value of several keys from cache
150 *
151 * @see WANObjectCache::get()
152 *
153 * @param array $keys List of cache keys
154 * @param array $curTTLs Map of (key => approximate TTL left) for existing keys [returned]
155 * @param array $checkKeys List of "check" keys
156 * @return array Map of (key => value) for keys that exist
157 */
158 final public function getMulti(
159 array $keys, &$curTTLs = array(), array $checkKeys = array()
160 ) {
161 $result = array();
162 $curTTLs = array();
163
164 $vPrefixLen = strlen( self::VALUE_KEY_PREFIX );
165 $valueKeys = self::prefixCacheKeys( $keys, self::VALUE_KEY_PREFIX );
166 $checkKeys = self::prefixCacheKeys( $checkKeys, self::TIME_KEY_PREFIX );
167
168 // Fetch all of the raw values
169 $wrappedValues = $this->cache->getMulti( array_merge( $valueKeys, $checkKeys ) );
170 $now = microtime( true );
171
172 // Get/initialize the timestamp of all the "check" keys
173 $checkKeyTimes = array();
174 foreach ( $checkKeys as $checkKey ) {
175 $timestamp = isset( $wrappedValues[$checkKey] )
176 ? self::parsePurgeValue( $wrappedValues[$checkKey] )
177 : false;
178 if ( !is_float( $timestamp ) ) {
179 // Key is not set or invalid; regenerate
180 $this->cache->add( $checkKey,
181 self::PURGE_VAL_PREFIX . $now, self::CHECK_KEY_TTL );
182 $timestamp = $now;
183 }
184
185 $checkKeyTimes[] = $timestamp;
186 }
187
188 // Get the main cache value for each key and validate them
189 foreach ( $valueKeys as $vKey ) {
190 if ( !isset( $wrappedValues[$vKey] ) ) {
191 continue; // not found
192 }
193
194 $key = substr( $vKey, $vPrefixLen ); // unprefix
195
196 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
197 if ( $value !== false ) {
198 $result[$key] = $value;
199 foreach ( $checkKeyTimes as $checkKeyTime ) {
200 // Force dependant keys to be invalid for a while after purging
201 // to reduce race conditions involving stale data getting cached
202 $safeTimestamp = $checkKeyTime + self::HOLDOFF_TTL;
203 if ( $safeTimestamp >= $wrappedValues[$vKey][self::FLD_TIME] ) {
204 $curTTL = min( $curTTL, $checkKeyTime - $now );
205 }
206 }
207 }
208
209 $curTTLs[$key] = $curTTL;
210 }
211
212 return $result;
213 }
214
215 /**
216 * Set the value of a key from cache
217 *
218 * Simply calling this method when source data changes is not valid because
219 * the changes do not replicate to the other WAN sites. In that case, delete()
220 * should be used instead. This method is intended for use on cache misses.
221 *
222 * @param string $key Cache key
223 * @param mixed $value
224 * @param integer $ttl Seconds to live [0=forever]
225 * @return bool Success
226 */
227 final public function set( $key, $value, $ttl = 0 ) {
228 $key = self::VALUE_KEY_PREFIX . $key;
229 $wrapped = $this->wrap( $value, $ttl );
230
231 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
232 return ( is_string( $cWrapped ) )
233 ? false // key is tombstoned; do nothing
234 : $wrapped;
235 };
236
237 return $this->cache->merge( $key, $func, $ttl, 1 );
238 }
239
240 /**
241 * Purge a key from all clusters
242 *
243 * This instantiates a hold-off period where the key cannot be
244 * written to avoid race conditions where dependent keys get updated
245 * with a stale value (e.g. from a DB slave).
246 *
247 * This should only be called when the underlying data (being cached)
248 * changes in a significant way. If called twice on the same key, then
249 * the last TTL takes precedence.
250 *
251 * @param string $key Cache key
252 * @param integer $ttl How long to block writes to the key [seconds]
253 * @return bool True if the item was purged or not found, false on failure
254 */
255 final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
256 $key = self::VALUE_KEY_PREFIX . $key;
257 // Update the local cluster immediately
258 $ok = $this->cache->set( $key, self::PURGE_VAL_PREFIX . microtime( true ), $ttl );
259 // Publish the purge to all clusters
260 return $this->relayPurge( $key, $ttl ) && $ok;
261 }
262
263 /**
264 * Fetch the value of a timestamp "check" key
265 *
266 * @param string $key
267 * @return float|bool TS_UNIX timestamp of the key; false if not present
268 */
269 final public function getCheckKeyTime( $key ) {
270 return self::parsePurgeValue( $this->cache->get( self::TIME_KEY_PREFIX . $key ) );
271 }
272
273 /**
274 * Purge a "check" key from all clusters, invalidating keys that use it
275 *
276 * This should only be called when the underlying data (being cached)
277 * changes in a significant way, and it is impractical to call delete()
278 * on all keys that should be changed. When get() is called on those
279 * keys, the relevant "check" keys must be supplied for this to work.
280 *
281 * The "check" key essentially represents a last-modified field.
282 * It is set in the future a few seconds when this is called, to
283 * avoid race conditions where dependent keys get updated with a
284 * stale value (e.g. from a DB slave).
285 *
286 * @see WANObjectCache::get()
287 *
288 * @param string $key Cache key
289 * @return bool True if the item was purged or not found, false on failure
290 */
291 final public function touchCheckKey( $key ) {
292 $key = self::TIME_KEY_PREFIX . $key;
293 // Update the local cluster immediately
294 $ok = $this->cache->set( $key,
295 self::PURGE_VAL_PREFIX . microtime( true ), self::CHECK_KEY_TTL );
296 // Publish the purge to all clusters
297 return $this->relayPurge( $key, self::CHECK_KEY_TTL ) && $ok;
298 }
299
300 /**
301 * Method to fetch/regenerate cache keys
302 *
303 * On cache miss, the key will be set to the callback result.
304 * The callback function returns the new value given the current
305 * value (false if not present). If false is returned, then nothing
306 * will be saved to cache.
307 *
308 * Most callers should ignore the current value, but it can be used
309 * to maintain "most recent X" values that come from time or sequence
310 * based source data, provided that the "as of" id/time is tracked.
311 *
312 * Usage of $checkKeys is the same as with get().
313 *
314 * The simplest way to avoid stampedes for hot keys is to use
315 * the 'lockTSE' option in $opts. If cache purges are needed, also:
316 * a) Pass $key into $checkKeys
317 * b) Use touchCheckKey( $key ) instead of delete( $key )
318 * Following this pattern lets the old cache be used until a
319 * single thread updates it as needed. Also consider tweaking
320 * the 'lowTTL' parameter.
321 *
322 * Example usage:
323 * <code>
324 * $key = wfMemcKey( 'cat-recent-actions', $catId );
325 * // Function that derives the new key value given the old value
326 * $callback = function( $cValue ) { ... };
327 * // Get the key value from cache or from source on cache miss;
328 * // try to only let one cluster thread manage doing cache updates
329 * $opts = array( 'lockTSE' => 5, 'lowTTL' => 10 );
330 * $value = $cache->getWithSetCallback( $key, $callback, 60, array(), $opts );
331 * </code>
332 *
333 * Example usage:
334 * <code>
335 * $key = wfMemcKey( 'cat-state', $catId );
336 * // The "check" keys that represent things the value depends on;
337 * // Calling touchCheckKey() on them invalidates "cat-state"
338 * $checkKeys = array(
339 * wfMemcKey( 'water-bowls', $houseId ),
340 * wfMemcKey( 'food-bowls', $houseId ),
341 * wfMemcKey( 'people-present', $houseId )
342 * );
343 * // Function that derives the new key value
344 * $callback = function() { ... };
345 * // Get the key value from cache or from source on cache miss;
346 * // try to only let one cluster thread manage doing cache updates
347 * $opts = array( 'lockTSE' => 5, 'lowTTL' => 10 );
348 * $value = $cache->getWithSetCallback( $key, $callback, 60, $checkKeys, $opts );
349 * </code>
350 *
351 * @see WANObjectCache::get()
352 *
353 * @param string $key Cache key
354 * @param callable $callback Value generation function
355 * @param integer $ttl Seconds to live when the key is updated [0=forever]
356 * @param array $checkKeys List of "check" keys
357 * @param array $opts Options map:
358 * - lowTTL : consider pre-emptive updates when the current TTL (sec)
359 * of the key is less than this. It becomes more likely
360 * over time, becoming a certainty once the key is expired.
361 * - lockTSE : if the key is tombstoned or expired less (by $checkKeys)
362 * than this many seconds ago, then try to have a single
363 * thread handle cache regeneration at any given time.
364 * Other threads will try to use stale values if possible.
365 * - tempTTL : when 'lockTSE' is set, this determines the TTL of the temp
366 * key used to cache values while a key is tombstoned.
367 * This avoids excessive regeneration of hot keys on delete() but
368 * may result in stale values.
369 * @return mixed Value to use for the key
370 */
371 final public function getWithSetCallback(
372 $key, $callback, $ttl, array $checkKeys = array(), array $opts = array()
373 ) {
374 $lowTTL = isset( $opts['lowTTL'] ) ? $opts['lowTTL'] : min( 10, $ttl );
375 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : -1;
376 $tempTTL = isset( $opts['tempTTL'] ) ? $opts['tempTTL'] : 5;
377
378 // Get the current key value
379 $curTTL = null;
380 $cValue = $this->get( $key, $curTTL, $checkKeys ); // current value
381 $value = $cValue; // return value
382
383 // Determine if a regeneration is desired
384 if ( $value !== false && $curTTL > 0 && !$this->worthRefresh( $curTTL, $lowTTL ) ) {
385 return $value;
386 }
387
388 if ( !is_callable( $callback ) ) {
389 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
390 }
391
392 // Assume a key is hot if requested soon after invalidation
393 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
394 $isTombstone = ( $curTTL !== null && $value === false );
395
396 $locked = false;
397 if ( $isHot || $isTombstone ) {
398 // Acquire a cluster-local non-blocking lock
399 if ( $this->cache->lock( $key, 0, self::LOCK_TTL ) ) {
400 // Lock acquired; this thread should update the key
401 $locked = true;
402 } elseif ( $value !== false ) {
403 // If it cannot be acquired; then the stale value can be used
404 return $value;
405 } else {
406 // Either another thread has the lock or the lock failed.
407 // Use the stash value, which is likely from the prior thread.
408 $value = $this->cache->get( self::STASH_KEY_PREFIX . $key );
409 // Regenerate on timeout or if the other thread failed
410 if ( $value !== false ) {
411 return $value;
412 }
413 }
414 }
415
416 // Generate the new value from the callback...
417 $value = call_user_func( $callback, $cValue );
418 // When delete() is called, writes are write-holed by the tombstone,
419 // so use a special stash key to pass the new value around threads.
420 if ( $value !== false && ( $isHot || $isTombstone ) ) {
421 $this->cache->set( self::STASH_KEY_PREFIX . $key, $value, $tempTTL );
422 }
423
424 if ( $locked ) {
425 $this->cache->unlock( $key );
426 }
427
428 if ( $value !== false ) {
429 // Update the cache; this will fail if the key is tombstoned
430 $this->set( $key, $value, $ttl );
431 }
432
433 return $value;
434 }
435
436 /**
437 * Get the "last error" registered; clearLastError() should be called manually
438 * @return int ERR_* constant for the "last error" registry
439 */
440 final public function getLastError() {
441 if ( $this->lastRelayError ) {
442 // If the cache and the relayer failed, focus on the later.
443 // An update not making it to the relayer means it won't show up
444 // in other DCs (nor will consistent re-hashing see up-to-date values).
445 // On the other hand, if just the cache update failed, then it should
446 // eventually be applied by the relayer.
447 return $this->lastRelayError;
448 }
449
450 $code = $this->cache->getLastError();
451 switch ( $code ) {
452 case BagOStuff::ERR_NONE:
453 return self::ERR_NONE;
454 case BagOStuff::ERR_NO_RESPONSE:
455 return self::ERR_NO_RESPONSE;
456 case BagOStuff::ERR_UNREACHABLE:
457 return self::ERR_UNREACHABLE;
458 default:
459 return self::ERR_UNEXPECTED;
460 }
461 }
462
463 /**
464 * Clear the "last error" registry
465 */
466 final public function clearLastError() {
467 $this->cache->clearLastError();
468 $this->lastRelayError = self::ERR_NONE;
469 }
470
471 /**
472 * Do the actual async bus purge of a key
473 *
474 * This must set the key to "PURGED:<UNIX timestamp>"
475 *
476 * @param string $key Cache key
477 * @param integer $ttl How long to keep the tombstone [seconds]
478 * @return bool Success
479 */
480 protected function relayPurge( $key, $ttl ) {
481 $event = $this->cache->modifySimpleRelayEvent( array(
482 'cmd' => 'set',
483 'key' => $key,
484 'val' => 'PURGED:$UNIXTIME$',
485 'ttl' => max( $ttl, 1 ),
486 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
487 ) );
488
489 $ok = $this->relayer->notify( "{$this->pool}:purge", $event );
490 if ( !$ok ) {
491 $this->lastRelayError = self::ERR_RELAY;
492 }
493
494 return $ok;
495 }
496
497 /**
498 * Check if a key should be regenerated (using random probability)
499 *
500 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance
501 * of returning true increases steadily from 0% to 100% as the $curTTL
502 * moves from $lowTTL to 0 seconds. This handles widely varying
503 * levels of cache access traffic.
504 *
505 * @param float|INF $curTTL Approximate TTL left on the key if present
506 * @param float $lowTTL Consider a refresh when $curTTL is less than this
507 * @return bool
508 */
509 protected function worthRefresh( $curTTL, $lowTTL ) {
510 if ( $curTTL >= $lowTTL ) {
511 return false;
512 } elseif ( $curTTL <= 0 ) {
513 return true;
514 }
515
516 $chance = ( 1 - $curTTL / $lowTTL );
517
518 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
519 }
520
521 /**
522 * Do not use this method outside WANObjectCache
523 *
524 * @param mixed $value
525 * @param integer $ttl [0=forever]
526 * @return string
527 */
528 protected function wrap( $value, $ttl ) {
529 return array(
530 self::FLD_VERSION => self::VERSION,
531 self::FLD_VALUE => $value,
532 self::FLD_TTL => $ttl,
533 self::FLD_TIME => microtime( true )
534 );
535 }
536
537 /**
538 * Do not use this method outside WANObjectCache
539 *
540 * @param array|string|bool $wrapped
541 * @param float $now Unix Current timestamp (preferrable pre-query)
542 * @return array (mixed; false if absent/invalid, current time left)
543 */
544 protected function unwrap( $wrapped, $now ) {
545 // Check if the value is a tombstone
546 $purgeTimestamp = self::parsePurgeValue( $wrapped );
547 if ( is_float( $purgeTimestamp ) ) {
548 // Purged values should always have a negative current $ttl
549 $curTTL = min( -0.000001, $purgeTimestamp - $now );
550 return array( false, $curTTL );
551 }
552
553 if ( !is_array( $wrapped ) // not found
554 || !isset( $wrapped[self::FLD_VERSION] ) // wrong format
555 || $wrapped[self::FLD_VERSION] !== self::VERSION // wrong version
556 ) {
557 return array( false, null );
558 }
559
560 if ( $wrapped[self::FLD_TTL] > 0 ) {
561 // Get the approximate time left on the key
562 $age = $now - $wrapped[self::FLD_TIME];
563 $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
564 } else {
565 // Key had no TTL, so the time left is unbounded
566 $curTTL = INF;
567 }
568
569 return array( $wrapped[self::FLD_VALUE], $curTTL );
570 }
571
572 /**
573 * @param array $keys
574 * @param string $prefix
575 * @return string[]
576 */
577 protected static function prefixCacheKeys( array $keys, $prefix ) {
578 $res = array();
579 foreach ( $keys as $key ) {
580 $res[] = $prefix . $key;
581 }
582
583 return $res;
584 }
585
586 /**
587 * @param string $value String like "PURGED:<timestamp>"
588 * @return float|bool UNIX timestamp or false on failure
589 */
590 protected static function parsePurgeValue( $value ) {
591 $m = array();
592 if ( is_string( $value ) &&
593 preg_match( '/^' . self::PURGE_VAL_PREFIX . '([^:]+)$/', $value, $m )
594 ) {
595 return (float)$m[1];
596 } else {
597 return false;
598 }
599 }
600 }