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