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