bd5b354c5da0ed14b2399cacf20cc05c758bbfd9
[lhc/web/wiklou.git] / includes / objectcache / RedisBagOStuff.php
1 <?php
2 /**
3 * Object caching using Redis (http://redis.io/).
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23
24 class RedisBagOStuff extends BagOStuff {
25 protected $connectTimeout, $persistent, $password, $automaticFailover;
26
27 /**
28 * A list of server names, from $params['servers']
29 */
30 protected $servers;
31
32 /**
33 * A cache of Redis objects, representing connections to Redis servers.
34 * The key is the server name.
35 */
36 protected $conns = array();
37
38 /**
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.
44 */
45 protected $deadServers = array();
46
47 /**
48 * Construct a RedisBagOStuff object. Parameters are:
49 *
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.
54 *
55 * - connectTimeout: The timeout for new connections, in seconds. Optional,
56 * default is 1 second.
57 *
58 * - persistent: Set this to true to allow connections to persist across
59 * multiple web requests. False by default.
60 *
61 * - password: The authentication password, will be sent to Redis in
62 * clear text. Optional, if it is unspecified, no AUTH command will be
63 * sent.
64 *
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.
72 */
73 function __construct( $params ) {
74 if ( !extension_loaded( 'redis' ) ) {
75 throw new MWException( __CLASS__. ' requires the phpredis extension: ' .
76 'https://github.com/nicolasff/phpredis' );
77 }
78
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'];
85 }
86 if ( isset( $params['automaticFailover'] ) ) {
87 $this->automaticFailover = $params['automaticFailover'];
88 } else {
89 $this->automaticFailover = true;
90 }
91 }
92
93 public function get( $key, &$casToken = null ) {
94 wfProfileIn( __METHOD__ );
95 list( $server, $conn ) = $this->getConnection( $key );
96 if ( !$conn ) {
97 wfProfileOut( __METHOD__ );
98 return false;
99 }
100 try {
101 $result = $conn->get( $key );
102 } catch ( RedisException $e ) {
103 $result = false;
104 $this->handleException( $server, $e );
105 }
106 $casToken = $result;
107 $this->logRequest( 'get', $key, $server, $result );
108 wfProfileOut( __METHOD__ );
109 return $result;
110 }
111
112 public function set( $key, $value, $expiry = 0 ) {
113 wfProfileIn( __METHOD__ );
114 list( $server, $conn ) = $this->getConnection( $key );
115 if ( !$conn ) {
116 wfProfileOut( __METHOD__ );
117 return false;
118 }
119 $expiry = $this->convertToRelative( $expiry );
120 try {
121 if ( !$expiry ) {
122 // No expiry, that is very different from zero expiry in Redis
123 $result = $conn->set( $key, $value );
124 } else {
125 $result = $conn->setex( $key, $expiry, $value );
126 }
127 } catch ( RedisException $e ) {
128 $result = false;
129 $this->handleException( $server, $e );
130 }
131
132 $this->logRequest( 'set', $key, $server, $result );
133 wfProfileOut( __METHOD__ );
134 return $result;
135 }
136
137 /**
138 * @param $casToken mixed
139 * @param $key string
140 * @param $value mixed
141 * @param $exptime int
142 * @return bool
143 */
144 public function cas( $casToken, $key, $value, $expiry = 0 ) {
145 wfProfileIn( __METHOD__ );
146 list( $server, $conn ) = $this->getConnection( $key );
147 if ( !$conn ) {
148 wfProfileOut( __METHOD__ );
149 return false;
150 }
151 $expiry = $this->convertToRelative( $expiry );
152 try {
153 $conn->watch( $key );
154
155 if ( $this->get( $key ) !== $casToken ) {
156 wfProfileOut( __METHOD__ );
157 return false;
158 }
159
160 $conn->multi();
161
162 if ( !$expiry ) {
163 // No expiry, that is very different from zero expiry in Redis
164 $conn->set( $key, $value );
165 } else {
166 $conn->setex( $key, $expiry, $value );
167 }
168
169 $result = $conn->exec();
170 } catch ( RedisException $e ) {
171 $result = false;
172 $this->handleException( $server, $e );
173 }
174
175 $this->logRequest( 'cas', $key, $server, $result );
176 wfProfileOut( __METHOD__ );
177 return $result;
178 }
179
180 public function delete( $key, $time = 0 ) {
181 wfProfileIn( __METHOD__ );
182 list( $server, $conn ) = $this->getConnection( $key );
183 if ( !$conn ) {
184 wfProfileOut( __METHOD__ );
185 return false;
186 }
187 try {
188 $conn->delete( $key );
189 // Return true even if the key didn't exist
190 $result = true;
191 } catch ( RedisException $e ) {
192 $result = false;
193 $this->handleException( $server, $e );
194 }
195 $this->logRequest( 'delete', $key, $server, $result );
196 wfProfileOut( __METHOD__ );
197 return $result;
198 }
199
200 public function getMulti( array $keys ) {
201 wfProfileIn( __METHOD__ );
202 $batches = array();
203 $conns = array();
204 foreach ( $keys as $key ) {
205 list( $server, $conn ) = $this->getConnection( $key );
206 if ( !$conn ) {
207 continue;
208 }
209 $conns[$server] = $conn;
210 $batches[$server][] = $key;
211 }
212 $result = array();
213 foreach ( $batches as $server => $batchKeys ) {
214 $conn = $conns[$server];
215 try {
216 $conn->multi( Redis::PIPELINE );
217 foreach ( $batchKeys as $key ) {
218 $conn->get( $key );
219 }
220 $batchResult = $conn->exec();
221 if ( $batchResult === false ) {
222 $this->debug( "multi request to $server failed" );
223 continue;
224 }
225 foreach ( $batchResult as $i => $value ) {
226 if ( $value !== false ) {
227 $result[$batchKeys[$i]] = $value;
228 }
229 }
230 } catch ( RedisException $e ) {
231 $this->handleException( $server, $e );
232 }
233 }
234
235 $this->debug( "getMulti for " . count( $keys ) . " keys " .
236 "returned " . count( $result ) . " results" );
237 wfProfileOut( __METHOD__ );
238 return $result;
239 }
240
241 public function add( $key, $value, $expiry = 0 ) {
242 wfProfileIn( __METHOD__ );
243 list( $server, $conn ) = $this->getConnection( $key );
244 if ( !$conn ) {
245 wfProfileOut( __METHOD__ );
246 return false;
247 }
248 $expiry = $this->convertToRelative( $expiry );
249 try {
250 $result = $conn->setnx( $key, $value );
251 if ( $result && $expiry ) {
252 $conn->expire( $key, $expiry );
253 }
254 } catch ( RedisException $e ) {
255 $result = false;
256 $this->handleException( $server, $e );
257 }
258 $this->logRequest( 'add', $key, $server, $result );
259 wfProfileOut( __METHOD__ );
260 return $result;
261 }
262
263 /**
264 * Non-atomic implementation of replace(). Could perhaps be done atomically
265 * with WATCH or scripting, but this function is rarely used.
266 */
267 public function replace( $key, $value, $expiry = 0 ) {
268 wfProfileIn( __METHOD__ );
269 list( $server, $conn ) = $this->getConnection( $key );
270 if ( !$conn ) {
271 wfProfileOut( __METHOD__ );
272 return false;
273 }
274 if ( !$conn->exists( $key ) ) {
275 wfProfileOut( __METHOD__ );
276 return false;
277 }
278
279 $expiry = $this->convertToRelative( $expiry );
280 try {
281 if ( !$expiry ) {
282 $result = $conn->set( $key, $value );
283 } else {
284 $result = $conn->setex( $key, $expiry, $value );
285 }
286 } catch ( RedisException $e ) {
287 $result = false;
288 $this->handleException( $server, $e );
289 }
290
291 $this->logRequest( 'replace', $key, $server, $result );
292 wfProfileOut( __METHOD__ );
293 return $result;
294 }
295
296 /**
297 * Non-atomic implementation of incr().
298 *
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
303 * atomic.
304 */
305 public function incr( $key, $value = 1 ) {
306 wfProfileIn( __METHOD__ );
307 list( $server, $conn ) = $this->getConnection( $key );
308 if ( !$conn ) {
309 wfProfileOut( __METHOD__ );
310 return false;
311 }
312 if ( !$conn->exists( $key ) ) {
313 wfProfileOut( __METHOD__ );
314 return null;
315 }
316 try {
317 $result = $conn->incrBy( $key, $value );
318 } catch ( RedisException $e ) {
319 $result = false;
320 $this->handleException( $server, $e );
321 }
322
323 $this->logRequest( 'incr', $key, $server, $result );
324 wfProfileOut( __METHOD__ );
325 return $result;
326 }
327
328 /**
329 * Get a Redis object with a connection suitable for fetching the specified key
330 */
331 protected function getConnection( $key ) {
332 if ( count( $this->servers ) === 1 ) {
333 $candidates = $this->servers;
334 } else {
335 $candidates = $this->servers;
336 ArrayUtils::consistentHashSort( $candidates, $key, '/' );
337 if ( !$this->automaticFailover ) {
338 $candidates = array_slice( $candidates, 0, 1 );
339 }
340 }
341
342 foreach ( $candidates as $server ) {
343 $conn = $this->getConnectionToServer( $server );
344 if ( $conn ) {
345 return array( $server, $conn );
346 }
347 }
348 return array( false, false );
349 }
350
351 /**
352 * Get a connection to the server with the specified name. Connections
353 * are cached, and failures are persistent to avoid multiple timeouts.
354 *
355 * @param $server
356 * @throws MWException
357 * @return Redis object, or false on failure
358 */
359 protected function getConnectionToServer( $server ) {
360 if ( isset( $this->deadServers[$server] ) ) {
361 $now = time();
362 if ( $now > $this->deadServers[$server] ) {
363 // Dead time expired
364 unset( $this->deadServers[$server] );
365 } else {
366 // Server is dead
367 $this->debug( "server $server is marked down for another " .
368 ($this->deadServers[$server] - $now ) .
369 " seconds, can't get connection" );
370 return false;
371 }
372 }
373
374 if ( isset( $this->conns[$server] ) ) {
375 return $this->conns[$server];
376 }
377
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.
382 $host = $server;
383 $port = 0;
384 } else {
385 // TCP connection
386 $hostPort = IP::splitHostAndPort( $server );
387 if ( !$hostPort ) {
388 throw new MWException( __CLASS__.": invalid configured server \"$server\"" );
389 }
390 list( $host, $port ) = $hostPort;
391 if ( $port === false ) {
392 $port = 6379;
393 }
394 }
395 $conn = new Redis;
396 try {
397 if ( $this->persistent ) {
398 $this->debug( "opening persistent connection to $host:$port" );
399 $result = $conn->pconnect( $host, $port, $this->connectTimeout );
400 } else {
401 $this->debug( "opening non-persistent connection to $host:$port" );
402 $result = $conn->connect( $host, $port, $this->connectTimeout );
403 }
404 if ( !$result ) {
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;
408 return false;
409 }
410 if ( $this->password !== null ) {
411 if ( !$conn->auth( $this->password ) ) {
412 $this->logError( "authentication error connecting to $server" );
413 }
414 }
415 } catch ( RedisException $e ) {
416 $this->deadServers[$server] = time() + 30;
417 wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
418 return false;
419 }
420
421 $conn->setOption( Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP );
422 $this->conns[$server] = $conn;
423 return $conn;
424 }
425
426 /**
427 * Log a fatal error
428 */
429 protected function logError( $msg ) {
430 wfDebugLog( 'redis', "Redis error: $msg\n" );
431 }
432
433 /**
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.
438 */
439 protected function handleException( $server, $e ) {
440 wfDebugLog( 'redis', "Redis exception on server $server: " . $e->getMessage() . "\n" );
441 unset( $this->conns[$server] );
442 }
443
444 /**
445 * Send information about a single request to the debug log
446 */
447 public function logRequest( $method, $key, $server, $result ) {
448 $this->debug( "$method $key on $server: " .
449 ( $result === false ? "failure" : "success" ) );
450 }
451 }
452