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