a9f5f8c7e2c62a644c41bed7f2299572e59fb8fb
[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 class RedisBagOStuff extends BagOStuff {
23 /** @var RedisConnectionPool */
24 protected $redisPool;
25 /** @var Array List of server names */
26 protected $servers;
27 /** @var bool */
28 protected $automaticFailover;
29
30 /**
31 * Construct a RedisBagOStuff object. Parameters are:
32 *
33 * - servers: An array of server names. A server name may be a hostname,
34 * a hostname/port combination or the absolute path of a UNIX socket.
35 * If a hostname is specified but no port, the standard port number
36 * 6379 will be used. Required.
37 *
38 * - connectTimeout: The timeout for new connections, in seconds. Optional,
39 * default is 1 second.
40 *
41 * - persistent: Set this to true to allow connections to persist across
42 * multiple web requests. False by default.
43 *
44 * - password: The authentication password, will be sent to Redis in
45 * clear text. Optional, if it is unspecified, no AUTH command will be
46 * sent.
47 *
48 * - automaticFailover: If this is false, then each key will be mapped to
49 * a single server, and if that server is down, any requests for that key
50 * will fail. If this is true, a connection failure will cause the client
51 * to immediately try the next server in the list (as determined by a
52 * consistent hashing algorithm). True by default. This has the
53 * potential to create consistency issues if a server is slow enough to
54 * flap, for example if it is in swap death.
55 */
56 function __construct( $params ) {
57 $redisConf = array( 'serializer' => 'php' );
58 foreach ( array( 'connectTimeout', 'persistent', 'password' ) as $opt ) {
59 if ( isset( $params[$opt] ) ) {
60 $redisConf[$opt] = $params[$opt];
61 }
62 }
63 $this->redisPool = RedisConnectionPool::singleton( $redisConf );
64
65 $this->servers = $params['servers'];
66 if ( isset( $params['automaticFailover'] ) ) {
67 $this->automaticFailover = $params['automaticFailover'];
68 } else {
69 $this->automaticFailover = true;
70 }
71 }
72
73 public function get( $key, &$casToken = null ) {
74 wfProfileIn( __METHOD__ );
75 list( $server, $conn ) = $this->getConnection( $key );
76 if ( !$conn ) {
77 wfProfileOut( __METHOD__ );
78 return false;
79 }
80 try {
81 $result = $conn->get( $key );
82 } catch ( RedisException $e ) {
83 $result = false;
84 $this->handleException( $server, $conn, $e );
85 }
86 $casToken = $result;
87 $this->logRequest( 'get', $key, $server, $result );
88 wfProfileOut( __METHOD__ );
89 return $result;
90 }
91
92 public function set( $key, $value, $expiry = 0 ) {
93 wfProfileIn( __METHOD__ );
94 list( $server, $conn ) = $this->getConnection( $key );
95 if ( !$conn ) {
96 wfProfileOut( __METHOD__ );
97 return false;
98 }
99 $expiry = $this->convertToRelative( $expiry );
100 try {
101 if ( !$expiry ) {
102 // No expiry, that is very different from zero expiry in Redis
103 $result = $conn->set( $key, $value );
104 } else {
105 $result = $conn->setex( $key, $expiry, $value );
106 }
107 } catch ( RedisException $e ) {
108 $result = false;
109 $this->handleException( $server, $conn, $e );
110 }
111
112 $this->logRequest( 'set', $key, $server, $result );
113 wfProfileOut( __METHOD__ );
114 return $result;
115 }
116
117 public function cas( $casToken, $key, $value, $expiry = 0 ) {
118 wfProfileIn( __METHOD__ );
119 list( $server, $conn ) = $this->getConnection( $key );
120 if ( !$conn ) {
121 wfProfileOut( __METHOD__ );
122 return false;
123 }
124 $expiry = $this->convertToRelative( $expiry );
125 try {
126 $conn->watch( $key );
127
128 if ( $this->get( $key ) !== $casToken ) {
129 wfProfileOut( __METHOD__ );
130 return false;
131 }
132
133 $conn->multi();
134
135 if ( !$expiry ) {
136 // No expiry, that is very different from zero expiry in Redis
137 $conn->set( $key, $value );
138 } else {
139 $conn->setex( $key, $expiry, $value );
140 }
141
142 $result = $conn->exec();
143 } catch ( RedisException $e ) {
144 $result = false;
145 $this->handleException( $server, $conn, $e );
146 }
147
148 $this->logRequest( 'cas', $key, $server, $result );
149 wfProfileOut( __METHOD__ );
150 return $result;
151 }
152
153 public function delete( $key, $time = 0 ) {
154 wfProfileIn( __METHOD__ );
155 list( $server, $conn ) = $this->getConnection( $key );
156 if ( !$conn ) {
157 wfProfileOut( __METHOD__ );
158 return false;
159 }
160 try {
161 $conn->delete( $key );
162 // Return true even if the key didn't exist
163 $result = true;
164 } catch ( RedisException $e ) {
165 $result = false;
166 $this->handleException( $server, $conn, $e );
167 }
168 $this->logRequest( 'delete', $key, $server, $result );
169 wfProfileOut( __METHOD__ );
170 return $result;
171 }
172
173 public function getMulti( array $keys ) {
174 wfProfileIn( __METHOD__ );
175 $batches = array();
176 $conns = array();
177 foreach ( $keys as $key ) {
178 list( $server, $conn ) = $this->getConnection( $key );
179 if ( !$conn ) {
180 continue;
181 }
182 $conns[$server] = $conn;
183 $batches[$server][] = $key;
184 }
185 $result = array();
186 foreach ( $batches as $server => $batchKeys ) {
187 $conn = $conns[$server];
188 try {
189 $conn->multi( Redis::PIPELINE );
190 foreach ( $batchKeys as $key ) {
191 $conn->get( $key );
192 }
193 $batchResult = $conn->exec();
194 if ( $batchResult === false ) {
195 $this->debug( "multi request to $server failed" );
196 continue;
197 }
198 foreach ( $batchResult as $i => $value ) {
199 if ( $value !== false ) {
200 $result[$batchKeys[$i]] = $value;
201 }
202 }
203 } catch ( RedisException $e ) {
204 $this->handleException( $server, $conn, $e );
205 }
206 }
207
208 $this->debug( "getMulti for " . count( $keys ) . " keys " .
209 "returned " . count( $result ) . " results" );
210 wfProfileOut( __METHOD__ );
211 return $result;
212 }
213
214 public function add( $key, $value, $expiry = 0 ) {
215 wfProfileIn( __METHOD__ );
216 list( $server, $conn ) = $this->getConnection( $key );
217 if ( !$conn ) {
218 wfProfileOut( __METHOD__ );
219 return false;
220 }
221 $expiry = $this->convertToRelative( $expiry );
222 try {
223 $result = $conn->setnx( $key, $value );
224 if ( $result && $expiry ) {
225 $conn->expire( $key, $expiry );
226 }
227 } catch ( RedisException $e ) {
228 $result = false;
229 $this->handleException( $server, $conn, $e );
230 }
231 $this->logRequest( 'add', $key, $server, $result );
232 wfProfileOut( __METHOD__ );
233 return $result;
234 }
235
236 /**
237 * Non-atomic implementation of replace(). Could perhaps be done atomically
238 * with WATCH or scripting, but this function is rarely used.
239 */
240 public function replace( $key, $value, $expiry = 0 ) {
241 wfProfileIn( __METHOD__ );
242 list( $server, $conn ) = $this->getConnection( $key );
243 if ( !$conn ) {
244 wfProfileOut( __METHOD__ );
245 return false;
246 }
247 if ( !$conn->exists( $key ) ) {
248 wfProfileOut( __METHOD__ );
249 return false;
250 }
251
252 $expiry = $this->convertToRelative( $expiry );
253 try {
254 if ( !$expiry ) {
255 $result = $conn->set( $key, $value );
256 } else {
257 $result = $conn->setex( $key, $expiry, $value );
258 }
259 } catch ( RedisException $e ) {
260 $result = false;
261 $this->handleException( $server, $conn, $e );
262 }
263
264 $this->logRequest( 'replace', $key, $server, $result );
265 wfProfileOut( __METHOD__ );
266 return $result;
267 }
268
269 /**
270 * Non-atomic implementation of incr().
271 *
272 * Probably all callers actually want incr() to atomically initialise
273 * values to zero if they don't exist, as provided by the Redis INCR
274 * command. But we are constrained by the memcached-like interface to
275 * return null in that case. Once the key exists, further increments are
276 * atomic.
277 */
278 public function incr( $key, $value = 1 ) {
279 wfProfileIn( __METHOD__ );
280 list( $server, $conn ) = $this->getConnection( $key );
281 if ( !$conn ) {
282 wfProfileOut( __METHOD__ );
283 return false;
284 }
285 if ( !$conn->exists( $key ) ) {
286 wfProfileOut( __METHOD__ );
287 return null;
288 }
289 try {
290 $result = $conn->incrBy( $key, $value );
291 } catch ( RedisException $e ) {
292 $result = false;
293 $this->handleException( $server, $conn, $e );
294 }
295
296 $this->logRequest( 'incr', $key, $server, $result );
297 wfProfileOut( __METHOD__ );
298 return $result;
299 }
300
301 /**
302 * Get a Redis object with a connection suitable for fetching the specified key
303 * @return Array (server, RedisConnRef) or (false, false)
304 */
305 protected function getConnection( $key ) {
306 if ( count( $this->servers ) === 1 ) {
307 $candidates = $this->servers;
308 } else {
309 $candidates = $this->servers;
310 ArrayUtils::consistentHashSort( $candidates, $key, '/' );
311 if ( !$this->automaticFailover ) {
312 $candidates = array_slice( $candidates, 0, 1 );
313 }
314 }
315
316 foreach ( $candidates as $server ) {
317 $conn = $this->redisPool->getConnection( $server );
318 if ( $conn ) {
319 return array( $server, $conn );
320 }
321 }
322 return array( false, false );
323 }
324
325 /**
326 * Log a fatal error
327 */
328 protected function logError( $msg ) {
329 wfDebugLog( 'redis', "Redis error: $msg\n" );
330 }
331
332 /**
333 * The redis extension throws an exception in response to various read, write
334 * and protocol errors. Sometimes it also closes the connection, sometimes
335 * not. The safest response for us is to explicitly destroy the connection
336 * object and let it be reopened during the next request.
337 */
338 protected function handleException( $server, RedisConnRef $conn, $e ) {
339 $this->redisPool->handleException( $server, $conn, $e );
340 }
341
342 /**
343 * Send information about a single request to the debug log
344 */
345 public function logRequest( $method, $key, $server, $result ) {
346 $this->debug( "$method $key on $server: " .
347 ( $result === false ? "failure" : "success" ) );
348 }
349 }