SECURITY: API: Don't find links in the middle of api.php links
[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' => 'none' ); // manage that in this class
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 $section = new ProfileSection( __METHOD__ );
76
77 list( $server, $conn ) = $this->getConnection( $key );
78 if ( !$conn ) {
79 return false;
80 }
81 try {
82 $value = $conn->get( $key );
83 $casToken = $value;
84 $result = $this->unserialize( $value );
85 } catch ( RedisException $e ) {
86 $result = false;
87 $this->handleException( $conn, $e );
88 }
89
90 $this->logRequest( 'get', $key, $server, $result );
91 return $result;
92 }
93
94 public function set( $key, $value, $expiry = 0 ) {
95 $section = new ProfileSection( __METHOD__ );
96
97 list( $server, $conn ) = $this->getConnection( $key );
98 if ( !$conn ) {
99 return false;
100 }
101 $expiry = $this->convertToRelative( $expiry );
102 try {
103 if ( $expiry ) {
104 $result = $conn->setex( $key, $expiry, $this->serialize( $value ) );
105 } else {
106 // No expiry, that is very different from zero expiry in Redis
107 $result = $conn->set( $key, $this->serialize( $value ) );
108 }
109 } catch ( RedisException $e ) {
110 $result = false;
111 $this->handleException( $conn, $e );
112 }
113
114 $this->logRequest( 'set', $key, $server, $result );
115 return $result;
116 }
117
118 public function cas( $casToken, $key, $value, $expiry = 0 ) {
119 $section = new ProfileSection( __METHOD__ );
120
121 list( $server, $conn ) = $this->getConnection( $key );
122 if ( !$conn ) {
123 return false;
124 }
125 $expiry = $this->convertToRelative( $expiry );
126 try {
127 $conn->watch( $key );
128
129 if ( $this->serialize( $this->get( $key ) ) !== $casToken ) {
130 $conn->unwatch();
131 return false;
132 }
133
134 // multi()/exec() will fail atomically if the key changed since watch()
135 $conn->multi();
136 if ( $expiry ) {
137 $conn->setex( $key, $expiry, $this->serialize( $value ) );
138 } else {
139 // No expiry, that is very different from zero expiry in Redis
140 $conn->set( $key, $this->serialize( $value ) );
141 }
142 $result = ( $conn->exec() == array( true ) );
143 } catch ( RedisException $e ) {
144 $result = false;
145 $this->handleException( $conn, $e );
146 }
147
148 $this->logRequest( 'cas', $key, $server, $result );
149 return $result;
150 }
151
152 public function delete( $key, $time = 0 ) {
153 $section = new ProfileSection( __METHOD__ );
154
155 list( $server, $conn ) = $this->getConnection( $key );
156 if ( !$conn ) {
157 return false;
158 }
159 try {
160 $conn->delete( $key );
161 // Return true even if the key didn't exist
162 $result = true;
163 } catch ( RedisException $e ) {
164 $result = false;
165 $this->handleException( $conn, $e );
166 }
167
168 $this->logRequest( 'delete', $key, $server, $result );
169 return $result;
170 }
171
172 public function getMulti( array $keys ) {
173 $section = new ProfileSection( __METHOD__ );
174
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]] = $this->unserialize( $value );
201 }
202 }
203 } catch ( RedisException $e ) {
204 $this->handleException( $conn, $e );
205 }
206 }
207
208 $this->debug( "getMulti for " . count( $keys ) . " keys " .
209 "returned " . count( $result ) . " results" );
210 return $result;
211 }
212
213 public function add( $key, $value, $expiry = 0 ) {
214 $section = new ProfileSection( __METHOD__ );
215
216 list( $server, $conn ) = $this->getConnection( $key );
217 if ( !$conn ) {
218 return false;
219 }
220 $expiry = $this->convertToRelative( $expiry );
221 try {
222 if ( $expiry ) {
223 $conn->multi();
224 $conn->setnx( $key, $this->serialize( $value ) );
225 $conn->expire( $key, $expiry );
226 $result = ( $conn->exec() == array( true, true ) );
227 } else {
228 $result = $conn->setnx( $key, $this->serialize( $value ) );
229 }
230 } catch ( RedisException $e ) {
231 $result = false;
232 $this->handleException( $conn, $e );
233 }
234
235 $this->logRequest( 'add', $key, $server, $result );
236 return $result;
237 }
238
239 /**
240 * Non-atomic implementation of replace(). Could perhaps be done atomically
241 * with WATCH or scripting, but this function is rarely used.
242 */
243 public function replace( $key, $value, $expiry = 0 ) {
244 $section = new ProfileSection( __METHOD__ );
245
246 list( $server, $conn ) = $this->getConnection( $key );
247 if ( !$conn ) {
248 return false;
249 }
250 if ( !$conn->exists( $key ) ) {
251 return false;
252 }
253
254 $expiry = $this->convertToRelative( $expiry );
255 try {
256 if ( !$expiry ) {
257 $result = $conn->set( $key, $this->serialize( $value ) );
258 } else {
259 $result = $conn->setex( $key, $expiry, $this->serialize( $value ) );
260 }
261 } catch ( RedisException $e ) {
262 $result = false;
263 $this->handleException( $conn, $e );
264 }
265
266 $this->logRequest( 'replace', $key, $server, $result );
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 $section = new ProfileSection( __METHOD__ );
281
282 list( $server, $conn ) = $this->getConnection( $key );
283 if ( !$conn ) {
284 return false;
285 }
286 if ( !$conn->exists( $key ) ) {
287 return null;
288 }
289 try {
290 $result = $this->unserialize( $conn->incrBy( $key, $value ) );
291 } catch ( RedisException $e ) {
292 $result = false;
293 $this->handleException( $conn, $e );
294 }
295
296 $this->logRequest( 'incr', $key, $server, $result );
297 return $result;
298 }
299
300 /**
301 * @param mixed $data
302 * @return string
303 */
304 protected function serialize( $data ) {
305 // Ignore digit strings and ints so INCR/DECR work
306 return ( is_int( $data ) || ctype_digit( $data ) ) ? $data : serialize( $data );
307 }
308
309 /**
310 * @param string $data
311 * @return mixed
312 */
313 protected function unserialize( $data ) {
314 // Ignore digit strings and ints so INCR/DECR work
315 return ( is_int( $data ) || ctype_digit( $data ) ) ? $data : unserialize( $data );
316 }
317
318 /**
319 * Get a Redis object with a connection suitable for fetching the specified key
320 * @return Array (server, RedisConnRef) or (false, false)
321 */
322 protected function getConnection( $key ) {
323 if ( count( $this->servers ) === 1 ) {
324 $candidates = $this->servers;
325 } else {
326 $candidates = $this->servers;
327 ArrayUtils::consistentHashSort( $candidates, $key, '/' );
328 if ( !$this->automaticFailover ) {
329 $candidates = array_slice( $candidates, 0, 1 );
330 }
331 }
332
333 foreach ( $candidates as $server ) {
334 $conn = $this->redisPool->getConnection( $server );
335 if ( $conn ) {
336 return array( $server, $conn );
337 }
338 }
339 return array( false, false );
340 }
341
342 /**
343 * Log a fatal error
344 */
345 protected function logError( $msg ) {
346 wfDebugLog( 'redis', "Redis error: $msg" );
347 }
348
349 /**
350 * The redis extension throws an exception in response to various read, write
351 * and protocol errors. Sometimes it also closes the connection, sometimes
352 * not. The safest response for us is to explicitly destroy the connection
353 * object and let it be reopened during the next request.
354 */
355 protected function handleException( RedisConnRef $conn, $e ) {
356 $this->redisPool->handleError( $conn, $e );
357 }
358
359 /**
360 * Send information about a single request to the debug log
361 */
362 public function logRequest( $method, $key, $server, $result ) {
363 $this->debug( "$method $key on $server: " .
364 ( $result === false ? "failure" : "success" ) );
365 }
366 }