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
24 * Redis-based caching module for redis server >= 2.6.12
26 * @note: avoid use of Redis::MULTI transactions for twemproxy support
28 class RedisBagOStuff
extends BagOStuff
{
29 /** @var RedisConnectionPool */
31 /** @var array List of server names */
33 /** @var array Map of (tag => server name) */
34 protected $serverTagMap;
36 protected $automaticFailover;
39 * Construct a RedisBagOStuff object. Parameters are:
41 * - servers: An array of server names. A server name may be a hostname,
42 * a hostname/port combination or the absolute path of a UNIX socket.
43 * If a hostname is specified but no port, the standard port number
44 * 6379 will be used. Arrays keys can be used to specify the tag to
45 * hash on in place of the host/port. Required.
47 * - connectTimeout: The timeout for new connections, in seconds. Optional,
48 * default is 1 second.
50 * - persistent: Set this to true to allow connections to persist across
51 * multiple web requests. False by default.
53 * - password: The authentication password, will be sent to Redis in
54 * clear text. Optional, if it is unspecified, no AUTH command will be
57 * - automaticFailover: If this is false, then each key will be mapped to
58 * a single server, and if that server is down, any requests for that key
59 * will fail. If this is true, a connection failure will cause the client
60 * to immediately try the next server in the list (as determined by a
61 * consistent hashing algorithm). True by default. This has the
62 * potential to create consistency issues if a server is slow enough to
63 * flap, for example if it is in swap death.
64 * @param array $params
66 function __construct( $params ) {
67 parent
::__construct( $params );
68 $redisConf = array( 'serializer' => 'none' ); // manage that in this class
69 foreach ( array( 'connectTimeout', 'persistent', 'password' ) as $opt ) {
70 if ( isset( $params[$opt] ) ) {
71 $redisConf[$opt] = $params[$opt];
74 $this->redisPool
= RedisConnectionPool
::singleton( $redisConf );
76 $this->servers
= $params['servers'];
77 foreach ( $this->servers
as $key => $server ) {
78 $this->serverTagMap
[is_int( $key ) ?
$server : $key] = $server;
81 if ( isset( $params['automaticFailover'] ) ) {
82 $this->automaticFailover
= $params['automaticFailover'];
84 $this->automaticFailover
= true;
88 public function get( $key, &$casToken = null, $flags = 0 ) {
89 list( $server, $conn ) = $this->getConnection( $key );
94 $value = $conn->get( $key );
96 $result = $this->unserialize( $value );
97 } catch ( RedisException
$e ) {
99 $this->handleException( $conn, $e );
102 $this->logRequest( 'get', $key, $server, $result );
106 public function set( $key, $value, $expiry = 0 ) {
107 list( $server, $conn ) = $this->getConnection( $key );
111 $expiry = $this->convertToRelative( $expiry );
114 $result = $conn->setex( $key, $expiry, $this->serialize( $value ) );
116 // No expiry, that is very different from zero expiry in Redis
117 $result = $conn->set( $key, $this->serialize( $value ) );
119 } catch ( RedisException
$e ) {
121 $this->handleException( $conn, $e );
124 $this->logRequest( 'set', $key, $server, $result );
128 public function delete( $key ) {
129 list( $server, $conn ) = $this->getConnection( $key );
134 $conn->delete( $key );
135 // Return true even if the key didn't exist
137 } catch ( RedisException
$e ) {
139 $this->handleException( $conn, $e );
142 $this->logRequest( 'delete', $key, $server, $result );
146 public function getMulti( array $keys, $flags = 0 ) {
149 foreach ( $keys as $key ) {
150 list( $server, $conn ) = $this->getConnection( $key );
154 $conns[$server] = $conn;
155 $batches[$server][] = $key;
158 foreach ( $batches as $server => $batchKeys ) {
159 $conn = $conns[$server];
161 $conn->multi( Redis
::PIPELINE
);
162 foreach ( $batchKeys as $key ) {
165 $batchResult = $conn->exec();
166 if ( $batchResult === false ) {
167 $this->debug( "multi request to $server failed" );
170 foreach ( $batchResult as $i => $value ) {
171 if ( $value !== false ) {
172 $result[$batchKeys[$i]] = $this->unserialize( $value );
175 } catch ( RedisException
$e ) {
176 $this->handleException( $conn, $e );
180 $this->debug( "getMulti for " . count( $keys ) . " keys " .
181 "returned " . count( $result ) . " results" );
190 public function setMulti( array $data, $expiry = 0 ) {
193 foreach ( $data as $key => $value ) {
194 list( $server, $conn ) = $this->getConnection( $key );
198 $conns[$server] = $conn;
199 $batches[$server][] = $key;
202 $expiry = $this->convertToRelative( $expiry );
204 foreach ( $batches as $server => $batchKeys ) {
205 $conn = $conns[$server];
207 $conn->multi( Redis
::PIPELINE
);
208 foreach ( $batchKeys as $key ) {
210 $conn->setex( $key, $expiry, $this->serialize( $data[$key] ) );
212 $conn->set( $key, $this->serialize( $data[$key] ) );
215 $batchResult = $conn->exec();
216 if ( $batchResult === false ) {
217 $this->debug( "setMulti request to $server failed" );
220 foreach ( $batchResult as $value ) {
221 if ( $value === false ) {
225 } catch ( RedisException
$e ) {
226 $this->handleException( $server, $conn, $e );
234 public function add( $key, $value, $expiry = 0 ) {
235 list( $server, $conn ) = $this->getConnection( $key );
239 $expiry = $this->convertToRelative( $expiry );
242 $result = $conn->set(
244 $this->serialize( $value ),
245 array( 'nx', 'ex' => $expiry )
248 $result = $conn->setnx( $key, $this->serialize( $value ) );
250 } catch ( RedisException
$e ) {
252 $this->handleException( $conn, $e );
255 $this->logRequest( 'add', $key, $server, $result );
260 * Non-atomic implementation of incr().
262 * Probably all callers actually want incr() to atomically initialise
263 * values to zero if they don't exist, as provided by the Redis INCR
264 * command. But we are constrained by the memcached-like interface to
265 * return null in that case. Once the key exists, further increments are
267 * @param string $key Key to increase
268 * @param int $value Value to add to $key (Default 1)
269 * @return int|bool New value or false on failure
271 public function incr( $key, $value = 1 ) {
272 list( $server, $conn ) = $this->getConnection( $key );
276 if ( !$conn->exists( $key ) ) {
280 // @FIXME: on races, the key may have a 0 TTL
281 $result = $conn->incrBy( $key, $value );
282 } catch ( RedisException
$e ) {
284 $this->handleException( $conn, $e );
287 $this->logRequest( 'incr', $key, $server, $result );
291 public function modifySimpleRelayEvent( array $event ) {
292 if ( array_key_exists( 'val', $event ) ) {
293 $event['val'] = serialize( $event['val'] ); // this class uses PHP serialization
303 protected function serialize( $data ) {
304 // Serialize anything but integers so INCR/DECR work
305 // Do not store integer-like strings as integers to avoid type confusion (bug 60563)
306 return is_int( $data ) ?
$data : serialize( $data );
310 * @param string $data
313 protected function unserialize( $data ) {
314 return ctype_digit( $data ) ?
intval( $data ) : unserialize( $data );
318 * Get a Redis object with a connection suitable for fetching the specified key
320 * @return array (server, RedisConnRef) or (false, false)
322 protected function getConnection( $key ) {
323 $candidates = array_keys( $this->serverTagMap
);
325 if ( count( $this->servers
) > 1 ) {
326 ArrayUtils
::consistentHashSort( $candidates, $key, '/' );
327 if ( !$this->automaticFailover
) {
328 $candidates = array_slice( $candidates, 0, 1 );
332 while ( ( $tag = array_shift( $candidates ) ) !== null ) {
333 $server = $this->serverTagMap
[$tag];
334 $conn = $this->redisPool
->getConnection( $server );
339 // If automatic failover is enabled, check that the server's link
340 // to its master (if any) is up -- but only if there are other
341 // viable candidates left to consider. Also, getMasterLinkStatus()
342 // does not work with twemproxy, though $candidates will be empty
343 // by now in such cases.
344 if ( $this->automaticFailover
&& $candidates ) {
346 if ( $this->getMasterLinkStatus( $conn ) === 'down' ) {
347 // If the master cannot be reached, fail-over to the next server.
348 // If masters are in data-center A, and slaves in data-center B,
349 // this helps avoid the case were fail-over happens in A but not
350 // to the corresponding server in B (e.g. read/write mismatch).
353 } catch ( RedisException
$e ) {
354 // Server is not accepting commands
355 $this->handleException( $conn, $e );
360 return array( $server, $conn );
363 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
365 return array( false, false );
369 * Check the master link status of a Redis server that is configured as a slave.
370 * @param RedisConnRef $conn
371 * @return string|null Master link status (either 'up' or 'down'), or null
372 * if the server is not a slave.
374 protected function getMasterLinkStatus( RedisConnRef
$conn ) {
375 $info = $conn->info();
376 return isset( $info['master_link_status'] )
377 ?
$info['master_link_status']
385 protected function logError( $msg ) {
386 $this->logger
->error( "Redis error: $msg" );
390 * The redis extension throws an exception in response to various read, write
391 * and protocol errors. Sometimes it also closes the connection, sometimes
392 * not. The safest response for us is to explicitly destroy the connection
393 * object and let it be reopened during the next request.
394 * @param RedisConnRef $conn
395 * @param Exception $e
397 protected function handleException( RedisConnRef
$conn, $e ) {
398 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
399 $this->redisPool
->handleError( $conn, $e );
403 * Send information about a single request to the debug log
404 * @param string $method
406 * @param string $server
407 * @param bool $result
409 public function logRequest( $method, $key, $server, $result ) {
410 $this->debug( "$method $key on $server: " .
411 ( $result === false ?
"failure" : "success" ) );