Merge "(bug 40072) Add semantic CSS classes to identify changes list items"
[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 // Use consistent hashing
292 $hashes = array();
293 foreach ( $this->servers as $server ) {
294 $hashes[$server] = md5( $server . '/' . $key );
295 }
296 asort( $hashes );
297 if ( !$this->automaticFailover ) {
298 reset( $hashes );
299 $candidates = array( key( $hashes ) );
300 } else {
301 $candidates = array_keys( $hashes );
302 }
303 }
304
305 foreach ( $candidates as $server ) {
306 $conn = $this->getConnectionToServer( $server );
307 if ( $conn ) {
308 return array( $server, $conn );
309 }
310 }
311 return array( false, false );
312 }
313
314 /**
315 * Get a connection to the server with the specified name. Connections
316 * are cached, and failures are persistent to avoid multiple timeouts.
317 *
318 * @return Redis object, or false on failure
319 */
320 protected function getConnectionToServer( $server ) {
321 if ( isset( $this->deadServers[$server] ) ) {
322 $now = time();
323 if ( $now > $this->deadServers[$server] ) {
324 // Dead time expired
325 unset( $this->deadServers[$server] );
326 } else {
327 // Server is dead
328 $this->debug( "server $server is marked down for another " .
329 ($this->deadServers[$server] - $now ) .
330 " seconds, can't get connection" );
331 return false;
332 }
333 }
334
335 if ( isset( $this->conns[$server] ) ) {
336 return $this->conns[$server];
337 }
338
339 if ( substr( $server, 0, 1 ) === '/' ) {
340 // UNIX domain socket
341 // These are required by the redis extension to start with a slash, but
342 // we still need to set the port to a special value to make it work.
343 $host = $server;
344 $port = 0;
345 } else {
346 // TCP connection
347 $hostPort = IP::splitHostAndPort( $server );
348 if ( !$hostPort ) {
349 throw new MWException( __CLASS__.": invalid configured server \"$server\"" );
350 }
351 list( $host, $port ) = $hostPort;
352 if ( $port === false ) {
353 $port = 6379;
354 }
355 }
356 $conn = new Redis;
357 try {
358 if ( $this->persistent ) {
359 $this->debug( "opening persistent connection to $host:$port" );
360 $result = $conn->pconnect( $host, $port, $this->connectTimeout );
361 } else {
362 $this->debug( "opening non-persistent connection to $host:$port" );
363 $result = $conn->connect( $host, $port, $this->connectTimeout );
364 }
365 if ( !$result ) {
366 $this->logError( "could not connect to server $server" );
367 // Mark server down for 30s to avoid further timeouts
368 $this->deadServers[$server] = time() + 30;
369 return false;
370 }
371 if ( $this->password !== null ) {
372 if ( !$conn->auth( $this->password ) ) {
373 $this->logError( "authentication error connecting to $server" );
374 }
375 }
376 } catch ( RedisException $e ) {
377 $this->deadServers[$server] = time() + 30;
378 wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
379 return false;
380 }
381
382 $conn->setOption( Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP );
383 $this->conns[$server] = $conn;
384 return $conn;
385 }
386
387 /**
388 * Log a fatal error
389 */
390 protected function logError( $msg ) {
391 wfDebugLog( 'redis', "Redis error: $msg\n" );
392 }
393
394 /**
395 * The redis extension throws an exception in response to various read, write
396 * and protocol errors. Sometimes it also closes the connection, sometimes
397 * not. The safest response for us is to explicitly destroy the connection
398 * object and let it be reopened during the next request.
399 */
400 protected function handleException( $server, $e ) {
401 wfDebugLog( 'redis', "Redis exception on server $server: " . $e->getMessage() . "\n" );
402 unset( $this->conns[$server] );
403 }
404
405 /**
406 * Send information about a single request to the debug log
407 */
408 public function logRequest( $method, $key, $server, $result ) {
409 $this->debug( "$method $key on $server: " .
410 ( $result === false ? "failure" : "success" ) );
411 }
412 }
413