Merge "Don't check namespace in SpecialWantedtemplates"
[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
66 public function __construct( array $params = array() ) {
67 if ( isset( $params['logger'] ) ) {
68 $this->setLogger( $params['logger'] );
69 } else {
70 $this->setLogger( new NullLogger() );
71 }
72 }
73
74 /**
75 * @param LoggerInterface $logger
76 * @return null
77 */
78 public function setLogger( LoggerInterface $logger ) {
79 $this->logger = $logger;
80 }
81
82 /**
83 * @param bool $bool
84 */
85 public function setDebug( $bool ) {
86 $this->debugMode = $bool;
87 }
88
89 /**
90 * Get an item with the given key. Returns false if it does not exist.
91 * @param string $key
92 * @param mixed $casToken [optional]
93 * @param integer $flags Bitfield; supports READ_LATEST [optional]
94 * @return mixed Returns false on failure
95 */
96 abstract public function get( $key, &$casToken = null, $flags = 0 );
97
98 /**
99 * Set an item.
100 * @param string $key
101 * @param mixed $value
102 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
103 * @return bool Success
104 */
105 abstract public function set( $key, $value, $exptime = 0 );
106
107 /**
108 * Delete an item.
109 * @param string $key
110 * @return bool True if the item was deleted or not found, false on failure
111 */
112 abstract public function delete( $key );
113
114 /**
115 * Merge changes into the existing cache value (possibly creating a new one).
116 * The callback function returns the new value given the current value
117 * (which will be false if not present), and takes the arguments:
118 * (this BagOStuff, cache key, current value).
119 *
120 * @param string $key
121 * @param callable $callback Callback method to be executed
122 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
123 * @param int $attempts The amount of times to attempt a merge in case of failure
124 * @return bool Success
125 * @throws InvalidArgumentException
126 */
127 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
128 if ( !is_callable( $callback ) ) {
129 throw new InvalidArgumentException( "Got invalid callback." );
130 }
131
132 return $this->mergeViaLock( $key, $callback, $exptime, $attempts );
133 }
134
135 /**
136 * @see BagOStuff::merge()
137 *
138 * @param string $key
139 * @param callable $callback Callback method to be executed
140 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
141 * @param int $attempts The amount of times to attempt a merge in case of failure
142 * @return bool Success
143 */
144 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
145 do {
146 $this->clearLastError();
147 $casToken = null; // passed by reference
148 $currentValue = $this->get( $key, $casToken );
149 if ( $this->getLastError() ) {
150 return false; // don't spam retries (retry only on races)
151 }
152
153 // Derive the new value from the old value
154 $value = call_user_func( $callback, $this, $key, $currentValue );
155
156 $this->clearLastError();
157 if ( $value === false ) {
158 $success = true; // do nothing
159 } elseif ( $currentValue === false ) {
160 // Try to create the key, failing if it gets created in the meantime
161 $success = $this->add( $key, $value, $exptime );
162 } else {
163 // Try to update the key, failing if it gets changed in the meantime
164 $success = $this->cas( $casToken, $key, $value, $exptime );
165 }
166 if ( $this->getLastError() ) {
167 return false; // IO error; don't spam retries
168 }
169 } while ( !$success && --$attempts );
170
171 return $success;
172 }
173
174 /**
175 * Check and set an item
176 *
177 * @param mixed $casToken
178 * @param string $key
179 * @param mixed $value
180 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
181 * @return bool Success
182 * @throws Exception
183 */
184 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
185 throw new Exception( "CAS is not implemented in " . __CLASS__ );
186 }
187
188 /**
189 * @see BagOStuff::merge()
190 *
191 * @param string $key
192 * @param callable $callback Callback method to be executed
193 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
194 * @param int $attempts The amount of times to attempt a merge in case of failure
195 * @return bool Success
196 */
197 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10 ) {
198 if ( !$this->lock( $key, 6 ) ) {
199 return false;
200 }
201
202 $this->clearLastError();
203 $currentValue = $this->get( $key );
204 if ( $this->getLastError() ) {
205 $success = false;
206 } else {
207 // Derive the new value from the old value
208 $value = call_user_func( $callback, $this, $key, $currentValue );
209 if ( $value === false ) {
210 $success = true; // do nothing
211 } else {
212 $success = $this->set( $key, $value, $exptime ); // set the new value
213 }
214 }
215
216 if ( !$this->unlock( $key ) ) {
217 // this should never happen
218 trigger_error( "Could not release lock for key '$key'." );
219 }
220
221 return $success;
222 }
223
224 /**
225 * Acquire an advisory lock on a key string
226 *
227 * Note that if reentry is enabled, duplicate calls ignore $expiry
228 *
229 * @param string $key
230 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
231 * @param int $expiry Lock expiry [optional]; 1 day maximum
232 * @param string $rclass Allow reentry if set and the current lock used this value
233 * @return bool Success
234 */
235 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
236 // Avoid deadlocks and allow lock reentry if specified
237 if ( isset( $this->locks[$key] ) ) {
238 if ( $rclass != '' && $this->locks[$key]['class'] === $rclass ) {
239 ++$this->locks[$key]['depth'];
240 return true;
241 } else {
242 return false;
243 }
244 }
245
246 $expiry = min( $expiry ?: INF, 86400 );
247
248 $this->clearLastError();
249 $timestamp = microtime( true ); // starting UNIX timestamp
250 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
251 $locked = true;
252 } elseif ( $this->getLastError() || $timeout <= 0 ) {
253 $locked = false; // network partition or non-blocking
254 } else {
255 $uRTT = ceil( 1e6 * ( microtime( true ) - $timestamp ) ); // estimate RTT (us)
256 $sleep = 2 * $uRTT; // rough time to do get()+set()
257
258 $attempts = 0; // failed attempts
259 do {
260 if ( ++$attempts >= 3 && $sleep <= 5e5 ) {
261 // Exponentially back off after failed attempts to avoid network spam.
262 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
263 $sleep *= 2;
264 }
265 usleep( $sleep ); // back off
266 $this->clearLastError();
267 $locked = $this->add( "{$key}:lock", 1, $expiry );
268 if ( $this->getLastError() ) {
269 $locked = false; // network partition
270 break;
271 }
272 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
273 }
274
275 if ( $locked ) {
276 $this->locks[$key] = array( 'class' => $rclass, 'depth' => 1 );
277 }
278
279 return $locked;
280 }
281
282 /**
283 * Release an advisory lock on a key string
284 *
285 * @param string $key
286 * @return bool Success
287 */
288 public function unlock( $key ) {
289 if ( isset( $this->locks[$key] ) && --$this->locks[$key]['depth'] <= 0 ) {
290 unset( $this->locks[$key] );
291
292 return $this->delete( "{$key}:lock" );
293 }
294
295 return true;
296 }
297
298 /**
299 * Get a lightweight exclusive self-unlocking lock
300 *
301 * Note that the same lock cannot be acquired twice.
302 *
303 * This is useful for task de-duplication or to avoid obtrusive
304 * (though non-corrupting) DB errors like INSERT key conflicts
305 * or deadlocks when using LOCK IN SHARE MODE.
306 *
307 * @param string $key
308 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
309 * @param int $expiry Lock expiry [optional]; 1 day maximum
310 * @param string $rclass Allow reentry if set and the current lock used this value
311 * @return ScopedCallback|null Returns null on failure
312 * @since 1.26
313 */
314 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
315 $expiry = min( $expiry ?: INF, 86400 );
316
317 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
318 return null;
319 }
320
321 $lSince = microtime( true ); // lock timestamp
322 // PHP 5.3: Can't use $this in a closure
323 $that = $this;
324 $logger = $this->logger;
325
326 return new ScopedCallback( function() use ( $that, $logger, $key, $lSince, $expiry ) {
327 $latency = .050; // latency skew (err towards keeping lock present)
328 $age = ( microtime( true ) - $lSince + $latency );
329 if ( ( $age + $latency ) >= $expiry ) {
330 $logger->warning( "Lock for $key held too long ($age sec)." );
331 return; // expired; it's not "safe" to delete the key
332 }
333 $that->unlock( $key );
334 } );
335 }
336
337 /**
338 * Delete all objects expiring before a certain date.
339 * @param string $date The reference date in MW format
340 * @param callable|bool $progressCallback Optional, a function which will be called
341 * regularly during long-running operations with the percentage progress
342 * as the first parameter.
343 *
344 * @return bool Success, false if unimplemented
345 */
346 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
347 // stub
348 return false;
349 }
350
351 /**
352 * Get an associative array containing the item for each of the keys that have items.
353 * @param array $keys List of strings
354 * @param integer $flags Bitfield; supports READ_LATEST [optional]
355 * @return array
356 */
357 public function getMulti( array $keys, $flags = 0 ) {
358 $res = array();
359 foreach ( $keys as $key ) {
360 $val = $this->get( $key );
361 if ( $val !== false ) {
362 $res[$key] = $val;
363 }
364 }
365 return $res;
366 }
367
368 /**
369 * Batch insertion
370 * @param array $data $key => $value assoc array
371 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
372 * @return bool Success
373 * @since 1.24
374 */
375 public function setMulti( array $data, $exptime = 0 ) {
376 $res = true;
377 foreach ( $data as $key => $value ) {
378 if ( !$this->set( $key, $value, $exptime ) ) {
379 $res = false;
380 }
381 }
382 return $res;
383 }
384
385 /**
386 * @param string $key
387 * @param mixed $value
388 * @param int $exptime
389 * @return bool Success
390 */
391 public function add( $key, $value, $exptime = 0 ) {
392 if ( $this->get( $key ) === false ) {
393 return $this->set( $key, $value, $exptime );
394 }
395 return false; // key already set
396 }
397
398 /**
399 * Increase stored value of $key by $value while preserving its TTL
400 * @param string $key Key to increase
401 * @param int $value Value to add to $key (Default 1)
402 * @return int|bool New value or false on failure
403 */
404 public function incr( $key, $value = 1 ) {
405 if ( !$this->lock( $key ) ) {
406 return false;
407 }
408 $n = $this->get( $key );
409 if ( $this->isInteger( $n ) ) { // key exists?
410 $n += intval( $value );
411 $this->set( $key, max( 0, $n ) ); // exptime?
412 } else {
413 $n = false;
414 }
415 $this->unlock( $key );
416
417 return $n;
418 }
419
420 /**
421 * Decrease stored value of $key by $value while preserving its TTL
422 * @param string $key
423 * @param int $value
424 * @return int|bool New value or false on failure
425 */
426 public function decr( $key, $value = 1 ) {
427 return $this->incr( $key, - $value );
428 }
429
430 /**
431 * Increase stored value of $key by $value while preserving its TTL
432 *
433 * This will create the key with value $init and TTL $ttl if not present
434 *
435 * @param string $key
436 * @param int $ttl
437 * @param int $value
438 * @param int $init
439 * @return bool
440 * @since 1.24
441 */
442 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
443 return $this->incr( $key, $value ) ||
444 $this->add( $key, (int)$init, $ttl ) || $this->incr( $key, $value );
445 }
446
447 /**
448 * Get the "last error" registered; clearLastError() should be called manually
449 * @return int ERR_* constant for the "last error" registry
450 * @since 1.23
451 */
452 public function getLastError() {
453 return $this->lastError;
454 }
455
456 /**
457 * Clear the "last error" registry
458 * @since 1.23
459 */
460 public function clearLastError() {
461 $this->lastError = self::ERR_NONE;
462 }
463
464 /**
465 * Set the "last error" registry
466 * @param int $err ERR_* constant
467 * @since 1.23
468 */
469 protected function setLastError( $err ) {
470 $this->lastError = $err;
471 }
472
473 /**
474 * Modify a cache update operation array for EventRelayer::notify()
475 *
476 * This is used for relayed writes, e.g. for broadcasting a change
477 * to multiple data-centers. If the array contains a 'val' field
478 * then the command involves setting a key to that value. Note that
479 * for simplicity, 'val' is always a simple scalar value. This method
480 * is used to possibly serialize the value and add any cache-specific
481 * key/values needed for the relayer daemon (e.g. memcached flags).
482 *
483 * @param array $event
484 * @return array
485 * @since 1.26
486 */
487 public function modifySimpleRelayEvent( array $event ) {
488 return $event;
489 }
490
491 /**
492 * @param string $text
493 */
494 protected function debug( $text ) {
495 if ( $this->debugMode ) {
496 $this->logger->debug( "{class} debug: $text", array(
497 'class' => get_class( $this ),
498 ) );
499 }
500 }
501
502 /**
503 * Convert an optionally relative time to an absolute time
504 * @param int $exptime
505 * @return int
506 */
507 protected function convertExpiry( $exptime ) {
508 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
509 return time() + $exptime;
510 } else {
511 return $exptime;
512 }
513 }
514
515 /**
516 * Convert an optionally absolute expiry time to a relative time. If an
517 * absolute time is specified which is in the past, use a short expiry time.
518 *
519 * @param int $exptime
520 * @return int
521 */
522 protected function convertToRelative( $exptime ) {
523 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
524 $exptime -= time();
525 if ( $exptime <= 0 ) {
526 $exptime = 1;
527 }
528 return $exptime;
529 } else {
530 return $exptime;
531 }
532 }
533
534 /**
535 * Check if a value is an integer
536 *
537 * @param mixed $value
538 * @return bool
539 */
540 protected function isInteger( $value ) {
541 return ( is_int( $value ) || ctype_digit( $value ) );
542 }
543 }