Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / objectcache / RedisBagOStuff.php
blobb1be9d83d09797401db29dfdf5e24b5b9d644d42
1 <?php
2 /**
3 * Object caching using Redis (http://redis.io/).
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.
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.
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
20 * @file
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;
31 /**
32 * Construct a RedisBagOStuff object. Parameters are:
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.
39 * - connectTimeout: The timeout for new connections, in seconds. Optional,
40 * default is 1 second.
42 * - persistent: Set this to true to allow connections to persist across
43 * multiple web requests. False by default.
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.
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 * @param array $params
58 function __construct( $params ) {
59 parent::__construct( $params );
60 $redisConf = array( 'serializer' => 'none' ); // manage that in this class
61 foreach ( array( 'connectTimeout', 'persistent', 'password' ) as $opt ) {
62 if ( isset( $params[$opt] ) ) {
63 $redisConf[$opt] = $params[$opt];
66 $this->redisPool = RedisConnectionPool::singleton( $redisConf );
68 $this->servers = $params['servers'];
69 if ( isset( $params['automaticFailover'] ) ) {
70 $this->automaticFailover = $params['automaticFailover'];
71 } else {
72 $this->automaticFailover = true;
76 public function get( $key, &$casToken = null ) {
78 list( $server, $conn ) = $this->getConnection( $key );
79 if ( !$conn ) {
80 return false;
82 try {
83 $value = $conn->get( $key );
84 $casToken = $value;
85 $result = $this->unserialize( $value );
86 } catch ( RedisException $e ) {
87 $result = false;
88 $this->handleException( $conn, $e );
91 $this->logRequest( 'get', $key, $server, $result );
92 return $result;
95 public function set( $key, $value, $expiry = 0 ) {
97 list( $server, $conn ) = $this->getConnection( $key );
98 if ( !$conn ) {
99 return false;
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 ) );
109 } catch ( RedisException $e ) {
110 $result = false;
111 $this->handleException( $conn, $e );
114 $this->logRequest( 'set', $key, $server, $result );
115 return $result;
118 protected function cas( $casToken, $key, $value, $expiry = 0 ) {
120 list( $server, $conn ) = $this->getConnection( $key );
121 if ( !$conn ) {
122 return false;
124 $expiry = $this->convertToRelative( $expiry );
125 try {
126 $conn->watch( $key );
128 if ( $this->serialize( $this->get( $key ) ) !== $casToken ) {
129 $conn->unwatch();
130 return false;
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 ) );
141 $result = ( $conn->exec() == array( true ) );
142 } catch ( RedisException $e ) {
143 $result = false;
144 $this->handleException( $conn, $e );
147 $this->logRequest( 'cas', $key, $server, $result );
148 return $result;
151 public function delete( $key ) {
153 list( $server, $conn ) = $this->getConnection( $key );
154 if ( !$conn ) {
155 return false;
157 try {
158 $conn->delete( $key );
159 // Return true even if the key didn't exist
160 $result = true;
161 } catch ( RedisException $e ) {
162 $result = false;
163 $this->handleException( $conn, $e );
166 $this->logRequest( 'delete', $key, $server, $result );
167 return $result;
170 public function getMulti( array $keys ) {
172 $batches = array();
173 $conns = array();
174 foreach ( $keys as $key ) {
175 list( $server, $conn ) = $this->getConnection( $key );
176 if ( !$conn ) {
177 continue;
179 $conns[$server] = $conn;
180 $batches[$server][] = $key;
182 $result = array();
183 foreach ( $batches as $server => $batchKeys ) {
184 $conn = $conns[$server];
185 try {
186 $conn->multi( Redis::PIPELINE );
187 foreach ( $batchKeys as $key ) {
188 $conn->get( $key );
190 $batchResult = $conn->exec();
191 if ( $batchResult === false ) {
192 $this->debug( "multi request to $server failed" );
193 continue;
195 foreach ( $batchResult as $i => $value ) {
196 if ( $value !== false ) {
197 $result[$batchKeys[$i]] = $this->unserialize( $value );
200 } catch ( RedisException $e ) {
201 $this->handleException( $conn, $e );
205 $this->debug( "getMulti for " . count( $keys ) . " keys " .
206 "returned " . count( $result ) . " results" );
207 return $result;
211 * @param array $data
212 * @param int $expiry
213 * @return bool
215 public function setMulti( array $data, $expiry = 0 ) {
217 $batches = array();
218 $conns = array();
219 foreach ( $data as $key => $value ) {
220 list( $server, $conn ) = $this->getConnection( $key );
221 if ( !$conn ) {
222 continue;
224 $conns[$server] = $conn;
225 $batches[$server][] = $key;
228 $expiry = $this->convertToRelative( $expiry );
229 $result = true;
230 foreach ( $batches as $server => $batchKeys ) {
231 $conn = $conns[$server];
232 try {
233 $conn->multi( Redis::PIPELINE );
234 foreach ( $batchKeys as $key ) {
235 if ( $expiry ) {
236 $conn->setex( $key, $expiry, $this->serialize( $data[$key] ) );
237 } else {
238 $conn->set( $key, $this->serialize( $data[$key] ) );
241 $batchResult = $conn->exec();
242 if ( $batchResult === false ) {
243 $this->debug( "setMulti request to $server failed" );
244 continue;
246 foreach ( $batchResult as $value ) {
247 if ( $value === false ) {
248 $result = false;
251 } catch ( RedisException $e ) {
252 $this->handleException( $server, $conn, $e );
253 $result = false;
257 return $result;
262 public function add( $key, $value, $expiry = 0 ) {
264 list( $server, $conn ) = $this->getConnection( $key );
265 if ( !$conn ) {
266 return false;
268 $expiry = $this->convertToRelative( $expiry );
269 try {
270 if ( $expiry ) {
271 $conn->multi();
272 $conn->setnx( $key, $this->serialize( $value ) );
273 $conn->expire( $key, $expiry );
274 $result = ( $conn->exec() == array( true, true ) );
275 } else {
276 $result = $conn->setnx( $key, $this->serialize( $value ) );
278 } catch ( RedisException $e ) {
279 $result = false;
280 $this->handleException( $conn, $e );
283 $this->logRequest( 'add', $key, $server, $result );
284 return $result;
288 * Non-atomic implementation of incr().
290 * Probably all callers actually want incr() to atomically initialise
291 * values to zero if they don't exist, as provided by the Redis INCR
292 * command. But we are constrained by the memcached-like interface to
293 * return null in that case. Once the key exists, further increments are
294 * atomic.
295 * @param string $key Key to increase
296 * @param int $value Value to add to $key (Default 1)
297 * @return int|bool New value or false on failure
299 public function incr( $key, $value = 1 ) {
301 list( $server, $conn ) = $this->getConnection( $key );
302 if ( !$conn ) {
303 return false;
305 if ( !$conn->exists( $key ) ) {
306 return null;
308 try {
309 $result = $conn->incrBy( $key, $value );
310 } catch ( RedisException $e ) {
311 $result = false;
312 $this->handleException( $conn, $e );
315 $this->logRequest( 'incr', $key, $server, $result );
316 return $result;
319 * @param mixed $data
320 * @return string
322 protected function serialize( $data ) {
323 // Serialize anything but integers so INCR/DECR work
324 // Do not store integer-like strings as integers to avoid type confusion (bug 60563)
325 return is_int( $data ) ? $data : serialize( $data );
329 * @param string $data
330 * @return mixed
332 protected function unserialize( $data ) {
333 return ctype_digit( $data ) ? intval( $data ) : unserialize( $data );
337 * Get a Redis object with a connection suitable for fetching the specified key
338 * @param string $key
339 * @return array (server, RedisConnRef) or (false, false)
341 protected function getConnection( $key ) {
342 if ( count( $this->servers ) === 1 ) {
343 $candidates = $this->servers;
344 } else {
345 $candidates = $this->servers;
346 ArrayUtils::consistentHashSort( $candidates, $key, '/' );
347 if ( !$this->automaticFailover ) {
348 $candidates = array_slice( $candidates, 0, 1 );
352 foreach ( $candidates as $server ) {
353 $conn = $this->redisPool->getConnection( $server );
354 if ( $conn ) {
355 return array( $server, $conn );
358 $this->setLastError( BagOStuff::ERR_UNREACHABLE );
359 return array( false, false );
363 * Log a fatal error
364 * @param string $msg
366 protected function logError( $msg ) {
367 $this->logger->error( "Redis error: $msg" );
371 * The redis extension throws an exception in response to various read, write
372 * and protocol errors. Sometimes it also closes the connection, sometimes
373 * not. The safest response for us is to explicitly destroy the connection
374 * object and let it be reopened during the next request.
375 * @param RedisConnRef $conn
376 * @param Exception $e
378 protected function handleException( RedisConnRef $conn, $e ) {
379 $this->setLastError( BagOStuff::ERR_UNEXPECTED );
380 $this->redisPool->handleError( $conn, $e );
384 * Send information about a single request to the debug log
385 * @param string $method
386 * @param string $key
387 * @param string $server
388 * @param bool $result
390 public function logRequest( $method, $key, $server, $result ) {
391 $this->debug( "$method $key on $server: " .
392 ( $result === false ? "failure" : "success" ) );