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