3 * Object caching using Redis (http://redis.io/).
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 class RedisBagOStuff
extends BagOStuff
{
24 /** @var RedisConnectionPool */
26 /** @var array List of server names */
28 /** @var array Map of (tag => server name) */
29 protected $serverTagMap;
31 protected $automaticFailover;
34 * Construct a RedisBagOStuff object. Parameters are:
36 * - servers: An array of server names. A server name may be a hostname,
37 * a hostname/port combination or the absolute path of a UNIX socket.
38 * If a hostname is specified but no port, the standard port number
39 * 6379 will be used. Arrays keys can be used to specify the tag to
40 * hash on in place of the host/port. Required.
42 * - connectTimeout: The timeout for new connections, in seconds. Optional,
43 * default is 1 second.
45 * - persistent: Set this to true to allow connections to persist across
46 * multiple web requests. False by default.
48 * - password: The authentication password, will be sent to Redis in
49 * clear text. Optional, if it is unspecified, no AUTH command will be
52 * - automaticFailover: If this is false, then each key will be mapped to
53 * a single server, and if that server is down, any requests for that key
54 * will fail. If this is true, a connection failure will cause the client
55 * to immediately try the next server in the list (as determined by a
56 * consistent hashing algorithm). True by default. This has the
57 * potential to create consistency issues if a server is slow enough to
58 * flap, for example if it is in swap death.
59 * @param array $params
61 function __construct( $params ) {
62 parent
::__construct( $params );
63 $redisConf = array( 'serializer' => 'none' ); // manage that in this class
64 foreach ( array( 'connectTimeout', 'persistent', 'password' ) as $opt ) {
65 if ( isset( $params[$opt] ) ) {
66 $redisConf[$opt] = $params[$opt];
69 $this->redisPool
= RedisConnectionPool
::singleton( $redisConf );
71 $this->servers
= $params['servers'];
72 foreach ( $this->servers
as $key => $server ) {
73 $this->serverTagMap
[is_int( $key ) ?
$server : $key] = $server;
76 if ( isset( $params['automaticFailover'] ) ) {
77 $this->automaticFailover
= $params['automaticFailover'];
79 $this->automaticFailover
= true;
83 public function get( $key, &$casToken = null ) {
85 list( $server, $conn ) = $this->getConnection( $key );
90 $value = $conn->get( $key );
92 $result = $this->unserialize( $value );
93 } catch ( RedisException
$e ) {
95 $this->handleException( $conn, $e );
98 $this->logRequest( 'get', $key, $server, $result );
102 public function set( $key, $value, $expiry = 0 ) {
104 list( $server, $conn ) = $this->getConnection( $key );
108 $expiry = $this->convertToRelative( $expiry );
111 $result = $conn->setex( $key, $expiry, $this->serialize( $value ) );
113 // No expiry, that is very different from zero expiry in Redis
114 $result = $conn->set( $key, $this->serialize( $value ) );
116 } catch ( RedisException
$e ) {
118 $this->handleException( $conn, $e );
121 $this->logRequest( 'set', $key, $server, $result );
125 protected function cas( $casToken, $key, $value, $expiry = 0 ) {
127 list( $server, $conn ) = $this->getConnection( $key );
131 $expiry = $this->convertToRelative( $expiry );
133 $conn->watch( $key );
135 if ( $this->serialize( $this->get( $key ) ) !== $casToken ) {
140 // multi()/exec() will fail atomically if the key changed since watch()
143 $conn->setex( $key, $expiry, $this->serialize( $value ) );
145 // No expiry, that is very different from zero expiry in Redis
146 $conn->set( $key, $this->serialize( $value ) );
148 $result = ( $conn->exec() == array( true ) );
149 } catch ( RedisException
$e ) {
151 $this->handleException( $conn, $e );
154 $this->logRequest( 'cas', $key, $server, $result );
158 public function delete( $key ) {
160 list( $server, $conn ) = $this->getConnection( $key );
165 $conn->delete( $key );
166 // Return true even if the key didn't exist
168 } catch ( RedisException
$e ) {
170 $this->handleException( $conn, $e );
173 $this->logRequest( 'delete', $key, $server, $result );
177 public function getMulti( array $keys ) {
181 foreach ( $keys as $key ) {
182 list( $server, $conn ) = $this->getConnection( $key );
186 $conns[$server] = $conn;
187 $batches[$server][] = $key;
190 foreach ( $batches as $server => $batchKeys ) {
191 $conn = $conns[$server];
193 $conn->multi( Redis
::PIPELINE
);
194 foreach ( $batchKeys as $key ) {
197 $batchResult = $conn->exec();
198 if ( $batchResult === false ) {
199 $this->debug( "multi request to $server failed" );
202 foreach ( $batchResult as $i => $value ) {
203 if ( $value !== false ) {
204 $result[$batchKeys[$i]] = $this->unserialize( $value );
207 } catch ( RedisException
$e ) {
208 $this->handleException( $conn, $e );
212 $this->debug( "getMulti for " . count( $keys ) . " keys " .
213 "returned " . count( $result ) . " results" );
222 public function setMulti( array $data, $expiry = 0 ) {
226 foreach ( $data as $key => $value ) {
227 list( $server, $conn ) = $this->getConnection( $key );
231 $conns[$server] = $conn;
232 $batches[$server][] = $key;
235 $expiry = $this->convertToRelative( $expiry );
237 foreach ( $batches as $server => $batchKeys ) {
238 $conn = $conns[$server];
240 $conn->multi( Redis
::PIPELINE
);
241 foreach ( $batchKeys as $key ) {
243 $conn->setex( $key, $expiry, $this->serialize( $data[$key] ) );
245 $conn->set( $key, $this->serialize( $data[$key] ) );
248 $batchResult = $conn->exec();
249 if ( $batchResult === false ) {
250 $this->debug( "setMulti request to $server failed" );
253 foreach ( $batchResult as $value ) {
254 if ( $value === false ) {
258 } catch ( RedisException
$e ) {
259 $this->handleException( $server, $conn, $e );
267 public function add( $key, $value, $expiry = 0 ) {
269 list( $server, $conn ) = $this->getConnection( $key );
273 $expiry = $this->convertToRelative( $expiry );
277 $conn->setnx( $key, $this->serialize( $value ) );
278 // @FIXME: this always bumps the TTL; use Redis 2.8 or Lua
279 $conn->expire( $key, $expiry );
280 $result = ( $conn->exec() == array( true, true ) );
282 $result = $conn->setnx( $key, $this->serialize( $value ) );
284 } catch ( RedisException
$e ) {
286 $this->handleException( $conn, $e );
289 $this->logRequest( 'add', $key, $server, $result );
294 * Non-atomic implementation of incr().
296 * Probably all callers actually want incr() to atomically initialise
297 * values to zero if they don't exist, as provided by the Redis INCR
298 * command. But we are constrained by the memcached-like interface to
299 * return null in that case. Once the key exists, further increments are
301 * @param string $key Key to increase
302 * @param int $value Value to add to $key (Default 1)
303 * @return int|bool New value or false on failure
305 public function incr( $key, $value = 1 ) {
307 list( $server, $conn ) = $this->getConnection( $key );
311 if ( !$conn->exists( $key ) ) {
315 // @FIXME: on races, the key may have a 0 TTL
316 $result = $conn->incrBy( $key, $value );
317 } catch ( RedisException
$e ) {
319 $this->handleException( $conn, $e );
322 $this->logRequest( 'incr', $key, $server, $result );
326 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
327 if ( !is_callable( $callback ) ) {
328 throw new Exception( "Got invalid callback." );
331 return $this->mergeViaCas( $key, $callback, $exptime, $attempts );
334 public function modifySimpleRelayEvent( array $event ) {
335 if ( array_key_exists( 'val', $event ) ) {
336 $event['val'] = serialize( $event['val'] ); // this class uses PHP serialization
346 protected function serialize( $data ) {
347 // Serialize anything but integers so INCR/DECR work
348 // Do not store integer-like strings as integers to avoid type confusion (bug 60563)
349 return is_int( $data ) ?
$data : serialize( $data );
353 * @param string $data
356 protected function unserialize( $data ) {
357 return ctype_digit( $data ) ?
intval( $data ) : unserialize( $data );
361 * Get a Redis object with a connection suitable for fetching the specified key
363 * @return array (server, RedisConnRef) or (false, false)
365 protected function getConnection( $key ) {
366 $candidates = array_keys( $this->serverTagMap
);
368 if ( count( $this->servers
) > 1 ) {
369 ArrayUtils
::consistentHashSort( $candidates, $key, '/' );
370 if ( !$this->automaticFailover
) {
371 $candidates = array_slice( $candidates, 0, 1 );
375 foreach ( $candidates as $tag ) {
376 $server = $this->serverTagMap
[$tag];
377 $conn = $this->redisPool
->getConnection( $server );
379 return array( $server, $conn );
383 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
385 return array( false, false );
392 protected function logError( $msg ) {
393 $this->logger
->error( "Redis error: $msg" );
397 * The redis extension throws an exception in response to various read, write
398 * and protocol errors. Sometimes it also closes the connection, sometimes
399 * not. The safest response for us is to explicitly destroy the connection
400 * object and let it be reopened during the next request.
401 * @param RedisConnRef $conn
402 * @param Exception $e
404 protected function handleException( RedisConnRef
$conn, $e ) {
405 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
406 $this->redisPool
->handleError( $conn, $e );
410 * Send information about a single request to the debug log
411 * @param string $method
413 * @param string $server
414 * @param bool $result
416 public function logRequest( $method, $key, $server, $result ) {
417 $this->debug( "$method $key on $server: " .
418 ( $result === false ?
"failure" : "success" ) );