Merge "Fixed getLagTimes() locking"
[lhc/web/wiklou.git] / includes / libs / objectcache / BagOStuff.php
1 <?php
2 /**
3 * Classes to cache objects in PHP accelerators, SQL database or DBA files
4 *
5 * Copyright © 2003-2004 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Cache
25 */
26
27 /**
28 * @defgroup Cache Cache
29 */
30
31 use Psr\Log\LoggerAwareInterface;
32 use Psr\Log\LoggerInterface;
33 use Psr\Log\NullLogger;
34
35 /**
36 * interface is intended to be more or less compatible with
37 * the PHP memcached client.
38 *
39 * backends for local hash array and SQL table included:
40 * <code>
41 * $bag = new HashBagOStuff();
42 * $bag = new SqlBagOStuff(); # connect to db first
43 * </code>
44 *
45 * @ingroup Cache
46 */
47 abstract class BagOStuff implements LoggerAwareInterface {
48 private $debugMode = false;
49
50 /** @var integer */
51 protected $lastError = self::ERR_NONE;
52
53 /**
54 * @var LoggerInterface
55 */
56 protected $logger;
57
58 /** Possible values for getLastError() */
59 const ERR_NONE = 0; // no error
60 const ERR_NO_RESPONSE = 1; // no response
61 const ERR_UNREACHABLE = 2; // can't connect
62 const ERR_UNEXPECTED = 3; // response gave some error
63
64 public function __construct( array $params = array() ) {
65 if ( isset( $params['logger'] ) ) {
66 $this->setLogger( $params['logger'] );
67 } else {
68 $this->setLogger( new NullLogger() );
69 }
70 }
71
72 /**
73 * @param LoggerInterface $logger
74 * @return null
75 */
76 public function setLogger( LoggerInterface $logger ) {
77 $this->logger = $logger;
78 }
79
80 /**
81 * @param bool $bool
82 */
83 public function setDebug( $bool ) {
84 $this->debugMode = $bool;
85 }
86
87 /**
88 * Get an item with the given key. Returns false if it does not exist.
89 * @param string $key
90 * @param mixed $casToken [optional]
91 * @return mixed Returns false on failure
92 */
93 abstract public function get( $key, &$casToken = null );
94
95 /**
96 * Set an item.
97 * @param string $key
98 * @param mixed $value
99 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
100 * @return bool Success
101 */
102 abstract public function set( $key, $value, $exptime = 0 );
103
104 /**
105 * Delete an item.
106 * @param string $key
107 * @return bool True if the item was deleted or not found, false on failure
108 */
109 abstract public function delete( $key );
110
111 /**
112 * Merge changes into the existing cache value (possibly creating a new one).
113 * The callback function returns the new value given the current value
114 * (which will be false if not present), and takes the arguments:
115 * (this BagOStuff, cache key, current value).
116 *
117 * @param string $key
118 * @param callable $callback Callback method to be executed
119 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
120 * @param int $attempts The amount of times to attempt a merge in case of failure
121 * @return bool Success
122 */
123 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
124 if ( !is_callable( $callback ) ) {
125 throw new Exception( "Got invalid callback." );
126 }
127
128 return $this->mergeViaLock( $key, $callback, $exptime, $attempts );
129 }
130
131 /**
132 * @see BagOStuff::merge()
133 *
134 * @param string $key
135 * @param callable $callback Callback method to be executed
136 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
137 * @param int $attempts The amount of times to attempt a merge in case of failure
138 * @return bool Success
139 */
140 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
141 do {
142 $casToken = null; // passed by reference
143 $currentValue = $this->get( $key, $casToken );
144 // Derive the new value from the old value
145 $value = call_user_func( $callback, $this, $key, $currentValue );
146
147 if ( $value === false ) {
148 $success = true; // do nothing
149 } elseif ( $currentValue === false ) {
150 // Try to create the key, failing if it gets created in the meantime
151 $success = $this->add( $key, $value, $exptime );
152 } else {
153 // Try to update the key, failing if it gets changed in the meantime
154 $success = $this->cas( $casToken, $key, $value, $exptime );
155 }
156 } while ( !$success && --$attempts );
157
158 return $success;
159 }
160
161 /**
162 * Check and set an item
163 *
164 * @param mixed $casToken
165 * @param string $key
166 * @param mixed $value
167 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
168 * @return bool Success
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 }