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