Move up devunt's name to Developers
[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 class RedisBagOStuff extends BagOStuff {
24 /** @var RedisConnectionPool */
25 protected $redisPool;
26 /** @var array List of server names */
27 protected $servers;
28 /** @var array Map of (tag => server name) */
29 protected $serverTagMap;
30 /** @var bool */
31 protected $automaticFailover;
32
33 /**
34 * Construct a RedisBagOStuff object. Parameters are:
35 *
36 * - servers: An array of server names. A server name may be a hostname,
37 * a hostname/port combination or the absolute path of a UNIX socket.
38 * If a hostname is specified but no port, the standard port number
39 * 6379 will be used. Arrays keys can be used to specify the tag to
40 * hash on in place of the host/port. Required.
41 *
42 * - connectTimeout: The timeout for new connections, in seconds. Optional,
43 * default is 1 second.
44 *
45 * - persistent: Set this to true to allow connections to persist across
46 * multiple web requests. False by default.
47 *
48 * - password: The authentication password, will be sent to Redis in
49 * clear text. Optional, if it is unspecified, no AUTH command will be
50 * sent.
51 *
52 * - automaticFailover: If this is false, then each key will be mapped to
53 * a single server, and if that server is down, any requests for that key
54 * will fail. If this is true, a connection failure will cause the client
55 * to immediately try the next server in the list (as determined by a
56 * consistent hashing algorithm). True by default. This has the
57 * potential to create consistency issues if a server is slow enough to
58 * flap, for example if it is in swap death.
59 * @param array $params
60 */
61 function __construct( $params ) {
62 parent::__construct( $params );
63 $redisConf = array( 'serializer' => 'none' ); // manage that in this class
64 foreach ( array( 'connectTimeout', 'persistent', 'password' ) as $opt ) {
65 if ( isset( $params[$opt] ) ) {
66 $redisConf[$opt] = $params[$opt];
67 }
68 }
69 $this->redisPool = RedisConnectionPool::singleton( $redisConf );
70
71 $this->servers = $params['servers'];
72 foreach ( $this->servers as $key => $server ) {
73 $this->serverTagMap[is_int( $key ) ? $server : $key] = $server;
74 }
75
76 if ( isset( $params['automaticFailover'] ) ) {
77 $this->automaticFailover = $params['automaticFailover'];
78 } else {
79 $this->automaticFailover = true;
80 }
81 }
82
83 public function get( $key, &$casToken = null ) {
84
85 list( $server, $conn ) = $this->getConnection( $key );
86 if ( !$conn ) {
87 return false;
88 }
89 try {
90 $value = $conn->get( $key );
91 $casToken = $value;
92 $result = $this->unserialize( $value );
93 } catch ( RedisException $e ) {
94 $result = false;
95 $this->handleException( $conn, $e );
96 }
97
98 $this->logRequest( 'get', $key, $server, $result );
99 return $result;
100 }
101
102 public function set( $key, $value, $expiry = 0 ) {
103
104 list( $server, $conn ) = $this->getConnection( $key );
105 if ( !$conn ) {
106 return false;
107 }
108 $expiry = $this->convertToRelative( $expiry );
109 try {
110 if ( $expiry ) {
111 $result = $conn->setex( $key, $expiry, $this->serialize( $value ) );
112 } else {
113 // No expiry, that is very different from zero expiry in Redis
114 $result = $conn->set( $key, $this->serialize( $value ) );
115 }
116 } catch ( RedisException $e ) {
117 $result = false;
118 $this->handleException( $conn, $e );
119 }
120
121 $this->logRequest( 'set', $key, $server, $result );
122 return $result;
123 }
124
125 protected function cas( $casToken, $key, $value, $expiry = 0 ) {
126
127 list( $server, $conn ) = $this->getConnection( $key );
128 if ( !$conn ) {
129 return false;
130 }
131 $expiry = $this->convertToRelative( $expiry );
132 try {
133 $conn->watch( $key );
134
135 if ( $this->serialize( $this->get( $key ) ) !== $casToken ) {
136 $conn->unwatch();
137 return false;
138 }
139
140 // multi()/exec() will fail atomically if the key changed since watch()
141 $conn->multi();
142 if ( $expiry ) {
143 $conn->setex( $key, $expiry, $this->serialize( $value ) );
144 } else {
145 // No expiry, that is very different from zero expiry in Redis
146 $conn->set( $key, $this->serialize( $value ) );
147 }
148 $result = ( $conn->exec() == array( true ) );
149 } catch ( RedisException $e ) {
150 $result = false;
151 $this->handleException( $conn, $e );
152 }
153
154 $this->logRequest( 'cas', $key, $server, $result );
155 return $result;
156 }
157
158 public function delete( $key ) {
159
160 list( $server, $conn ) = $this->getConnection( $key );
161 if ( !$conn ) {
162 return false;
163 }
164 try {
165 $conn->delete( $key );
166 // Return true even if the key didn't exist
167 $result = true;
168 } catch ( RedisException $e ) {
169 $result = false;
170 $this->handleException( $conn, $e );
171 }
172
173 $this->logRequest( 'delete', $key, $server, $result );
174 return $result;
175 }
176
177 public function getMulti( array $keys ) {
178
179 $batches = array();
180 $conns = array();
181 foreach ( $keys as $key ) {
182 list( $server, $conn ) = $this->getConnection( $key );
183 if ( !$conn ) {
184 continue;
185 }
186 $conns[$server] = $conn;
187 $batches[$server][] = $key;
188 }
189 $result = array();
190 foreach ( $batches as $server => $batchKeys ) {
191 $conn = $conns[$server];
192 try {
193 $conn->multi( Redis::PIPELINE );
194 foreach ( $batchKeys as $key ) {
195 $conn->get( $key );
196 }
197 $batchResult = $conn->exec();
198 if ( $batchResult === false ) {
199 $this->debug( "multi request to $server failed" );
200 continue;
201 }
202 foreach ( $batchResult as $i => $value ) {
203 if ( $value !== false ) {
204 $result[$batchKeys[$i]] = $this->unserialize( $value );
205 }
206 }
207 } catch ( RedisException $e ) {
208 $this->handleException( $conn, $e );
209 }
210 }
211
212 $this->debug( "getMulti for " . count( $keys ) . " keys " .
213 "returned " . count( $result ) . " results" );
214 return $result;
215 }
216
217 /**
218 * @param array $data
219 * @param int $expiry
220 * @return bool
221 */
222 public function setMulti( array $data, $expiry = 0 ) {
223
224 $batches = array();
225 $conns = array();
226 foreach ( $data as $key => $value ) {
227 list( $server, $conn ) = $this->getConnection( $key );
228 if ( !$conn ) {
229 continue;
230 }
231 $conns[$server] = $conn;
232 $batches[$server][] = $key;
233 }
234
235 $expiry = $this->convertToRelative( $expiry );
236 $result = true;
237 foreach ( $batches as $server => $batchKeys ) {
238 $conn = $conns[$server];
239 try {
240 $conn->multi( Redis::PIPELINE );
241 foreach ( $batchKeys as $key ) {
242 if ( $expiry ) {
243 $conn->setex( $key, $expiry, $this->serialize( $data[$key] ) );
244 } else {
245 $conn->set( $key, $this->serialize( $data[$key] ) );
246 }
247 }
248 $batchResult = $conn->exec();
249 if ( $batchResult === false ) {
250 $this->debug( "setMulti request to $server failed" );
251 continue;
252 }
253 foreach ( $batchResult as $value ) {
254 if ( $value === false ) {
255 $result = false;
256 }
257 }
258 } catch ( RedisException $e ) {
259 $this->handleException( $server, $conn, $e );
260 $result = false;
261 }
262 }
263
264 return $result;
265 }
266
267
268
269 public function add( $key, $value, $expiry = 0 ) {
270
271 list( $server, $conn ) = $this->getConnection( $key );
272 if ( !$conn ) {
273 return false;
274 }
275 $expiry = $this->convertToRelative( $expiry );
276 try {
277 if ( $expiry ) {
278 $conn->multi();
279 $conn->setnx( $key, $this->serialize( $value ) );
280 $conn->expire( $key, $expiry );
281 $result = ( $conn->exec() == array( true, true ) );
282 } else {
283 $result = $conn->setnx( $key, $this->serialize( $value ) );
284 }
285 } catch ( RedisException $e ) {
286 $result = false;
287 $this->handleException( $conn, $e );
288 }
289
290 $this->logRequest( 'add', $key, $server, $result );
291 return $result;
292 }
293
294 /**
295 * Non-atomic implementation of incr().
296 *
297 * Probably all callers actually want incr() to atomically initialise
298 * values to zero if they don't exist, as provided by the Redis INCR
299 * command. But we are constrained by the memcached-like interface to
300 * return null in that case. Once the key exists, further increments are
301 * atomic.
302 * @param string $key Key to increase
303 * @param int $value Value to add to $key (Default 1)
304 * @return int|bool New value or false on failure
305 */
306 public function incr( $key, $value = 1 ) {
307
308 list( $server, $conn ) = $this->getConnection( $key );
309 if ( !$conn ) {
310 return false;
311 }
312 if ( !$conn->exists( $key ) ) {
313 return null;
314 }
315 try {
316 $result = $conn->incrBy( $key, $value );
317 } catch ( RedisException $e ) {
318 $result = false;
319 $this->handleException( $conn, $e );
320 }
321
322 $this->logRequest( 'incr', $key, $server, $result );
323 return $result;
324 }
325
326 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
327 if ( !is_callable( $callback ) ) {
328 throw new Exception( "Got invalid callback." );
329 }
330
331 return $this->mergeViaCas( $key, $callback, $exptime, $attempts );
332 }
333
334 public function modifySimpleRelayEvent( array $event ) {
335 if ( array_key_exists( 'val', $event ) ) {
336 $event['val'] = serialize( $event['val'] ); // this class uses PHP serialization
337 }
338
339 return $event;
340 }
341
342 /**
343 * @param mixed $data
344 * @return string
345 */
346 protected function serialize( $data ) {
347 // Serialize anything but integers so INCR/DECR work
348 // Do not store integer-like strings as integers to avoid type confusion (bug 60563)
349 return is_int( $data ) ? $data : serialize( $data );
350 }
351
352 /**
353 * @param string $data
354 * @return mixed
355 */
356 protected function unserialize( $data ) {
357 return ctype_digit( $data ) ? intval( $data ) : unserialize( $data );
358 }
359
360 /**
361 * Get a Redis object with a connection suitable for fetching the specified key
362 * @param string $key
363 * @return array (server, RedisConnRef) or (false, false)
364 */
365 protected function getConnection( $key ) {
366 $candidates = array_keys( $this->serverTagMap );
367
368 if ( count( $this->servers ) > 1 ) {
369 ArrayUtils::consistentHashSort( $candidates, $key, '/' );
370 if ( !$this->automaticFailover ) {
371 $candidates = array_slice( $candidates, 0, 1 );
372 }
373 }
374
375 foreach ( $candidates as $tag ) {
376 $server = $this->serverTagMap[$tag];
377 $conn = $this->redisPool->getConnection( $server );
378 if ( $conn ) {
379 return array( $server, $conn );
380 }
381 }
382
383 $this->setLastError( BagOStuff::ERR_UNREACHABLE );
384
385 return array( false, false );
386 }
387
388 /**
389 * Log a fatal error
390 * @param string $msg
391 */
392 protected function logError( $msg ) {
393 $this->logger->error( "Redis error: $msg" );
394 }
395
396 /**
397 * The redis extension throws an exception in response to various read, write
398 * and protocol errors. Sometimes it also closes the connection, sometimes
399 * not. The safest response for us is to explicitly destroy the connection
400 * object and let it be reopened during the next request.
401 * @param RedisConnRef $conn
402 * @param Exception $e
403 */
404 protected function handleException( RedisConnRef $conn, $e ) {
405 $this->setLastError( BagOStuff::ERR_UNEXPECTED );
406 $this->redisPool->handleError( $conn, $e );
407 }
408
409 /**
410 * Send information about a single request to the debug log
411 * @param string $method
412 * @param string $key
413 * @param string $server
414 * @param bool $result
415 */
416 public function logRequest( $method, $key, $server, $result ) {
417 $this->debug( "$method $key on $server: " .
418 ( $result === false ? "failure" : "success" ) );
419 }
420 }