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
31 class RedisBagOStuff
extends BagOStuff
{
32 /** @var RedisConnectionPool */
34 /** @var array List of server names */
36 /** @var array Map of (tag => server name) */
37 protected $serverTagMap;
39 protected $automaticFailover;
42 * Construct a RedisBagOStuff object. Parameters are:
44 * - servers: An array of server names. A server name may be a hostname,
45 * a hostname/port combination or the absolute path of a UNIX socket.
46 * If a hostname is specified but no port, the standard port number
47 * 6379 will be used. Arrays keys can be used to specify the tag to
48 * hash on in place of the host/port. Required.
50 * - connectTimeout: The timeout for new connections, in seconds. Optional,
51 * default is 1 second.
53 * - persistent: Set this to true to allow connections to persist across
54 * multiple web requests. False by default.
56 * - password: The authentication password, will be sent to Redis in
57 * clear text. Optional, if it is unspecified, no AUTH command will be
60 * - automaticFailover: If this is false, then each key will be mapped to
61 * a single server, and if that server is down, any requests for that key
62 * will fail. If this is true, a connection failure will cause the client
63 * to immediately try the next server in the list (as determined by a
64 * consistent hashing algorithm). True by default. This has the
65 * potential to create consistency issues if a server is slow enough to
66 * flap, for example if it is in swap death.
67 * @param array $params
69 function __construct( $params ) {
70 parent
::__construct( $params );
71 $redisConf = [ 'serializer' => 'none' ]; // manage that in this class
72 foreach ( [ 'connectTimeout', 'persistent', 'password' ] as $opt ) {
73 if ( isset( $params[$opt] ) ) {
74 $redisConf[$opt] = $params[$opt];
77 $this->redisPool
= RedisConnectionPool
::singleton( $redisConf );
79 $this->servers
= $params['servers'];
80 foreach ( $this->servers
as $key => $server ) {
81 $this->serverTagMap
[is_int( $key ) ?
$server : $key] = $server;
84 $this->automaticFailover
= $params['automaticFailover'] ??
true;
86 $this->attrMap
[self
::ATTR_SYNCWRITES
] = self
::QOS_SYNCWRITES_NONE
;
89 protected function doGet( $key, $flags = 0, &$casToken = null ) {
92 list( $server, $conn ) = $this->getConnection( $key );
97 $value = $conn->get( $key );
99 $result = $this->unserialize( $value );
100 } catch ( RedisException
$e ) {
102 $this->handleException( $conn, $e );
105 $this->logRequest( 'get', $key, $server, $result );
109 protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
110 list( $server, $conn ) = $this->getConnection( $key );
114 $ttl = $this->convertToRelative( $exptime );
117 $result = $conn->setex( $key, $ttl, $this->serialize( $value ) );
119 // No expiry, that is very different from zero expiry in Redis
120 $result = $conn->set( $key, $this->serialize( $value ) );
122 } catch ( RedisException
$e ) {
124 $this->handleException( $conn, $e );
127 $this->logRequest( 'set', $key, $server, $result );
131 protected function doDelete( $key, $flags = 0 ) {
132 list( $server, $conn ) = $this->getConnection( $key );
137 $conn->delete( $key );
138 // Return true even if the key didn't exist
140 } catch ( RedisException
$e ) {
142 $this->handleException( $conn, $e );
145 $this->logRequest( 'delete', $key, $server, $result );
149 protected function doGetMulti( array $keys, $flags = 0 ) {
152 foreach ( $keys as $key ) {
153 list( $server, $conn ) = $this->getConnection( $key );
157 $conns[$server] = $conn;
158 $batches[$server][] = $key;
161 foreach ( $batches as $server => $batchKeys ) {
162 $conn = $conns[$server];
164 $conn->multi( Redis
::PIPELINE
);
165 foreach ( $batchKeys as $key ) {
168 $batchResult = $conn->exec();
169 if ( $batchResult === false ) {
170 $this->debug( "multi request to $server failed" );
173 foreach ( $batchResult as $i => $value ) {
174 if ( $value !== false ) {
175 $result[$batchKeys[$i]] = $this->unserialize( $value );
178 } catch ( RedisException
$e ) {
179 $this->handleException( $conn, $e );
183 $this->debug( "getMulti for " . count( $keys ) . " keys " .
184 "returned " . count( $result ) . " results" );
188 protected function doSetMulti( array $data, $expiry = 0, $flags = 0 ) {
191 foreach ( $data as $key => $value ) {
192 list( $server, $conn ) = $this->getConnection( $key );
196 $conns[$server] = $conn;
197 $batches[$server][] = $key;
200 $expiry = $this->convertToRelative( $expiry );
202 foreach ( $batches as $server => $batchKeys ) {
203 $conn = $conns[$server];
205 $conn->multi( Redis
::PIPELINE
);
206 foreach ( $batchKeys as $key ) {
208 $conn->setex( $key, $expiry, $this->serialize( $data[$key] ) );
210 $conn->set( $key, $this->serialize( $data[$key] ) );
213 $batchResult = $conn->exec();
214 if ( $batchResult === false ) {
215 $this->debug( "setMulti request to $server failed" );
218 foreach ( $batchResult as $value ) {
219 if ( $value === false ) {
223 } catch ( RedisException
$e ) {
224 $this->handleException( $conn, $e );
232 protected function doDeleteMulti( array $keys, $flags = 0 ) {
235 foreach ( $keys as $key ) {
236 list( $server, $conn ) = $this->getConnection( $key );
240 $conns[$server] = $conn;
241 $batches[$server][] = $key;
245 foreach ( $batches as $server => $batchKeys ) {
246 $conn = $conns[$server];
248 $conn->multi( Redis
::PIPELINE
);
249 foreach ( $batchKeys as $key ) {
250 $conn->delete( $key );
252 $batchResult = $conn->exec();
253 if ( $batchResult === false ) {
254 $this->debug( "deleteMulti request to $server failed" );
257 foreach ( $batchResult as $value ) {
258 if ( $value === false ) {
262 } catch ( RedisException
$e ) {
263 $this->handleException( $conn, $e );
271 public function add( $key, $value, $expiry = 0, $flags = 0 ) {
272 list( $server, $conn ) = $this->getConnection( $key );
276 $expiry = $this->convertToRelative( $expiry );
279 $result = $conn->set(
281 $this->serialize( $value ),
282 [ 'nx', 'ex' => $expiry ]
285 $result = $conn->setnx( $key, $this->serialize( $value ) );
287 } catch ( RedisException
$e ) {
289 $this->handleException( $conn, $e );
292 $this->logRequest( 'add', $key, $server, $result );
297 * Non-atomic implementation of incr().
299 * Probably all callers actually want incr() to atomically initialise
300 * values to zero if they don't exist, as provided by the Redis INCR
301 * command. But we are constrained by the memcached-like interface to
302 * return null in that case. Once the key exists, further increments are
304 * @param string $key Key to increase
305 * @param int $value Value to add to $key (Default 1)
306 * @return int|bool New value or false on failure
308 public function incr( $key, $value = 1 ) {
309 list( $server, $conn ) = $this->getConnection( $key );
314 if ( !$conn->exists( $key ) ) {
317 // @FIXME: on races, the key may have a 0 TTL
318 $result = $conn->incrBy( $key, $value );
319 } catch ( RedisException
$e ) {
321 $this->handleException( $conn, $e );
324 $this->logRequest( 'incr', $key, $server, $result );
328 protected function doChangeTTL( $key, $exptime, $flags ) {
329 list( $server, $conn ) = $this->getConnection( $key );
334 $relative = $this->expiryIsRelative( $exptime );
336 if ( $exptime == 0 ) {
337 $result = $conn->persist( $key );
338 $this->logRequest( 'persist', $key, $server, $result );
339 } elseif ( $relative ) {
340 $result = $conn->expire( $key, $this->convertToRelative( $exptime ) );
341 $this->logRequest( 'expire', $key, $server, $result );
343 $result = $conn->expireAt( $key, $this->convertToExpiry( $exptime ) );
344 $this->logRequest( 'expireAt', $key, $server, $result );
346 } catch ( RedisException
$e ) {
348 $this->handleException( $conn, $e );
355 * Get a Redis object with a connection suitable for fetching the specified key
357 * @return array (server, RedisConnRef) or (false, false)
359 protected function getConnection( $key ) {
360 $candidates = array_keys( $this->serverTagMap
);
362 if ( count( $this->servers
) > 1 ) {
363 ArrayUtils
::consistentHashSort( $candidates, $key, '/' );
364 if ( !$this->automaticFailover
) {
365 $candidates = array_slice( $candidates, 0, 1 );
369 while ( ( $tag = array_shift( $candidates ) ) !== null ) {
370 $server = $this->serverTagMap
[$tag];
371 $conn = $this->redisPool
->getConnection( $server, $this->logger
);
376 // If automatic failover is enabled, check that the server's link
377 // to its master (if any) is up -- but only if there are other
378 // viable candidates left to consider. Also, getMasterLinkStatus()
379 // does not work with twemproxy, though $candidates will be empty
380 // by now in such cases.
381 if ( $this->automaticFailover
&& $candidates ) {
383 if ( $this->getMasterLinkStatus( $conn ) === 'down' ) {
384 // If the master cannot be reached, fail-over to the next server.
385 // If masters are in data-center A, and replica DBs in data-center B,
386 // this helps avoid the case were fail-over happens in A but not
387 // to the corresponding server in B (e.g. read/write mismatch).
390 } catch ( RedisException
$e ) {
391 // Server is not accepting commands
392 $this->handleException( $conn, $e );
397 return [ $server, $conn ];
400 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
402 return [ false, false ];
406 * Check the master link status of a Redis server that is configured as a replica DB.
407 * @param RedisConnRef $conn
408 * @return string|null Master link status (either 'up' or 'down'), or null
409 * if the server is not a replica DB.
411 protected function getMasterLinkStatus( RedisConnRef
$conn ) {
412 $info = $conn->info();
413 return $info['master_link_status'] ??
null;
420 protected function logError( $msg ) {
421 $this->logger
->error( "Redis error: $msg" );
425 * The redis extension throws an exception in response to various read, write
426 * and protocol errors. Sometimes it also closes the connection, sometimes
427 * not. The safest response for us is to explicitly destroy the connection
428 * object and let it be reopened during the next request.
429 * @param RedisConnRef $conn
430 * @param RedisException $e
432 protected function handleException( RedisConnRef
$conn, $e ) {
433 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
434 $this->redisPool
->handleError( $conn, $e );
438 * Send information about a single request to the debug log
439 * @param string $method
441 * @param string $server
442 * @param bool $result
444 public function logRequest( $method, $key, $server, $result ) {
445 $this->debug( "$method $key on $server: " .
446 ( $result === false ?
"failure" : "success" ) );