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