Catch exceptions in SqlBagOStuff and cache connection failures.
[lhc/web/wiklou.git] / includes / objectcache / RedisBagOStuff.php
1 <?php
2
3 class RedisBagOStuff extends BagOStuff {
4 protected $connectTimeout, $persistent, $password, $automaticFailover;
5
6 /**
7 * A list of server names, from $params['servers']
8 */
9 protected $servers;
10
11 /**
12 * A cache of Redis objects, representing connections to Redis servers.
13 * The key is the server name.
14 */
15 protected $conns = array();
16
17 /**
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.
23 */
24 protected $deadServers = array();
25
26 /**
27 * Construct a RedisBagOStuff object. Parameters are:
28 *
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.
33 *
34 * - connectTimeout: The timeout for new connections, in seconds. Optional,
35 * default is 1 second.
36 *
37 * - persistent: Set this to true to allow connections to persist across
38 * multiple web requests. False by default.
39 *
40 * - password: The authentication password, will be sent to Redis in
41 * clear text. Optional, if it is unspecified, no AUTH command will be
42 * sent.
43 *
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.
51 */
52 function __construct( $params ) {
53 if ( !extension_loaded( 'redis' ) ) {
54 throw new MWException( __CLASS__. ' requires the phpredis extension: ' .
55 'https://github.com/nicolasff/phpredis' );
56 }
57
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'];
64 }
65 if ( isset( $params['automaticFailover'] ) ) {
66 $this->automaticFailover = $params['automaticFailover'];
67 } else {
68 $this->automaticFailover = true;
69 }
70 }
71
72 public function get( $key ) {
73 wfProfileIn( __METHOD__ );
74 list( $server, $conn ) = $this->getConnection( $key );
75 if ( !$conn ) {
76 wfProfileOut( __METHOD__ );
77 return false;
78 }
79 try {
80 $result = $conn->get( $key );
81 } catch ( RedisException $e ) {
82 $result = false;
83 $this->handleException( $server, $e );
84 }
85 $this->logRequest( 'get', $key, $server, $result );
86 wfProfileOut( __METHOD__ );
87 return $result;
88 }
89
90 public function set( $key, $value, $expiry = 0 ) {
91 wfProfileIn( __METHOD__ );
92 list( $server, $conn ) = $this->getConnection( $key );
93 if ( !$conn ) {
94 wfProfileOut( __METHOD__ );
95 return false;
96 }
97 $expiry = $this->convertToRelative( $expiry );
98 try {
99 if ( !$expiry ) {
100 // No expiry, that is very different from zero expiry in Redis
101 $result = $conn->set( $key, $value );
102 } else {
103 $result = $conn->setex( $key, $expiry, $value );
104 }
105 } catch ( RedisException $e ) {
106 $result = false;
107 $this->handleException( $server, $e );
108 }
109
110 $this->logRequest( 'set', $key, $server, $result );
111 wfProfileOut( __METHOD__ );
112 return $result;
113 }
114
115 public function delete( $key, $time = 0 ) {
116 wfProfileIn( __METHOD__ );
117 list( $server, $conn ) = $this->getConnection( $key );
118 if ( !$conn ) {
119 wfProfileOut( __METHOD__ );
120 return false;
121 }
122 try {
123 $conn->delete( $key );
124 // Return true even if the key didn't exist
125 $result = true;
126 } catch ( RedisException $e ) {
127 $result = false;
128 $this->handleException( $server, $e );
129 }
130 $this->logRequest( 'delete', $key, $server, $result );
131 wfProfileOut( __METHOD__ );
132 return $result;
133 }
134
135 public function getMulti( array $keys ) {
136 wfProfileIn( __METHOD__ );
137 $batches = array();
138 $conns = array();
139 foreach ( $keys as $key ) {
140 list( $server, $conn ) = $this->getConnection( $key );
141 if ( !$conn ) {
142 continue;
143 }
144 $conns[$server] = $conn;
145 $batches[$server][] = $key;
146 }
147 $result = array();
148 foreach ( $batches as $server => $batchKeys ) {
149 $conn = $conns[$server];
150 try {
151 $conn->multi( Redis::PIPELINE );
152 foreach ( $batchKeys as $key ) {
153 $conn->get( $key );
154 }
155 $batchResult = $conn->exec();
156 if ( $batchResult === false ) {
157 $this->debug( "multi request to $server failed" );
158 continue;
159 }
160 foreach ( $batchResult as $i => $value ) {
161 if ( $value !== false ) {
162 $result[$batchKeys[$i]] = $value;
163 }
164 }
165 } catch ( RedisException $e ) {
166 $this->handleException( $server, $e );
167 }
168 }
169
170 $this->debug( "getMulti for " . count( $keys ) . " keys " .
171 "returned " . count( $result ) . " results" );
172 wfProfileOut( __METHOD__ );
173 return $result;
174 }
175
176 public function add( $key, $value, $expiry = 0 ) {
177 wfProfileIn( __METHOD__ );
178 list( $server, $conn ) = $this->getConnection( $key );
179 if ( !$conn ) {
180 wfProfileOut( __METHOD__ );
181 return false;
182 }
183 $expiry = $this->convertToRelative( $expiry );
184 try {
185 $result = $conn->setnx( $key, $value );
186 if ( $result && $expiry ) {
187 $conn->expire( $key, $expiry );
188 }
189 } catch ( RedisException $e ) {
190 $result = false;
191 $this->handleException( $server, $e );
192 }
193 $this->logRequest( 'add', $key, $server, $result );
194 wfProfileOut( __METHOD__ );
195 return $result;
196 }
197
198 /**
199 * Non-atomic implementation of replace(). Could perhaps be done atomically
200 * with WATCH or scripting, but this function is rarely used.
201 */
202 public function replace( $key, $value, $expiry = 0 ) {
203 wfProfileIn( __METHOD__ );
204 list( $server, $conn ) = $this->getConnection( $key );
205 if ( !$conn ) {
206 wfProfileOut( __METHOD__ );
207 return false;
208 }
209 if ( !$conn->exists( $key ) ) {
210 wfProfileOut( __METHOD__ );
211 return false;
212 }
213
214 $expiry = $this->convertToRelative( $expiry );
215 try {
216 if ( !$expiry ) {
217 $result = $conn->set( $key, $value );
218 } else {
219 $result = $conn->setex( $key, $expiry, $value );
220 }
221 } catch ( RedisException $e ) {
222 $result = false;
223 $this->handleException( $server, $e );
224 }
225
226 $this->logRequest( 'replace', $key, $server, $result );
227 wfProfileOut( __METHOD__ );
228 return $result;
229 }
230
231 /**
232 * Non-atomic implementation of incr().
233 *
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
238 * atomic.
239 */
240 public function incr( $key, $value = 1 ) {
241 wfProfileIn( __METHOD__ );
242 list( $server, $conn ) = $this->getConnection( $key );
243 if ( !$conn ) {
244 wfProfileOut( __METHOD__ );
245 return false;
246 }
247 if ( !$conn->exists( $key ) ) {
248 wfProfileOut( __METHOD__ );
249 return null;
250 }
251 try {
252 $result = $conn->incrBy( $key, $value );
253 } catch ( RedisException $e ) {
254 $result = false;
255 $this->handleException( $server, $e );
256 }
257
258 $this->logRequest( 'incr', $key, $server, $result );
259 wfProfileOut( __METHOD__ );
260 return $result;
261 }
262
263 /**
264 * Get a Redis object with a connection suitable for fetching the specified key
265 */
266 protected function getConnection( $key ) {
267 if ( count( $this->servers ) === 1 ) {
268 $candidates = $this->servers;
269 } else {
270 // Use consistent hashing
271 $hashes = array();
272 foreach ( $this->servers as $server ) {
273 $hashes[$server] = md5( $server . '/' . $key );
274 }
275 asort( $hashes );
276 if ( !$this->automaticFailover ) {
277 reset( $hashes );
278 $candidates = array( key( $hashes ) );
279 } else {
280 $candidates = array_keys( $hashes );
281 }
282 }
283
284 foreach ( $candidates as $server ) {
285 $conn = $this->getConnectionToServer( $server );
286 if ( $conn ) {
287 return array( $server, $conn );
288 }
289 }
290 return array( false, false );
291 }
292
293 /**
294 * Get a connection to the server with the specified name. Connections
295 * are cached, and failures are persistent to avoid multiple timeouts.
296 *
297 * @return Redis object, or false on failure
298 */
299 protected function getConnectionToServer( $server ) {
300 if ( isset( $this->deadServers[$server] ) ) {
301 $now = time();
302 if ( $now > $this->deadServers[$server] ) {
303 // Dead time expired
304 unset( $this->deadServers[$server] );
305 } else {
306 // Server is dead
307 $this->debug( "server $server is marked down for another " .
308 ($this->deadServers[$server] - $now ) .
309 " seconds, can't get connection" );
310 return false;
311 }
312 }
313
314 if ( isset( $this->conns[$server] ) ) {
315 return $this->conns[$server];
316 }
317
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.
322 $host = $server;
323 $port = 0;
324 } else {
325 // TCP connection
326 $hostPort = IP::splitHostAndPort( $server );
327 if ( !$hostPort ) {
328 throw new MWException( __CLASS__.": invalid configured server \"$server\"" );
329 }
330 list( $host, $port ) = $hostPort;
331 if ( $port === false ) {
332 $port = 6379;
333 }
334 }
335 $conn = new Redis;
336 try {
337 if ( $this->persistent ) {
338 $this->debug( "opening persistent connection to $host:$port" );
339 $result = $conn->pconnect( $host, $port, $this->connectTimeout );
340 } else {
341 $this->debug( "opening non-persistent connection to $host:$port" );
342 $result = $conn->connect( $host, $port, $this->connectTimeout );
343 }
344 if ( !$result ) {
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;
348 return false;
349 }
350 if ( $this->password !== null ) {
351 if ( !$conn->auth( $this->password ) ) {
352 $this->logError( "authentication error connecting to $server" );
353 }
354 }
355 } catch ( RedisException $e ) {
356 $this->deadServers[$server] = time() + 30;
357 wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
358 return false;
359 }
360
361 $conn->setOption( Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP );
362 $this->conns[$server] = $conn;
363 return $conn;
364 }
365
366 /**
367 * Log a fatal error
368 */
369 protected function logError( $msg ) {
370 wfDebugLog( 'redis', "Redis error: $msg\n" );
371 }
372
373 /**
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.
378 */
379 protected function handleException( $server, $e ) {
380 wfDebugLog( 'redis', "Redis exception on server $server: " . $e->getMessage() . "\n" );
381 unset( $this->conns[$server] );
382 }
383
384 /**
385 * Send information about a single request to the debug log
386 */
387 public function logRequest( $method, $key, $server, $result ) {
388 $this->debug( "$method $key on $server: " .
389 ( $result === false ? "failure" : "success" ) );
390 }
391 }
392