Merge "More specific @return doc in WikiPage::getDeletionUpdates"
[lhc/web/wiklou.git] / includes / libs / objectcache / BagOStuff.php
1 <?php
2 /**
3 * Copyright © 2003-2004 Brion Vibber <brion@pobox.com>
4 * https://www.mediawiki.org/
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 * @ingroup Cache
23 */
24
25 /**
26 * @defgroup Cache Cache
27 */
28
29 use Psr\Log\LoggerAwareInterface;
30 use Psr\Log\LoggerInterface;
31 use Psr\Log\NullLogger;
32
33 /**
34 * interface is intended to be more or less compatible with
35 * the PHP memcached client.
36 *
37 * backends for local hash array and SQL table included:
38 * @code
39 * $bag = new HashBagOStuff();
40 * $bag = new SqlBagOStuff(); # connect to db first
41 * @endcode
42 *
43 * @ingroup Cache
44 */
45 abstract class BagOStuff implements LoggerAwareInterface {
46 /** @var array[] Lock tracking */
47 protected $locks = array();
48 /** @var integer */
49 protected $lastError = self::ERR_NONE;
50
51 /** @var LoggerInterface */
52 protected $logger;
53
54 /** @var bool */
55 private $debugMode = false;
56
57 /** Possible values for getLastError() */
58 const ERR_NONE = 0; // no error
59 const ERR_NO_RESPONSE = 1; // no response
60 const ERR_UNREACHABLE = 2; // can't connect
61 const ERR_UNEXPECTED = 3; // response gave some error
62
63 /** Bitfield constants for get()/getMulti() */
64 const READ_LATEST = 1; // use latest data for replicated stores
65 const READ_VERIFIED = 2; // promise that caller can tell when keys are stale
66
67 public function __construct( array $params = array() ) {
68 if ( isset( $params['logger'] ) ) {
69 $this->setLogger( $params['logger'] );
70 } else {
71 $this->setLogger( new NullLogger() );
72 }
73 }
74
75 /**
76 * @param LoggerInterface $logger
77 * @return null
78 */
79 public function setLogger( LoggerInterface $logger ) {
80 $this->logger = $logger;
81 }
82
83 /**
84 * @param bool $bool
85 */
86 public function setDebug( $bool ) {
87 $this->debugMode = $bool;
88 }
89
90 /**
91 * Get an item with the given key, regenerating and setting it if not found
92 *
93 * If the callback returns false, then nothing is stored.
94 *
95 * @param string $key
96 * @param int $ttl Time-to-live (seconds)
97 * @param callable $callback Callback that derives the new value
98 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
99 * @return mixed The cached value if found or the result of $callback otherwise
100 * @since 1.27
101 */
102 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
103 $value = $this->get( $key, $flags );
104
105 if ( $value === false ) {
106 if ( !is_callable( $callback ) ) {
107 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
108 }
109 $value = call_user_func( $callback );
110 if ( $value !== false ) {
111 $this->set( $key, $value, $ttl );
112 }
113 }
114
115 return $value;
116 }
117
118 /**
119 * Get an item with the given key
120 *
121 * If the key includes a determistic input hash (e.g. the key can only have
122 * the correct value) or complete staleness checks are handled by the caller
123 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
124 * This lets tiered backends know they can safely upgrade a cached value to
125 * higher tiers using standard TTLs.
126 *
127 * @param string $key
128 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
129 * @param integer $oldFlags [unused]
130 * @return mixed Returns false on failure and if the item does not exist
131 */
132 public function get( $key, $flags = 0, $oldFlags = null ) {
133 // B/C for ( $key, &$casToken = null, $flags = 0 )
134 $flags = is_int( $oldFlags ) ? $oldFlags : $flags;
135
136 return $this->doGet( $key, $flags );
137 }
138
139 /**
140 * @param string $key
141 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
142 * @return mixed Returns false on failure and if the item does not exist
143 */
144 abstract protected function doGet( $key, $flags = 0 );
145
146 /**
147 * @note: This method is only needed if cas() is not is used for merge()
148 *
149 * @param string $key
150 * @param mixed $casToken
151 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
152 * @return mixed Returns false on failure and if the item does not exist
153 */
154 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
155 throw new Exception( __METHOD__ . ' not implemented.' );
156 }
157
158 /**
159 * Set an item
160 *
161 * @param string $key
162 * @param mixed $value
163 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
164 * @return bool Success
165 */
166 abstract public function set( $key, $value, $exptime = 0 );
167
168 /**
169 * Delete an item
170 *
171 * @param string $key
172 * @return bool True if the item was deleted or not found, false on failure
173 */
174 abstract public function delete( $key );
175
176 /**
177 * Merge changes into the existing cache value (possibly creating a new one).
178 * The callback function returns the new value given the current value
179 * (which will be false if not present), and takes the arguments:
180 * (this BagOStuff, cache key, current value).
181 *
182 * @param string $key
183 * @param callable $callback Callback method to be executed
184 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
185 * @param int $attempts The amount of times to attempt a merge in case of failure
186 * @return bool Success
187 * @throws InvalidArgumentException
188 */
189 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
190 if ( !is_callable( $callback ) ) {
191 throw new InvalidArgumentException( "Got invalid callback." );
192 }
193
194 return $this->mergeViaLock( $key, $callback, $exptime, $attempts );
195 }
196
197 /**
198 * @see BagOStuff::merge()
199 *
200 * @param string $key
201 * @param callable $callback Callback method to be executed
202 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
203 * @param int $attempts The amount of times to attempt a merge in case of failure
204 * @return bool Success
205 */
206 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
207 do {
208 $this->clearLastError();
209 $casToken = null; // passed by reference
210 $currentValue = $this->getWithToken( $key, $casToken, BagOStuff::READ_LATEST );
211 if ( $this->getLastError() ) {
212 return false; // don't spam retries (retry only on races)
213 }
214
215 // Derive the new value from the old value
216 $value = call_user_func( $callback, $this, $key, $currentValue );
217
218 $this->clearLastError();
219 if ( $value === false ) {
220 $success = true; // do nothing
221 } elseif ( $currentValue === false ) {
222 // Try to create the key, failing if it gets created in the meantime
223 $success = $this->add( $key, $value, $exptime );
224 } else {
225 // Try to update the key, failing if it gets changed in the meantime
226 $success = $this->cas( $casToken, $key, $value, $exptime );
227 }
228 if ( $this->getLastError() ) {
229 return false; // IO error; don't spam retries
230 }
231 } while ( !$success && --$attempts );
232
233 return $success;
234 }
235
236 /**
237 * Check and set an item
238 *
239 * @param mixed $casToken
240 * @param string $key
241 * @param mixed $value
242 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
243 * @return bool Success
244 * @throws Exception
245 */
246 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
247 throw new Exception( "CAS is not implemented in " . __CLASS__ );
248 }
249
250 /**
251 * @see BagOStuff::merge()
252 *
253 * @param string $key
254 * @param callable $callback Callback method to be executed
255 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
256 * @param int $attempts The amount of times to attempt a merge in case of failure
257 * @return bool Success
258 */
259 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10 ) {
260 if ( !$this->lock( $key, 6 ) ) {
261 return false;
262 }
263
264 $this->clearLastError();
265 $currentValue = $this->get( $key, BagOStuff::READ_LATEST );
266 if ( $this->getLastError() ) {
267 $success = false;
268 } else {
269 // Derive the new value from the old value
270 $value = call_user_func( $callback, $this, $key, $currentValue );
271 if ( $value === false ) {
272 $success = true; // do nothing
273 } else {
274 $success = $this->set( $key, $value, $exptime ); // set the new value
275 }
276 }
277
278 if ( !$this->unlock( $key ) ) {
279 // this should never happen
280 trigger_error( "Could not release lock for key '$key'." );
281 }
282
283 return $success;
284 }
285
286 /**
287 * Acquire an advisory lock on a key string
288 *
289 * Note that if reentry is enabled, duplicate calls ignore $expiry
290 *
291 * @param string $key
292 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
293 * @param int $expiry Lock expiry [optional]; 1 day maximum
294 * @param string $rclass Allow reentry if set and the current lock used this value
295 * @return bool Success
296 */
297 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
298 // Avoid deadlocks and allow lock reentry if specified
299 if ( isset( $this->locks[$key] ) ) {
300 if ( $rclass != '' && $this->locks[$key]['class'] === $rclass ) {
301 ++$this->locks[$key]['depth'];
302 return true;
303 } else {
304 return false;
305 }
306 }
307
308 $expiry = min( $expiry ?: INF, 86400 );
309
310 $this->clearLastError();
311 $timestamp = microtime( true ); // starting UNIX timestamp
312 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
313 $locked = true;
314 } elseif ( $this->getLastError() || $timeout <= 0 ) {
315 $locked = false; // network partition or non-blocking
316 } else {
317 $uRTT = ceil( 1e6 * ( microtime( true ) - $timestamp ) ); // estimate RTT (us)
318 $sleep = 2 * $uRTT; // rough time to do get()+set()
319
320 $attempts = 0; // failed attempts
321 do {
322 if ( ++$attempts >= 3 && $sleep <= 5e5 ) {
323 // Exponentially back off after failed attempts to avoid network spam.
324 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
325 $sleep *= 2;
326 }
327 usleep( $sleep ); // back off
328 $this->clearLastError();
329 $locked = $this->add( "{$key}:lock", 1, $expiry );
330 if ( $this->getLastError() ) {
331 $locked = false; // network partition
332 break;
333 }
334 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
335 }
336
337 if ( $locked ) {
338 $this->locks[$key] = array( 'class' => $rclass, 'depth' => 1 );
339 }
340
341 return $locked;
342 }
343
344 /**
345 * Release an advisory lock on a key string
346 *
347 * @param string $key
348 * @return bool Success
349 */
350 public function unlock( $key ) {
351 if ( isset( $this->locks[$key] ) && --$this->locks[$key]['depth'] <= 0 ) {
352 unset( $this->locks[$key] );
353
354 return $this->delete( "{$key}:lock" );
355 }
356
357 return true;
358 }
359
360 /**
361 * Get a lightweight exclusive self-unlocking lock
362 *
363 * Note that the same lock cannot be acquired twice.
364 *
365 * This is useful for task de-duplication or to avoid obtrusive
366 * (though non-corrupting) DB errors like INSERT key conflicts
367 * or deadlocks when using LOCK IN SHARE MODE.
368 *
369 * @param string $key
370 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
371 * @param int $expiry Lock expiry [optional]; 1 day maximum
372 * @param string $rclass Allow reentry if set and the current lock used this value
373 * @return ScopedCallback|null Returns null on failure
374 * @since 1.26
375 */
376 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
377 $expiry = min( $expiry ?: INF, 86400 );
378
379 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
380 return null;
381 }
382
383 $lSince = microtime( true ); // lock timestamp
384 // PHP 5.3: Can't use $this in a closure
385 $that = $this;
386 $logger = $this->logger;
387
388 return new ScopedCallback( function() use ( $that, $logger, $key, $lSince, $expiry ) {
389 $latency = .050; // latency skew (err towards keeping lock present)
390 $age = ( microtime( true ) - $lSince + $latency );
391 if ( ( $age + $latency ) >= $expiry ) {
392 $logger->warning( "Lock for $key held too long ($age sec)." );
393 return; // expired; it's not "safe" to delete the key
394 }
395 $that->unlock( $key );
396 } );
397 }
398
399 /**
400 * Delete all objects expiring before a certain date.
401 * @param string $date The reference date in MW format
402 * @param callable|bool $progressCallback Optional, a function which will be called
403 * regularly during long-running operations with the percentage progress
404 * as the first parameter.
405 *
406 * @return bool Success, false if unimplemented
407 */
408 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
409 // stub
410 return false;
411 }
412
413 /**
414 * Get an associative array containing the item for each of the keys that have items.
415 * @param array $keys List of strings
416 * @param integer $flags Bitfield; supports READ_LATEST [optional]
417 * @return array
418 */
419 public function getMulti( array $keys, $flags = 0 ) {
420 $res = array();
421 foreach ( $keys as $key ) {
422 $val = $this->get( $key );
423 if ( $val !== false ) {
424 $res[$key] = $val;
425 }
426 }
427 return $res;
428 }
429
430 /**
431 * Batch insertion
432 * @param array $data $key => $value assoc array
433 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
434 * @return bool Success
435 * @since 1.24
436 */
437 public function setMulti( array $data, $exptime = 0 ) {
438 $res = true;
439 foreach ( $data as $key => $value ) {
440 if ( !$this->set( $key, $value, $exptime ) ) {
441 $res = false;
442 }
443 }
444 return $res;
445 }
446
447 /**
448 * @param string $key
449 * @param mixed $value
450 * @param int $exptime
451 * @return bool Success
452 */
453 public function add( $key, $value, $exptime = 0 ) {
454 if ( $this->get( $key ) === false ) {
455 return $this->set( $key, $value, $exptime );
456 }
457 return false; // key already set
458 }
459
460 /**
461 * Increase stored value of $key by $value while preserving its TTL
462 * @param string $key Key to increase
463 * @param int $value Value to add to $key (Default 1)
464 * @return int|bool New value or false on failure
465 */
466 public function incr( $key, $value = 1 ) {
467 if ( !$this->lock( $key ) ) {
468 return false;
469 }
470 $n = $this->get( $key );
471 if ( $this->isInteger( $n ) ) { // key exists?
472 $n += intval( $value );
473 $this->set( $key, max( 0, $n ) ); // exptime?
474 } else {
475 $n = false;
476 }
477 $this->unlock( $key );
478
479 return $n;
480 }
481
482 /**
483 * Decrease stored value of $key by $value while preserving its TTL
484 * @param string $key
485 * @param int $value
486 * @return int|bool New value or false on failure
487 */
488 public function decr( $key, $value = 1 ) {
489 return $this->incr( $key, - $value );
490 }
491
492 /**
493 * Increase stored value of $key by $value while preserving its TTL
494 *
495 * This will create the key with value $init and TTL $ttl if not present
496 *
497 * @param string $key
498 * @param int $ttl
499 * @param int $value
500 * @param int $init
501 * @return bool
502 * @since 1.24
503 */
504 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
505 return $this->incr( $key, $value ) ||
506 $this->add( $key, (int)$init, $ttl ) || $this->incr( $key, $value );
507 }
508
509 /**
510 * Get the "last error" registered; clearLastError() should be called manually
511 * @return int ERR_* constant for the "last error" registry
512 * @since 1.23
513 */
514 public function getLastError() {
515 return $this->lastError;
516 }
517
518 /**
519 * Clear the "last error" registry
520 * @since 1.23
521 */
522 public function clearLastError() {
523 $this->lastError = self::ERR_NONE;
524 }
525
526 /**
527 * Set the "last error" registry
528 * @param int $err ERR_* constant
529 * @since 1.23
530 */
531 protected function setLastError( $err ) {
532 $this->lastError = $err;
533 }
534
535 /**
536 * Modify a cache update operation array for EventRelayer::notify()
537 *
538 * This is used for relayed writes, e.g. for broadcasting a change
539 * to multiple data-centers. If the array contains a 'val' field
540 * then the command involves setting a key to that value. Note that
541 * for simplicity, 'val' is always a simple scalar value. This method
542 * is used to possibly serialize the value and add any cache-specific
543 * key/values needed for the relayer daemon (e.g. memcached flags).
544 *
545 * @param array $event
546 * @return array
547 * @since 1.26
548 */
549 public function modifySimpleRelayEvent( array $event ) {
550 return $event;
551 }
552
553 /**
554 * @param string $text
555 */
556 protected function debug( $text ) {
557 if ( $this->debugMode ) {
558 $this->logger->debug( "{class} debug: $text", array(
559 'class' => get_class( $this ),
560 ) );
561 }
562 }
563
564 /**
565 * Convert an optionally relative time to an absolute time
566 * @param int $exptime
567 * @return int
568 */
569 protected function convertExpiry( $exptime ) {
570 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
571 return time() + $exptime;
572 } else {
573 return $exptime;
574 }
575 }
576
577 /**
578 * Convert an optionally absolute expiry time to a relative time. If an
579 * absolute time is specified which is in the past, use a short expiry time.
580 *
581 * @param int $exptime
582 * @return int
583 */
584 protected function convertToRelative( $exptime ) {
585 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
586 $exptime -= time();
587 if ( $exptime <= 0 ) {
588 $exptime = 1;
589 }
590 return $exptime;
591 } else {
592 return $exptime;
593 }
594 }
595
596 /**
597 * Check if a value is an integer
598 *
599 * @param mixed $value
600 * @return bool
601 */
602 protected function isInteger( $value ) {
603 return ( is_int( $value ) || ctype_digit( $value ) );
604 }
605 }