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