4715859119c19cd80ba7142a541eef4dea4a417e
[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 class RedisBagOStuff extends BagOStuff {
25 protected $connectTimeout, $persistent, $password, $automaticFailover;
26
27 /**
28 * A list of server names, from $params['servers']
29 */
30 protected $servers;
31
32 /**
33 * A cache of Redis objects, representing connections to Redis servers.
34 * The key is the server name.
35 */
36 protected $conns = array();
37
38 /**
39 * An array listing "dead" servers which have had a connection error in
40 * the past. Servers are marked dead for a limited period of time, to
41 * avoid excessive overhead from repeated connection timeouts. The key in
42 * the array is the server name, the value is the UNIX timestamp at which
43 * the server is resurrected.
44 */
45 protected $deadServers = array();
46
47 /**
48 * Construct a RedisBagOStuff object. Parameters are:
49 *
50 * - servers: An array of server names. A server name may be a hostname,
51 * a hostname/port combination or the absolute path of a UNIX socket.
52 * If a hostname is specified but no port, the standard port number
53 * 6379 will be used. Required.
54 *
55 * - connectTimeout: The timeout for new connections, in seconds. Optional,
56 * default is 1 second.
57 *
58 * - persistent: Set this to true to allow connections to persist across
59 * multiple web requests. False by default.
60 *
61 * - password: The authentication password, will be sent to Redis in
62 * clear text. Optional, if it is unspecified, no AUTH command will be
63 * sent.
64 *
65 * - automaticFailover: If this is false, then each key will be mapped to
66 * a single server, and if that server is down, any requests for that key
67 * will fail. If this is true, a connection failure will cause the client
68 * to immediately try the next server in the list (as determined by a
69 * consistent hashing algorithm). True by default. This has the
70 * potential to create consistency issues if a server is slow enough to
71 * flap, for example if it is in swap death.
72 */
73 function __construct( $params ) {
74 if ( !extension_loaded( 'redis' ) ) {
75 throw new MWException( __CLASS__. ' requires the phpredis extension: ' .
76 'https://github.com/nicolasff/phpredis' );
77 }
78
79 $this->servers = $params['servers'];
80 $this->connectTimeout = isset( $params['connectTimeout'] )
81 ? $params['connectTimeout'] : 1;
82 $this->persistent = !empty( $params['persistent'] );
83 if ( isset( $params['password'] ) ) {
84 $this->password = $params['password'];
85 }
86 if ( isset( $params['automaticFailover'] ) ) {
87 $this->automaticFailover = $params['automaticFailover'];
88 } else {
89 $this->automaticFailover = true;
90 }
91 }
92
93 public function get( $key ) {
94 wfProfileIn( __METHOD__ );
95 list( $server, $conn ) = $this->getConnection( $key );
96 if ( !$conn ) {
97 wfProfileOut( __METHOD__ );
98 return false;
99 }
100 try {
101 $result = $conn->get( $key );
102 } catch ( RedisException $e ) {
103 $result = false;
104 $this->handleException( $server, $e );
105 }
106 $this->logRequest( 'get', $key, $server, $result );
107 wfProfileOut( __METHOD__ );
108 return $result;
109 }
110
111 public function set( $key, $value, $expiry = 0 ) {
112 wfProfileIn( __METHOD__ );
113 list( $server, $conn ) = $this->getConnection( $key );
114 if ( !$conn ) {
115 wfProfileOut( __METHOD__ );
116 return false;
117 }
118 $expiry = $this->convertToRelative( $expiry );
119 try {
120 if ( !$expiry ) {
121 // No expiry, that is very different from zero expiry in Redis
122 $result = $conn->set( $key, $value );
123 } else {
124 $result = $conn->setex( $key, $expiry, $value );
125 }
126 } catch ( RedisException $e ) {
127 $result = false;
128 $this->handleException( $server, $e );
129 }
130
131 $this->logRequest( 'set', $key, $server, $result );
132 wfProfileOut( __METHOD__ );
133 return $result;
134 }
135
136 public function delete( $key, $time = 0 ) {
137 wfProfileIn( __METHOD__ );
138 list( $server, $conn ) = $this->getConnection( $key );
139 if ( !$conn ) {
140 wfProfileOut( __METHOD__ );
141 return false;
142 }
143 try {
144 $conn->delete( $key );
145 // Return true even if the key didn't exist
146 $result = true;
147 } catch ( RedisException $e ) {
148 $result = false;
149 $this->handleException( $server, $e );
150 }
151 $this->logRequest( 'delete', $key, $server, $result );
152 wfProfileOut( __METHOD__ );
153 return $result;
154 }
155
156 public function getMulti( array $keys ) {
157 wfProfileIn( __METHOD__ );
158 $batches = array();
159 $conns = array();
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 = array();
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]] = $value;
184 }
185 }
186 } catch ( RedisException $e ) {
187 $this->handleException( $server, $e );
188 }
189 }
190
191 $this->debug( "getMulti for " . count( $keys ) . " keys " .
192 "returned " . count( $result ) . " results" );
193 wfProfileOut( __METHOD__ );
194 return $result;
195 }
196
197 public function add( $key, $value, $expiry = 0 ) {
198 wfProfileIn( __METHOD__ );
199 list( $server, $conn ) = $this->getConnection( $key );
200 if ( !$conn ) {
201 wfProfileOut( __METHOD__ );
202 return false;
203 }
204 $expiry = $this->convertToRelative( $expiry );
205 try {
206 $result = $conn->setnx( $key, $value );
207 if ( $result && $expiry ) {
208 $conn->expire( $key, $expiry );
209 }
210 } catch ( RedisException $e ) {
211 $result = false;
212 $this->handleException( $server, $e );
213 }
214 $this->logRequest( 'add', $key, $server, $result );
215 wfProfileOut( __METHOD__ );
216 return $result;
217 }
218
219 /**
220 * Non-atomic implementation of replace(). Could perhaps be done atomically
221 * with WATCH or scripting, but this function is rarely used.
222 */
223 public function replace( $key, $value, $expiry = 0 ) {
224 wfProfileIn( __METHOD__ );
225 list( $server, $conn ) = $this->getConnection( $key );
226 if ( !$conn ) {
227 wfProfileOut( __METHOD__ );
228 return false;
229 }
230 if ( !$conn->exists( $key ) ) {
231 wfProfileOut( __METHOD__ );
232 return false;
233 }
234
235 $expiry = $this->convertToRelative( $expiry );
236 try {
237 if ( !$expiry ) {
238 $result = $conn->set( $key, $value );
239 } else {
240 $result = $conn->setex( $key, $expiry, $value );
241 }
242 } catch ( RedisException $e ) {
243 $result = false;
244 $this->handleException( $server, $e );
245 }
246
247 $this->logRequest( 'replace', $key, $server, $result );
248 wfProfileOut( __METHOD__ );
249 return $result;
250 }
251
252 /**
253 * Non-atomic implementation of incr().
254 *
255 * Probably all callers actually want incr() to atomically initialise
256 * values to zero if they don't exist, as provided by the Redis INCR
257 * command. But we are constrained by the memcached-like interface to
258 * return null in that case. Once the key exists, further increments are
259 * atomic.
260 */
261 public function incr( $key, $value = 1 ) {
262 wfProfileIn( __METHOD__ );
263 list( $server, $conn ) = $this->getConnection( $key );
264 if ( !$conn ) {
265 wfProfileOut( __METHOD__ );
266 return false;
267 }
268 if ( !$conn->exists( $key ) ) {
269 wfProfileOut( __METHOD__ );
270 return null;
271 }
272 try {
273 $result = $conn->incrBy( $key, $value );
274 } catch ( RedisException $e ) {
275 $result = false;
276 $this->handleException( $server, $e );
277 }
278
279 $this->logRequest( 'incr', $key, $server, $result );
280 wfProfileOut( __METHOD__ );
281 return $result;
282 }
283
284 /**
285 * Get a Redis object with a connection suitable for fetching the specified key
286 */
287 protected function getConnection( $key ) {
288 if ( count( $this->servers ) === 1 ) {
289 $candidates = $this->servers;
290 } else {
291 $candidates = $this->servers;
292 ArrayUtils::consistentHashSort( $candidates, $key, '/' );
293 if ( !$this->automaticFailover ) {
294 $candidates = array_slice( $candidates, 0, 1 );
295 }
296 }
297
298 foreach ( $candidates as $server ) {
299 $conn = $this->getConnectionToServer( $server );
300 if ( $conn ) {
301 return array( $server, $conn );
302 }
303 }
304 return array( false, false );
305 }
306
307 /**
308 * Get a connection to the server with the specified name. Connections
309 * are cached, and failures are persistent to avoid multiple timeouts.
310 *
311 * @param $server
312 * @throws MWException
313 * @return Redis object, or false on failure
314 */
315 protected function getConnectionToServer( $server ) {
316 if ( isset( $this->deadServers[$server] ) ) {
317 $now = time();
318 if ( $now > $this->deadServers[$server] ) {
319 // Dead time expired
320 unset( $this->deadServers[$server] );
321 } else {
322 // Server is dead
323 $this->debug( "server $server is marked down for another " .
324 ($this->deadServers[$server] - $now ) .
325 " seconds, can't get connection" );
326 return false;
327 }
328 }
329
330 if ( isset( $this->conns[$server] ) ) {
331 return $this->conns[$server];
332 }
333
334 if ( substr( $server, 0, 1 ) === '/' ) {
335 // UNIX domain socket
336 // These are required by the redis extension to start with a slash, but
337 // we still need to set the port to a special value to make it work.
338 $host = $server;
339 $port = 0;
340 } else {
341 // TCP connection
342 $hostPort = IP::splitHostAndPort( $server );
343 if ( !$hostPort ) {
344 throw new MWException( __CLASS__.": invalid configured server \"$server\"" );
345 }
346 list( $host, $port ) = $hostPort;
347 if ( $port === false ) {
348 $port = 6379;
349 }
350 }
351 $conn = new Redis;
352 try {
353 if ( $this->persistent ) {
354 $this->debug( "opening persistent connection to $host:$port" );
355 $result = $conn->pconnect( $host, $port, $this->connectTimeout );
356 } else {
357 $this->debug( "opening non-persistent connection to $host:$port" );
358 $result = $conn->connect( $host, $port, $this->connectTimeout );
359 }
360 if ( !$result ) {
361 $this->logError( "could not connect to server $server" );
362 // Mark server down for 30s to avoid further timeouts
363 $this->deadServers[$server] = time() + 30;
364 return false;
365 }
366 if ( $this->password !== null ) {
367 if ( !$conn->auth( $this->password ) ) {
368 $this->logError( "authentication error connecting to $server" );
369 }
370 }
371 } catch ( RedisException $e ) {
372 $this->deadServers[$server] = time() + 30;
373 wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
374 return false;
375 }
376
377 $conn->setOption( Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP );
378 $this->conns[$server] = $conn;
379 return $conn;
380 }
381
382 /**
383 * Log a fatal error
384 */
385 protected function logError( $msg ) {
386 wfDebugLog( 'redis', "Redis error: $msg\n" );
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 */
395 protected function handleException( $server, $e ) {
396 wfDebugLog( 'redis', "Redis exception on server $server: " . $e->getMessage() . "\n" );
397 unset( $this->conns[$server] );
398 }
399
400 /**
401 * Send information about a single request to the debug log
402 */
403 public function logRequest( $method, $key, $server, $result ) {
404 $this->debug( "$method $key on $server: " .
405 ( $result === false ? "failure" : "success" ) );
406 }
407 }
408