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 ) {
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 );
106 $this->logRequest( 'get', $key, $server, $result );
107 wfProfileOut( __METHOD__
);
111 public function set( $key, $value, $expiry = 0 ) {
112 wfProfileIn( __METHOD__
);
113 list( $server, $conn ) = $this->getConnection( $key );
115 wfProfileOut( __METHOD__
);
118 $expiry = $this->convertToRelative( $expiry );
121 // No expiry, that is very different from zero expiry in Redis
122 $result = $conn->set( $key, $value );
124 $result = $conn->setex( $key, $expiry, $value );
126 } catch ( RedisException
$e ) {
128 $this->handleException( $server, $e );
131 $this->logRequest( 'set', $key, $server, $result );
132 wfProfileOut( __METHOD__
);
136 public function delete( $key, $time = 0 ) {
137 wfProfileIn( __METHOD__
);
138 list( $server, $conn ) = $this->getConnection( $key );
140 wfProfileOut( __METHOD__
);
144 $conn->delete( $key );
145 // Return true even if the key didn't exist
147 } catch ( RedisException
$e ) {
149 $this->handleException( $server, $e );
151 $this->logRequest( 'delete', $key, $server, $result );
152 wfProfileOut( __METHOD__
);
156 public function getMulti( array $keys ) {
157 wfProfileIn( __METHOD__
);
160 foreach ( $keys as $key ) {
161 list( $server, $conn ) = $this->getConnection( $key );
165 $conns[$server] = $conn;
166 $batches[$server][] = $key;
169 foreach ( $batches as $server => $batchKeys ) {
170 $conn = $conns[$server];
172 $conn->multi( Redis
::PIPELINE
);
173 foreach ( $batchKeys as $key ) {
176 $batchResult = $conn->exec();
177 if ( $batchResult === false ) {
178 $this->debug( "multi request to $server failed" );
181 foreach ( $batchResult as $i => $value ) {
182 if ( $value !== false ) {
183 $result[$batchKeys[$i]] = $value;
186 } catch ( RedisException
$e ) {
187 $this->handleException( $server, $e );
191 $this->debug( "getMulti for " . count( $keys ) . " keys " .
192 "returned " . count( $result ) . " results" );
193 wfProfileOut( __METHOD__
);
197 public function add( $key, $value, $expiry = 0 ) {
198 wfProfileIn( __METHOD__
);
199 list( $server, $conn ) = $this->getConnection( $key );
201 wfProfileOut( __METHOD__
);
204 $expiry = $this->convertToRelative( $expiry );
206 $result = $conn->setnx( $key, $value );
207 if ( $result && $expiry ) {
208 $conn->expire( $key, $expiry );
210 } catch ( RedisException
$e ) {
212 $this->handleException( $server, $e );
214 $this->logRequest( 'add', $key, $server, $result );
215 wfProfileOut( __METHOD__
);
220 * Non-atomic implementation of replace(). Could perhaps be done atomically
221 * with WATCH or scripting, but this function is rarely used.
223 public function replace( $key, $value, $expiry = 0 ) {
224 wfProfileIn( __METHOD__
);
225 list( $server, $conn ) = $this->getConnection( $key );
227 wfProfileOut( __METHOD__
);
230 if ( !$conn->exists( $key ) ) {
231 wfProfileOut( __METHOD__
);
235 $expiry = $this->convertToRelative( $expiry );
238 $result = $conn->set( $key, $value );
240 $result = $conn->setex( $key, $expiry, $value );
242 } catch ( RedisException
$e ) {
244 $this->handleException( $server, $e );
247 $this->logRequest( 'replace', $key, $server, $result );
248 wfProfileOut( __METHOD__
);
253 * Non-atomic implementation of incr().
255 * Probably all callers actually want incr() to atomically initialise
256 * values to zero if they don't exist, as provided by the Redis INCR
257 * command. But we are constrained by the memcached-like interface to
258 * return null in that case. Once the key exists, further increments are
261 public function incr( $key, $value = 1 ) {
262 wfProfileIn( __METHOD__
);
263 list( $server, $conn ) = $this->getConnection( $key );
265 wfProfileOut( __METHOD__
);
268 if ( !$conn->exists( $key ) ) {
269 wfProfileOut( __METHOD__
);
273 $result = $conn->incrBy( $key, $value );
274 } catch ( RedisException
$e ) {
276 $this->handleException( $server, $e );
279 $this->logRequest( 'incr', $key, $server, $result );
280 wfProfileOut( __METHOD__
);
285 * Get a Redis object with a connection suitable for fetching the specified key
287 protected function getConnection( $key ) {
288 if ( count( $this->servers
) === 1 ) {
289 $candidates = $this->servers
;
291 // Use consistent hashing
293 // Note: Benchmarking on PHP 5.3 and 5.4 indicates that for small
294 // strings, md5() is only 10% slower than hash('joaat',...) etc.,
295 // since the function call overhead dominates. So there's not much
296 // justification for breaking compatibility with installations
297 // compiled with ./configure --disable-hash.
299 foreach ( $this->servers
as $server ) {
300 $hashes[$server] = md5( $server . '/' . $key );
303 if ( !$this->automaticFailover
) {
305 $candidates = array( key( $hashes ) );
307 $candidates = array_keys( $hashes );
311 foreach ( $candidates as $server ) {
312 $conn = $this->getConnectionToServer( $server );
314 return array( $server, $conn );
317 return array( false, false );
321 * Get a connection to the server with the specified name. Connections
322 * are cached, and failures are persistent to avoid multiple timeouts.
324 * @return Redis object, or false on failure
326 protected function getConnectionToServer( $server ) {
327 if ( isset( $this->deadServers
[$server] ) ) {
329 if ( $now > $this->deadServers
[$server] ) {
331 unset( $this->deadServers
[$server] );
334 $this->debug( "server $server is marked down for another " .
335 ($this->deadServers
[$server] - $now ) .
336 " seconds, can't get connection" );
341 if ( isset( $this->conns
[$server] ) ) {
342 return $this->conns
[$server];
345 if ( substr( $server, 0, 1 ) === '/' ) {
346 // UNIX domain socket
347 // These are required by the redis extension to start with a slash, but
348 // we still need to set the port to a special value to make it work.
353 $hostPort = IP
::splitHostAndPort( $server );
355 throw new MWException( __CLASS__
.": invalid configured server \"$server\"" );
357 list( $host, $port ) = $hostPort;
358 if ( $port === false ) {
364 if ( $this->persistent
) {
365 $this->debug( "opening persistent connection to $host:$port" );
366 $result = $conn->pconnect( $host, $port, $this->connectTimeout
);
368 $this->debug( "opening non-persistent connection to $host:$port" );
369 $result = $conn->connect( $host, $port, $this->connectTimeout
);
372 $this->logError( "could not connect to server $server" );
373 // Mark server down for 30s to avoid further timeouts
374 $this->deadServers
[$server] = time() +
30;
377 if ( $this->password
!== null ) {
378 if ( !$conn->auth( $this->password
) ) {
379 $this->logError( "authentication error connecting to $server" );
382 } catch ( RedisException
$e ) {
383 $this->deadServers
[$server] = time() +
30;
384 wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
388 $conn->setOption( Redis
::OPT_SERIALIZER
, Redis
::SERIALIZER_PHP
);
389 $this->conns
[$server] = $conn;
396 protected function logError( $msg ) {
397 wfDebugLog( 'redis', "Redis error: $msg\n" );
401 * The redis extension throws an exception in response to various read, write
402 * and protocol errors. Sometimes it also closes the connection, sometimes
403 * not. The safest response for us is to explicitly destroy the connection
404 * object and let it be reopened during the next request.
406 protected function handleException( $server, $e ) {
407 wfDebugLog( 'redis', "Redis exception on server $server: " . $e->getMessage() . "\n" );
408 unset( $this->conns
[$server] );
412 * Send information about a single request to the debug log
414 public function logRequest( $method, $key, $server, $result ) {
415 $this->debug( "$method $key on $server: " .
416 ( $result === false ?
"failure" : "success" ) );