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