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