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