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 ) {
92 return $this->getWithToken( $key, $casToken, $flags );
95 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
96 list( $server, $conn ) = $this->getConnection( $key );
101 $value = $conn->get( $key );
103 $result = $this->unserialize( $value );
104 } catch ( RedisException
$e ) {
106 $this->handleException( $conn, $e );
109 $this->logRequest( 'get', $key, $server, $result );
113 public function set( $key, $value, $expiry = 0, $flags = 0 ) {
114 list( $server, $conn ) = $this->getConnection( $key );
118 $expiry = $this->convertToRelative( $expiry );
121 $result = $conn->setex( $key, $expiry, $this->serialize( $value ) );
123 // No expiry, that is very different from zero expiry in Redis
124 $result = $conn->set( $key, $this->serialize( $value ) );
126 } catch ( RedisException
$e ) {
128 $this->handleException( $conn, $e );
131 $this->logRequest( 'set', $key, $server, $result );
135 public function delete( $key, $flags = 0 ) {
136 list( $server, $conn ) = $this->getConnection( $key );
141 $conn->delete( $key );
142 // Return true even if the key didn't exist
144 } catch ( RedisException
$e ) {
146 $this->handleException( $conn, $e );
149 $this->logRequest( 'delete', $key, $server, $result );
153 public function getMulti( array $keys, $flags = 0 ) {
156 foreach ( $keys as $key ) {
157 list( $server, $conn ) = $this->getConnection( $key );
161 $conns[$server] = $conn;
162 $batches[$server][] = $key;
165 foreach ( $batches as $server => $batchKeys ) {
166 $conn = $conns[$server];
168 $conn->multi( Redis
::PIPELINE
);
169 foreach ( $batchKeys as $key ) {
172 $batchResult = $conn->exec();
173 if ( $batchResult === false ) {
174 $this->debug( "multi request to $server failed" );
177 foreach ( $batchResult as $i => $value ) {
178 if ( $value !== false ) {
179 $result[$batchKeys[$i]] = $this->unserialize( $value );
182 } catch ( RedisException
$e ) {
183 $this->handleException( $conn, $e );
187 $this->debug( "getMulti for " . count( $keys ) . " keys " .
188 "returned " . count( $result ) . " results" );
197 public function setMulti( array $data, $expiry = 0 ) {
200 foreach ( $data as $key => $value ) {
201 list( $server, $conn ) = $this->getConnection( $key );
205 $conns[$server] = $conn;
206 $batches[$server][] = $key;
209 $expiry = $this->convertToRelative( $expiry );
211 foreach ( $batches as $server => $batchKeys ) {
212 $conn = $conns[$server];
214 $conn->multi( Redis
::PIPELINE
);
215 foreach ( $batchKeys as $key ) {
217 $conn->setex( $key, $expiry, $this->serialize( $data[$key] ) );
219 $conn->set( $key, $this->serialize( $data[$key] ) );
222 $batchResult = $conn->exec();
223 if ( $batchResult === false ) {
224 $this->debug( "setMulti request to $server failed" );
227 foreach ( $batchResult as $value ) {
228 if ( $value === false ) {
232 } catch ( RedisException
$e ) {
233 $this->handleException( $conn, $e );
241 public function add( $key, $value, $expiry = 0 ) {
242 list( $server, $conn ) = $this->getConnection( $key );
246 $expiry = $this->convertToRelative( $expiry );
249 $result = $conn->set(
251 $this->serialize( $value ),
252 [ 'nx', 'ex' => $expiry ]
255 $result = $conn->setnx( $key, $this->serialize( $value ) );
257 } catch ( RedisException
$e ) {
259 $this->handleException( $conn, $e );
262 $this->logRequest( 'add', $key, $server, $result );
266 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
267 return $this->mergeViaCas( $key, $callback, $exptime, $attempts );
271 * Non-atomic implementation of incr().
273 * Probably all callers actually want incr() to atomically initialise
274 * values to zero if they don't exist, as provided by the Redis INCR
275 * command. But we are constrained by the memcached-like interface to
276 * return null in that case. Once the key exists, further increments are
278 * @param string $key Key to increase
279 * @param int $value Value to add to $key (Default 1)
280 * @return int|bool New value or false on failure
282 public function incr( $key, $value = 1 ) {
283 list( $server, $conn ) = $this->getConnection( $key );
288 if ( !$conn->exists( $key ) ) {
291 // @FIXME: on races, the key may have a 0 TTL
292 $result = $conn->incrBy( $key, $value );
293 } catch ( RedisException
$e ) {
295 $this->handleException( $conn, $e );
298 $this->logRequest( 'incr', $key, $server, $result );
302 public function changeTTL( $key, $expiry = 0 ) {
303 list( $server, $conn ) = $this->getConnection( $key );
308 $expiry = $this->convertToRelative( $expiry );
310 $result = $conn->expire( $key, $expiry );
311 } catch ( RedisException
$e ) {
313 $this->handleException( $conn, $e );
316 $this->logRequest( 'expire', $key, $server, $result );
324 protected function serialize( $data ) {
325 // Serialize anything but integers so INCR/DECR work
326 // Do not store integer-like strings as integers to avoid type confusion (T62563)
327 return is_int( $data ) ?
$data : serialize( $data );
331 * @param string $data
334 protected function unserialize( $data ) {
335 $int = intval( $data );
336 return $data === (string)$int ?
$int : unserialize( $data );
340 * Get a Redis object with a connection suitable for fetching the specified key
342 * @return array (server, RedisConnRef) or (false, false)
344 protected function getConnection( $key ) {
345 $candidates = array_keys( $this->serverTagMap
);
347 if ( count( $this->servers
) > 1 ) {
348 ArrayUtils
::consistentHashSort( $candidates, $key, '/' );
349 if ( !$this->automaticFailover
) {
350 $candidates = array_slice( $candidates, 0, 1 );
354 while ( ( $tag = array_shift( $candidates ) ) !== null ) {
355 $server = $this->serverTagMap
[$tag];
356 $conn = $this->redisPool
->getConnection( $server, $this->logger
);
361 // If automatic failover is enabled, check that the server's link
362 // to its master (if any) is up -- but only if there are other
363 // viable candidates left to consider. Also, getMasterLinkStatus()
364 // does not work with twemproxy, though $candidates will be empty
365 // by now in such cases.
366 if ( $this->automaticFailover
&& $candidates ) {
368 if ( $this->getMasterLinkStatus( $conn ) === 'down' ) {
369 // If the master cannot be reached, fail-over to the next server.
370 // If masters are in data-center A, and replica DBs in data-center B,
371 // this helps avoid the case were fail-over happens in A but not
372 // to the corresponding server in B (e.g. read/write mismatch).
375 } catch ( RedisException
$e ) {
376 // Server is not accepting commands
377 $this->handleException( $conn, $e );
382 return [ $server, $conn ];
385 $this->setLastError( BagOStuff
::ERR_UNREACHABLE
);
387 return [ false, false ];
391 * Check the master link status of a Redis server that is configured as a replica DB.
392 * @param RedisConnRef $conn
393 * @return string|null Master link status (either 'up' or 'down'), or null
394 * if the server is not a replica DB.
396 protected function getMasterLinkStatus( RedisConnRef
$conn ) {
397 $info = $conn->info();
398 return $info['master_link_status'] ??
null;
405 protected function logError( $msg ) {
406 $this->logger
->error( "Redis error: $msg" );
410 * The redis extension throws an exception in response to various read, write
411 * and protocol errors. Sometimes it also closes the connection, sometimes
412 * not. The safest response for us is to explicitly destroy the connection
413 * object and let it be reopened during the next request.
414 * @param RedisConnRef $conn
415 * @param Exception $e
417 protected function handleException( RedisConnRef
$conn, $e ) {
418 $this->setLastError( BagOStuff
::ERR_UNEXPECTED
);
419 $this->redisPool
->handleError( $conn, $e );
423 * Send information about a single request to the debug log
424 * @param string $method
426 * @param string $server
427 * @param bool $result
429 public function logRequest( $method, $key, $server, $result ) {
430 $this->debug( "$method $key on $server: " .
431 ( $result === false ?
"failure" : "success" ) );