67a3337dfc86a29cd30b8f07f487c4dd771d5657
3 class RedisBagOStuff
extends BagOStuff
{
4 protected $connectTimeout, $persistent, $password, $automaticFailover;
7 * A list of server names, from $params['servers']
12 * A cache of Redis objects, representing connections to Redis servers.
13 * The key is the server name.
15 protected $conns = array();
18 * An array listing "dead" servers which have had a connection error in
19 * the past. Servers are marked dead for a limited period of time, to
20 * avoid excessive overhead from repeated connection timeouts. The key in
21 * the array is the server name, the value is the UNIX timestamp at which
22 * the server is resurrected.
24 protected $deadServers = array();
27 * Construct a RedisBagOStuff object. Parameters are:
29 * - servers: An array of server names. A server name may be a hostname,
30 * a hostname/port combination or the absolute path of a UNIX socket.
31 * If a hostname is specified but no port, the standard port number
32 * 6379 will be used. Required.
34 * - connectTimeout: The timeout for new connections, in seconds. Optional,
35 * default is 1 second.
37 * - persistent: Set this to true to allow connections to persist across
38 * multiple web requests. False by default.
40 * - password: The authentication password, will be sent to Redis in
41 * clear text. Optional, if it is unspecified, no AUTH command will be
44 * - automaticFailover: If this is false, then each key will be mapped to
45 * a single server, and if that server is down, any requests for that key
46 * will fail. If this is true, a connection failure will cause the client
47 * to immediately try the next server in the list (as determined by a
48 * consistent hashing algorithm). True by default. This has the
49 * potential to create consistency issues if a server is slow enough to
50 * flap, for example if it is in swap death.
52 function __construct( $params ) {
53 if ( !extension_loaded( 'redis' ) ) {
54 throw new MWException( __CLASS__
. ' requires the phpredis extension: ' .
55 'https://github.com/nicolasff/phpredis' );
58 $this->servers
= $params['servers'];
59 $this->connectTimeout
= isset( $params['connectTimeout'] )
60 ?
$params['connectTimeout'] : 1;
61 $this->persistent
= !empty( $params['persistent'] );
62 if ( isset( $params['password'] ) ) {
63 $this->password
= $params['password'];
65 if ( isset( $params['automaticFailover'] ) ) {
66 $this->automaticFailover
= $params['automaticFailover'];
68 $this->automaticFailover
= true;
72 public function get( $key ) {
73 wfProfileIn( __METHOD__
);
74 list( $server, $conn ) = $this->getConnection( $key );
76 wfProfileOut( __METHOD__
);
80 $result = $conn->get( $key );
81 } catch ( RedisException
$e ) {
83 $this->handleException( $server, $e );
85 $this->logRequest( 'get', $key, $server, $result );
86 wfProfileOut( __METHOD__
);
90 public function set( $key, $value, $expiry = 0 ) {
91 wfProfileIn( __METHOD__
);
92 list( $server, $conn ) = $this->getConnection( $key );
94 wfProfileOut( __METHOD__
);
97 $expiry = $this->convertToRelative( $expiry );
100 // No expiry, that is very different from zero expiry in Redis
101 $result = $conn->set( $key, $value );
103 $result = $conn->setex( $key, $expiry, $value );
105 } catch ( RedisException
$e ) {
107 $this->handleException( $server, $e );
110 $this->logRequest( 'set', $key, $server, $result );
111 wfProfileOut( __METHOD__
);
115 public function delete( $key, $time = 0 ) {
116 wfProfileIn( __METHOD__
);
117 list( $server, $conn ) = $this->getConnection( $key );
119 wfProfileOut( __METHOD__
);
123 $conn->delete( $key );
124 // Return true even if the key didn't exist
126 } catch ( RedisException
$e ) {
128 $this->handleException( $server, $e );
130 $this->logRequest( 'delete', $key, $server, $result );
131 wfProfileOut( __METHOD__
);
135 public function getMulti( array $keys ) {
136 wfProfileIn( __METHOD__
);
139 foreach ( $keys as $key ) {
140 list( $server, $conn ) = $this->getConnection( $key );
144 $conns[$server] = $conn;
145 $batches[$server][] = $key;
148 foreach ( $batches as $server => $batchKeys ) {
149 $conn = $conns[$server];
151 $conn->multi( Redis
::PIPELINE
);
152 foreach ( $batchKeys as $key ) {
155 $batchResult = $conn->exec();
156 if ( $batchResult === false ) {
157 $this->debug( "multi request to $server failed" );
160 foreach ( $batchResult as $i => $value ) {
161 if ( $value !== false ) {
162 $result[$batchKeys[$i]] = $value;
165 } catch ( RedisException
$e ) {
166 $this->handleException( $server, $e );
170 $this->debug( "getMulti for " . count( $keys ) . " keys " .
171 "returned " . count( $result ) . " results" );
172 wfProfileOut( __METHOD__
);
176 public function add( $key, $value, $expiry = 0 ) {
177 wfProfileIn( __METHOD__
);
178 list( $server, $conn ) = $this->getConnection( $key );
180 wfProfileOut( __METHOD__
);
183 $expiry = $this->convertToRelative( $expiry );
185 $result = $conn->setnx( $key, $value );
186 if ( $result && $expiry ) {
187 $conn->expire( $key, $expiry );
189 } catch ( RedisException
$e ) {
191 $this->handleException( $server, $e );
193 $this->logRequest( 'add', $key, $server, $result );
194 wfProfileOut( __METHOD__
);
199 * Non-atomic implementation of replace(). Could perhaps be done atomically
200 * with WATCH or scripting, but this function is rarely used.
202 public function replace( $key, $value, $expiry = 0 ) {
203 wfProfileIn( __METHOD__
);
204 list( $server, $conn ) = $this->getConnection( $key );
206 wfProfileOut( __METHOD__
);
209 if ( !$conn->exists( $key ) ) {
210 wfProfileOut( __METHOD__
);
214 $expiry = $this->convertToRelative( $expiry );
217 $result = $conn->set( $key, $value );
219 $result = $conn->setex( $key, $expiry, $value );
221 } catch ( RedisException
$e ) {
223 $this->handleException( $server, $e );
226 $this->logRequest( 'replace', $key, $server, $result );
227 wfProfileOut( __METHOD__
);
232 * Non-atomic implementation of incr().
234 * Probably all callers actually want incr() to atomically initialise
235 * values to zero if they don't exist, as provided by the Redis INCR
236 * command. But we are constrained by the memcached-like interface to
237 * return null in that case. Once the key exists, further increments are
240 public function incr( $key, $value = 1 ) {
241 wfProfileIn( __METHOD__
);
242 list( $server, $conn ) = $this->getConnection( $key );
244 wfProfileOut( __METHOD__
);
247 if ( !$conn->exists( $key ) ) {
248 wfProfileOut( __METHOD__
);
252 $result = $conn->incrBy( $key, $value );
253 } catch ( RedisException
$e ) {
255 $this->handleException( $server, $e );
258 $this->logRequest( 'incr', $key, $server, $result );
259 wfProfileOut( __METHOD__
);
264 * Get a Redis object with a connection suitable for fetching the specified key
266 protected function getConnection( $key ) {
267 if ( count( $this->servers
) === 1 ) {
268 $candidates = $this->servers
;
270 // Use consistent hashing
272 foreach ( $this->servers
as $server ) {
273 $hashes[$server] = md5( $server . '/' . $key );
276 if ( !$this->automaticFailover
) {
278 $candidates = array( key( $hashes ) );
280 $candidates = array_keys( $hashes );
284 foreach ( $candidates as $server ) {
285 $conn = $this->getConnectionToServer( $server );
287 return array( $server, $conn );
290 return array( false, false );
294 * Get a connection to the server with the specified name. Connections
295 * are cached, and failures are persistent to avoid multiple timeouts.
297 * @return Redis object, or false on failure
299 protected function getConnectionToServer( $server ) {
300 if ( isset( $this->deadServers
[$server] ) ) {
302 if ( $now > $this->deadServers
[$server] ) {
304 unset( $this->deadServers
[$server] );
307 $this->debug( "server $server is marked down for another " .
308 ($this->deadServers
[$server] - $now ) .
309 " seconds, can't get connection" );
314 if ( isset( $this->conns
[$server] ) ) {
315 return $this->conns
[$server];
318 if ( substr( $server, 0, 1 ) === '/' ) {
319 // UNIX domain socket
320 // These are required by the redis extension to start with a slash, but
321 // we still need to set the port to a special value to make it work.
326 $hostPort = IP
::splitHostAndPort( $server );
328 throw new MWException( __CLASS__
.": invalid configured server \"$server\"" );
330 list( $host, $port ) = $hostPort;
331 if ( $port === false ) {
337 if ( $this->persistent
) {
338 $this->debug( "opening persistent connection to $host:$port" );
339 $result = $conn->pconnect( $host, $port, $this->connectTimeout
);
341 $this->debug( "opening non-persistent connection to $host:$port" );
342 $result = $conn->connect( $host, $port, $this->connectTimeout
);
345 $this->logError( "could not connect to server $server" );
346 // Mark server down for 30s to avoid further timeouts
347 $this->deadServers
[$server] = time() +
30;
350 if ( $this->password
!== null ) {
351 if ( !$conn->auth( $this->password
) ) {
352 $this->logError( "authentication error connecting to $server" );
355 } catch ( RedisException
$e ) {
356 $this->deadServers
[$server] = time() +
30;
357 wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
361 $conn->setOption( Redis
::OPT_SERIALIZER
, Redis
::SERIALIZER_PHP
);
362 $this->conns
[$server] = $conn;
369 protected function logError( $msg ) {
370 wfDebugLog( 'redis', "Redis error: $msg\n" );
374 * The redis extension throws an exception in response to various read, write
375 * and protocol errors. Sometimes it also closes the connection, sometimes
376 * not. The safest response for us is to explicitly destroy the connection
377 * object and let it be reopened during the next request.
379 protected function handleException( $server, $e ) {
380 wfDebugLog( 'redis', "Redis exception on server $server: " . $e->getMessage() . "\n" );
381 unset( $this->conns
[$server] );
385 * Send information about a single request to the debug log
387 public function logRequest( $method, $key, $server, $result ) {
388 $this->debug( "$method $key on $server: " .
389 ( $result === false ?
"failure" : "success" ) );