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 class RedisBagOStuff
extends BagOStuff
{
25 protected $connectTimeout, $persistent, $password, $automaticFailover;
28 * A list of server names, from $params['servers']
33 * A cache of Redis objects, representing connections to Redis servers.
34 * The key is the server name.
36 protected $conns = array();
39 * An array listing "dead" servers which have had a connection error in
40 * the past. Servers are marked dead for a limited period of time, to
41 * avoid excessive overhead from repeated connection timeouts. The key in
42 * the array is the server name, the value is the UNIX timestamp at which
43 * the server is resurrected.
45 protected $deadServers = array();
48 * Construct a RedisBagOStuff object. Parameters are:
50 * - servers: An array of server names. A server name may be a hostname,
51 * a hostname/port combination or the absolute path of a UNIX socket.
52 * If a hostname is specified but no port, the standard port number
53 * 6379 will be used. Required.
55 * - connectTimeout: The timeout for new connections, in seconds. Optional,
56 * default is 1 second.
58 * - persistent: Set this to true to allow connections to persist across
59 * multiple web requests. False by default.
61 * - password: The authentication password, will be sent to Redis in
62 * clear text. Optional, if it is unspecified, no AUTH command will be
65 * - automaticFailover: If this is false, then each key will be mapped to
66 * a single server, and if that server is down, any requests for that key
67 * will fail. If this is true, a connection failure will cause the client
68 * to immediately try the next server in the list (as determined by a
69 * consistent hashing algorithm). True by default. This has the
70 * potential to create consistency issues if a server is slow enough to
71 * flap, for example if it is in swap death.
73 function __construct( $params ) {
74 if ( !extension_loaded( 'redis' ) ) {
75 throw new MWException( __CLASS__
. ' requires the phpredis extension: ' .
76 'https://github.com/nicolasff/phpredis' );
79 $this->servers
= $params['servers'];
80 $this->connectTimeout
= isset( $params['connectTimeout'] )
81 ?
$params['connectTimeout'] : 1;
82 $this->persistent
= !empty( $params['persistent'] );
83 if ( isset( $params['password'] ) ) {
84 $this->password
= $params['password'];
86 if ( isset( $params['automaticFailover'] ) ) {
87 $this->automaticFailover
= $params['automaticFailover'];
89 $this->automaticFailover
= true;
93 public function get( $key, &$casToken = null ) {
94 wfProfileIn( __METHOD__
);
95 list( $server, $conn ) = $this->getConnection( $key );
97 wfProfileOut( __METHOD__
);
101 $result = $conn->get( $key );
102 } catch ( RedisException
$e ) {
104 $this->handleException( $server, $e );
107 $this->logRequest( 'get', $key, $server, $result );
108 wfProfileOut( __METHOD__
);
112 public function set( $key, $value, $expiry = 0 ) {
113 wfProfileIn( __METHOD__
);
114 list( $server, $conn ) = $this->getConnection( $key );
116 wfProfileOut( __METHOD__
);
119 $expiry = $this->convertToRelative( $expiry );
122 // No expiry, that is very different from zero expiry in Redis
123 $result = $conn->set( $key, $value );
125 $result = $conn->setex( $key, $expiry, $value );
127 } catch ( RedisException
$e ) {
129 $this->handleException( $server, $e );
132 $this->logRequest( 'set', $key, $server, $result );
133 wfProfileOut( __METHOD__
);
138 * @param $casToken mixed
140 * @param $value mixed
141 * @param $exptime int
144 public function cas( $casToken, $key, $value, $expiry = 0 ) {
145 wfProfileIn( __METHOD__
);
146 list( $server, $conn ) = $this->getConnection( $key );
148 wfProfileOut( __METHOD__
);
151 $expiry = $this->convertToRelative( $expiry );
153 $conn->watch( $key );
155 if ( $this->get( $key ) !== $casToken ) {
156 wfProfileOut( __METHOD__
);
163 // No expiry, that is very different from zero expiry in Redis
164 $conn->set( $key, $value );
166 $conn->setex( $key, $expiry, $value );
169 $result = $conn->exec();
170 } catch ( RedisException
$e ) {
172 $this->handleException( $server, $e );
175 $this->logRequest( 'cas', $key, $server, $result );
176 wfProfileOut( __METHOD__
);
180 public function delete( $key, $time = 0 ) {
181 wfProfileIn( __METHOD__
);
182 list( $server, $conn ) = $this->getConnection( $key );
184 wfProfileOut( __METHOD__
);
188 $conn->delete( $key );
189 // Return true even if the key didn't exist
191 } catch ( RedisException
$e ) {
193 $this->handleException( $server, $e );
195 $this->logRequest( 'delete', $key, $server, $result );
196 wfProfileOut( __METHOD__
);
200 public function getMulti( array $keys ) {
201 wfProfileIn( __METHOD__
);
204 foreach ( $keys as $key ) {
205 list( $server, $conn ) = $this->getConnection( $key );
209 $conns[$server] = $conn;
210 $batches[$server][] = $key;
213 foreach ( $batches as $server => $batchKeys ) {
214 $conn = $conns[$server];
216 $conn->multi( Redis
::PIPELINE
);
217 foreach ( $batchKeys as $key ) {
220 $batchResult = $conn->exec();
221 if ( $batchResult === false ) {
222 $this->debug( "multi request to $server failed" );
225 foreach ( $batchResult as $i => $value ) {
226 if ( $value !== false ) {
227 $result[$batchKeys[$i]] = $value;
230 } catch ( RedisException
$e ) {
231 $this->handleException( $server, $e );
235 $this->debug( "getMulti for " . count( $keys ) . " keys " .
236 "returned " . count( $result ) . " results" );
237 wfProfileOut( __METHOD__
);
241 public function add( $key, $value, $expiry = 0 ) {
242 wfProfileIn( __METHOD__
);
243 list( $server, $conn ) = $this->getConnection( $key );
245 wfProfileOut( __METHOD__
);
248 $expiry = $this->convertToRelative( $expiry );
250 $result = $conn->setnx( $key, $value );
251 if ( $result && $expiry ) {
252 $conn->expire( $key, $expiry );
254 } catch ( RedisException
$e ) {
256 $this->handleException( $server, $e );
258 $this->logRequest( 'add', $key, $server, $result );
259 wfProfileOut( __METHOD__
);
264 * Non-atomic implementation of replace(). Could perhaps be done atomically
265 * with WATCH or scripting, but this function is rarely used.
267 public function replace( $key, $value, $expiry = 0 ) {
268 wfProfileIn( __METHOD__
);
269 list( $server, $conn ) = $this->getConnection( $key );
271 wfProfileOut( __METHOD__
);
274 if ( !$conn->exists( $key ) ) {
275 wfProfileOut( __METHOD__
);
279 $expiry = $this->convertToRelative( $expiry );
282 $result = $conn->set( $key, $value );
284 $result = $conn->setex( $key, $expiry, $value );
286 } catch ( RedisException
$e ) {
288 $this->handleException( $server, $e );
291 $this->logRequest( 'replace', $key, $server, $result );
292 wfProfileOut( __METHOD__
);
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
305 public function incr( $key, $value = 1 ) {
306 wfProfileIn( __METHOD__
);
307 list( $server, $conn ) = $this->getConnection( $key );
309 wfProfileOut( __METHOD__
);
312 if ( !$conn->exists( $key ) ) {
313 wfProfileOut( __METHOD__
);
317 $result = $conn->incrBy( $key, $value );
318 } catch ( RedisException
$e ) {
320 $this->handleException( $server, $e );
323 $this->logRequest( 'incr', $key, $server, $result );
324 wfProfileOut( __METHOD__
);
329 * Get a Redis object with a connection suitable for fetching the specified key
331 protected function getConnection( $key ) {
332 if ( count( $this->servers
) === 1 ) {
333 $candidates = $this->servers
;
335 $candidates = $this->servers
;
336 ArrayUtils
::consistentHashSort( $candidates, $key, '/' );
337 if ( !$this->automaticFailover
) {
338 $candidates = array_slice( $candidates, 0, 1 );
342 foreach ( $candidates as $server ) {
343 $conn = $this->getConnectionToServer( $server );
345 return array( $server, $conn );
348 return array( false, false );
352 * Get a connection to the server with the specified name. Connections
353 * are cached, and failures are persistent to avoid multiple timeouts.
356 * @throws MWException
357 * @return Redis object, or false on failure
359 protected function getConnectionToServer( $server ) {
360 if ( isset( $this->deadServers
[$server] ) ) {
362 if ( $now > $this->deadServers
[$server] ) {
364 unset( $this->deadServers
[$server] );
367 $this->debug( "server $server is marked down for another " .
368 ($this->deadServers
[$server] - $now ) .
369 " seconds, can't get connection" );
374 if ( isset( $this->conns
[$server] ) ) {
375 return $this->conns
[$server];
378 if ( substr( $server, 0, 1 ) === '/' ) {
379 // UNIX domain socket
380 // These are required by the redis extension to start with a slash, but
381 // we still need to set the port to a special value to make it work.
386 $hostPort = IP
::splitHostAndPort( $server );
388 throw new MWException( __CLASS__
.": invalid configured server \"$server\"" );
390 list( $host, $port ) = $hostPort;
391 if ( $port === false ) {
397 if ( $this->persistent
) {
398 $this->debug( "opening persistent connection to $host:$port" );
399 $result = $conn->pconnect( $host, $port, $this->connectTimeout
);
401 $this->debug( "opening non-persistent connection to $host:$port" );
402 $result = $conn->connect( $host, $port, $this->connectTimeout
);
405 $this->logError( "could not connect to server $server" );
406 // Mark server down for 30s to avoid further timeouts
407 $this->deadServers
[$server] = time() +
30;
410 if ( $this->password
!== null ) {
411 if ( !$conn->auth( $this->password
) ) {
412 $this->logError( "authentication error connecting to $server" );
415 } catch ( RedisException
$e ) {
416 $this->deadServers
[$server] = time() +
30;
417 wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
421 $conn->setOption( Redis
::OPT_SERIALIZER
, Redis
::SERIALIZER_PHP
);
422 $this->conns
[$server] = $conn;
429 protected function logError( $msg ) {
430 wfDebugLog( 'redis', "Redis error: $msg\n" );
434 * The redis extension throws an exception in response to various read, write
435 * and protocol errors. Sometimes it also closes the connection, sometimes
436 * not. The safest response for us is to explicitly destroy the connection
437 * object and let it be reopened during the next request.
439 protected function handleException( $server, $e ) {
440 wfDebugLog( 'redis', "Redis exception on server $server: " . $e->getMessage() . "\n" );
441 unset( $this->conns
[$server] );
445 * Send information about a single request to the debug log
447 public function logRequest( $method, $key, $server, $result ) {
448 $this->debug( "$method $key on $server: " .
449 ( $result === false ?
"failure" : "success" ) );