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