Merge "Fix 'Tags' padding to keep it farther from the edge and document the source...
[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 $casToken = null;
95
96 return $this->getWithToken( $key, $casToken, $flags );
97 }
98
99 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
100 list( $server, $conn ) = $this->getConnection( $key );
101 if ( !$conn ) {
102 return false;
103 }
104 try {
105 $value = $conn->get( $key );
106 $casToken = $value;
107 $result = $this->unserialize( $value );
108 } catch ( RedisException $e ) {
109 $result = false;
110 $this->handleException( $conn, $e );
111 }
112
113 $this->logRequest( 'get', $key, $server, $result );
114 return $result;
115 }
116
117 public function set( $key, $value, $expiry = 0, $flags = 0 ) {
118 list( $server, $conn ) = $this->getConnection( $key );
119 if ( !$conn ) {
120 return false;
121 }
122 $expiry = $this->convertToRelative( $expiry );
123 try {
124 if ( $expiry ) {
125 $result = $conn->setex( $key, $expiry, $this->serialize( $value ) );
126 } else {
127 // No expiry, that is very different from zero expiry in Redis
128 $result = $conn->set( $key, $this->serialize( $value ) );
129 }
130 } catch ( RedisException $e ) {
131 $result = false;
132 $this->handleException( $conn, $e );
133 }
134
135 $this->logRequest( 'set', $key, $server, $result );
136 return $result;
137 }
138
139 public function delete( $key ) {
140 list( $server, $conn ) = $this->getConnection( $key );
141 if ( !$conn ) {
142 return false;
143 }
144 try {
145 $conn->delete( $key );
146 // Return true even if the key didn't exist
147 $result = true;
148 } catch ( RedisException $e ) {
149 $result = false;
150 $this->handleException( $conn, $e );
151 }
152
153 $this->logRequest( 'delete', $key, $server, $result );
154 return $result;
155 }
156
157 public function getMulti( array $keys, $flags = 0 ) {
158 $batches = [];
159 $conns = [];
160 foreach ( $keys as $key ) {
161 list( $server, $conn ) = $this->getConnection( $key );
162 if ( !$conn ) {
163 continue;
164 }
165 $conns[$server] = $conn;
166 $batches[$server][] = $key;
167 }
168 $result = [];
169 foreach ( $batches as $server => $batchKeys ) {
170 $conn = $conns[$server];
171 try {
172 $conn->multi( Redis::PIPELINE );
173 foreach ( $batchKeys as $key ) {
174 $conn->get( $key );
175 }
176 $batchResult = $conn->exec();
177 if ( $batchResult === false ) {
178 $this->debug( "multi request to $server failed" );
179 continue;
180 }
181 foreach ( $batchResult as $i => $value ) {
182 if ( $value !== false ) {
183 $result[$batchKeys[$i]] = $this->unserialize( $value );
184 }
185 }
186 } catch ( RedisException $e ) {
187 $this->handleException( $conn, $e );
188 }
189 }
190
191 $this->debug( "getMulti for " . count( $keys ) . " keys " .
192 "returned " . count( $result ) . " results" );
193 return $result;
194 }
195
196 /**
197 * @param array $data
198 * @param int $expiry
199 * @return bool
200 */
201 public function setMulti( array $data, $expiry = 0 ) {
202 $batches = [];
203 $conns = [];
204 foreach ( $data as $key => $value ) {
205 list( $server, $conn ) = $this->getConnection( $key );
206 if ( !$conn ) {
207 continue;
208 }
209 $conns[$server] = $conn;
210 $batches[$server][] = $key;
211 }
212
213 $expiry = $this->convertToRelative( $expiry );
214 $result = true;
215 foreach ( $batches as $server => $batchKeys ) {
216 $conn = $conns[$server];
217 try {
218 $conn->multi( Redis::PIPELINE );
219 foreach ( $batchKeys as $key ) {
220 if ( $expiry ) {
221 $conn->setex( $key, $expiry, $this->serialize( $data[$key] ) );
222 } else {
223 $conn->set( $key, $this->serialize( $data[$key] ) );
224 }
225 }
226 $batchResult = $conn->exec();
227 if ( $batchResult === false ) {
228 $this->debug( "setMulti request to $server failed" );
229 continue;
230 }
231 foreach ( $batchResult as $value ) {
232 if ( $value === false ) {
233 $result = false;
234 }
235 }
236 } catch ( RedisException $e ) {
237 $this->handleException( $server, $conn, $e );
238 $result = false;
239 }
240 }
241
242 return $result;
243 }
244
245 public function add( $key, $value, $expiry = 0 ) {
246 list( $server, $conn ) = $this->getConnection( $key );
247 if ( !$conn ) {
248 return false;
249 }
250 $expiry = $this->convertToRelative( $expiry );
251 try {
252 if ( $expiry ) {
253 $result = $conn->set(
254 $key,
255 $this->serialize( $value ),
256 [ 'nx', 'ex' => $expiry ]
257 );
258 } else {
259 $result = $conn->setnx( $key, $this->serialize( $value ) );
260 }
261 } catch ( RedisException $e ) {
262 $result = false;
263 $this->handleException( $conn, $e );
264 }
265
266 $this->logRequest( 'add', $key, $server, $result );
267 return $result;
268 }
269
270 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
271 return $this->mergeViaCas( $key, $callback, $exptime, $attempts );
272 }
273
274 /**
275 * Non-atomic implementation of incr().
276 *
277 * Probably all callers actually want incr() to atomically initialise
278 * values to zero if they don't exist, as provided by the Redis INCR
279 * command. But we are constrained by the memcached-like interface to
280 * return null in that case. Once the key exists, further increments are
281 * atomic.
282 * @param string $key Key to increase
283 * @param int $value Value to add to $key (Default 1)
284 * @return int|bool New value or false on failure
285 */
286 public function incr( $key, $value = 1 ) {
287 list( $server, $conn ) = $this->getConnection( $key );
288 if ( !$conn ) {
289 return false;
290 }
291 try {
292 if ( !$conn->exists( $key ) ) {
293 return false;
294 }
295 // @FIXME: on races, the key may have a 0 TTL
296 $result = $conn->incrBy( $key, $value );
297 } catch ( RedisException $e ) {
298 $result = false;
299 $this->handleException( $conn, $e );
300 }
301
302 $this->logRequest( 'incr', $key, $server, $result );
303 return $result;
304 }
305
306 public function changeTTL( $key, $expiry = 0 ) {
307 list( $server, $conn ) = $this->getConnection( $key );
308 if ( !$conn ) {
309 return false;
310 }
311
312 $expiry = $this->convertToRelative( $expiry );
313 try {
314 $result = $conn->expire( $key, $expiry );
315 } catch ( RedisException $e ) {
316 $result = false;
317 $this->handleException( $conn, $e );
318 }
319
320 $this->logRequest( 'expire', $key, $server, $result );
321 return $result;
322 }
323
324 public function modifySimpleRelayEvent( array $event ) {
325 if ( array_key_exists( 'val', $event ) ) {
326 $event['val'] = serialize( $event['val'] ); // this class uses PHP serialization
327 }
328
329 return $event;
330 }
331
332 /**
333 * @param mixed $data
334 * @return string
335 */
336 protected function serialize( $data ) {
337 // Serialize anything but integers so INCR/DECR work
338 // Do not store integer-like strings as integers to avoid type confusion (T62563)
339 return is_int( $data ) ? $data : serialize( $data );
340 }
341
342 /**
343 * @param string $data
344 * @return mixed
345 */
346 protected function unserialize( $data ) {
347 $int = intval( $data );
348 return $data === (string)$int ? $int : unserialize( $data );
349 }
350
351 /**
352 * Get a Redis object with a connection suitable for fetching the specified key
353 * @param string $key
354 * @return array (server, RedisConnRef) or (false, false)
355 */
356 protected function getConnection( $key ) {
357 $candidates = array_keys( $this->serverTagMap );
358
359 if ( count( $this->servers ) > 1 ) {
360 ArrayUtils::consistentHashSort( $candidates, $key, '/' );
361 if ( !$this->automaticFailover ) {
362 $candidates = array_slice( $candidates, 0, 1 );
363 }
364 }
365
366 while ( ( $tag = array_shift( $candidates ) ) !== null ) {
367 $server = $this->serverTagMap[$tag];
368 $conn = $this->redisPool->getConnection( $server, $this->logger );
369 if ( !$conn ) {
370 continue;
371 }
372
373 // If automatic failover is enabled, check that the server's link
374 // to its master (if any) is up -- but only if there are other
375 // viable candidates left to consider. Also, getMasterLinkStatus()
376 // does not work with twemproxy, though $candidates will be empty
377 // by now in such cases.
378 if ( $this->automaticFailover && $candidates ) {
379 try {
380 if ( $this->getMasterLinkStatus( $conn ) === 'down' ) {
381 // If the master cannot be reached, fail-over to the next server.
382 // If masters are in data-center A, and replica DBs in data-center B,
383 // this helps avoid the case were fail-over happens in A but not
384 // to the corresponding server in B (e.g. read/write mismatch).
385 continue;
386 }
387 } catch ( RedisException $e ) {
388 // Server is not accepting commands
389 $this->handleException( $conn, $e );
390 continue;
391 }
392 }
393
394 return [ $server, $conn ];
395 }
396
397 $this->setLastError( BagOStuff::ERR_UNREACHABLE );
398
399 return [ false, false ];
400 }
401
402 /**
403 * Check the master link status of a Redis server that is configured as a replica DB.
404 * @param RedisConnRef $conn
405 * @return string|null Master link status (either 'up' or 'down'), or null
406 * if the server is not a replica DB.
407 */
408 protected function getMasterLinkStatus( RedisConnRef $conn ) {
409 $info = $conn->info();
410 return $info['master_link_status'] ?? null;
411 }
412
413 /**
414 * Log a fatal error
415 * @param string $msg
416 */
417 protected function logError( $msg ) {
418 $this->logger->error( "Redis error: $msg" );
419 }
420
421 /**
422 * The redis extension throws an exception in response to various read, write
423 * and protocol errors. Sometimes it also closes the connection, sometimes
424 * not. The safest response for us is to explicitly destroy the connection
425 * object and let it be reopened during the next request.
426 * @param RedisConnRef $conn
427 * @param Exception $e
428 */
429 protected function handleException( RedisConnRef $conn, $e ) {
430 $this->setLastError( BagOStuff::ERR_UNEXPECTED );
431 $this->redisPool->handleError( $conn, $e );
432 }
433
434 /**
435 * Send information about a single request to the debug log
436 * @param string $method
437 * @param string $key
438 * @param string $server
439 * @param bool $result
440 */
441 public function logRequest( $method, $key, $server, $result ) {
442 $this->debug( "$method $key on $server: " .
443 ( $result === false ? "failure" : "success" ) );
444 }
445 }