Remove useless comments from search output
[mediawiki.git] / includes / objectcache / RedisBagOStuff.php
blobd6d49ae5824872cdc1bad357b067e76e44ec65e0
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 $redisConf = array( 'serializer' => 'none' ); // manage that in this class
60 foreach ( array( 'connectTimeout', 'persistent', 'password' ) as $opt ) {
61 if ( isset( $params[$opt] ) ) {
62 $redisConf[$opt] = $params[$opt];
65 $this->redisPool = RedisConnectionPool::singleton( $redisConf );
67 $this->servers = $params['servers'];
68 if ( isset( $params['automaticFailover'] ) ) {
69 $this->automaticFailover = $params['automaticFailover'];
70 } else {
71 $this->automaticFailover = true;
75 public function get( $key, &$casToken = null ) {
76 $section = new ProfileSection( __METHOD__ );
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 ) {
96 $section = new ProfileSection( __METHOD__ );
98 list( $server, $conn ) = $this->getConnection( $key );
99 if ( !$conn ) {
100 return false;
102 $expiry = $this->convertToRelative( $expiry );
103 try {
104 if ( $expiry ) {
105 $result = $conn->setex( $key, $expiry, $this->serialize( $value ) );
106 } else {
107 // No expiry, that is very different from zero expiry in Redis
108 $result = $conn->set( $key, $this->serialize( $value ) );
110 } catch ( RedisException $e ) {
111 $result = false;
112 $this->handleException( $conn, $e );
115 $this->logRequest( 'set', $key, $server, $result );
116 return $result;
119 public function cas( $casToken, $key, $value, $expiry = 0 ) {
120 $section = new ProfileSection( __METHOD__ );
122 list( $server, $conn ) = $this->getConnection( $key );
123 if ( !$conn ) {
124 return false;
126 $expiry = $this->convertToRelative( $expiry );
127 try {
128 $conn->watch( $key );
130 if ( $this->serialize( $this->get( $key ) ) !== $casToken ) {
131 $conn->unwatch();
132 return false;
135 // multi()/exec() will fail atomically if the key changed since watch()
136 $conn->multi();
137 if ( $expiry ) {
138 $conn->setex( $key, $expiry, $this->serialize( $value ) );
139 } else {
140 // No expiry, that is very different from zero expiry in Redis
141 $conn->set( $key, $this->serialize( $value ) );
143 $result = ( $conn->exec() == array( true ) );
144 } catch ( RedisException $e ) {
145 $result = false;
146 $this->handleException( $conn, $e );
149 $this->logRequest( 'cas', $key, $server, $result );
150 return $result;
153 public function delete( $key, $time = 0 ) {
154 $section = new ProfileSection( __METHOD__ );
156 list( $server, $conn ) = $this->getConnection( $key );
157 if ( !$conn ) {
158 return false;
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( $conn, $e );
169 $this->logRequest( 'delete', $key, $server, $result );
170 return $result;
173 public function getMulti( array $keys ) {
174 $section = new ProfileSection( __METHOD__ );
176 $batches = array();
177 $conns = array();
178 foreach ( $keys as $key ) {
179 list( $server, $conn ) = $this->getConnection( $key );
180 if ( !$conn ) {
181 continue;
183 $conns[$server] = $conn;
184 $batches[$server][] = $key;
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 );
194 $batchResult = $conn->exec();
195 if ( $batchResult === false ) {
196 $this->debug( "multi request to $server failed" );
197 continue;
199 foreach ( $batchResult as $i => $value ) {
200 if ( $value !== false ) {
201 $result[$batchKeys[$i]] = $this->unserialize( $value );
204 } catch ( RedisException $e ) {
205 $this->handleException( $conn, $e );
209 $this->debug( "getMulti for " . count( $keys ) . " keys " .
210 "returned " . count( $result ) . " results" );
211 return $result;
214 public function add( $key, $value, $expiry = 0 ) {
215 $section = new ProfileSection( __METHOD__ );
217 list( $server, $conn ) = $this->getConnection( $key );
218 if ( !$conn ) {
219 return false;
221 $expiry = $this->convertToRelative( $expiry );
222 try {
223 if ( $expiry ) {
224 $conn->multi();
225 $conn->setnx( $key, $this->serialize( $value ) );
226 $conn->expire( $key, $expiry );
227 $result = ( $conn->exec() == array( true, true ) );
228 } else {
229 $result = $conn->setnx( $key, $this->serialize( $value ) );
231 } catch ( RedisException $e ) {
232 $result = false;
233 $this->handleException( $conn, $e );
236 $this->logRequest( 'add', $key, $server, $result );
237 return $result;
241 * Non-atomic implementation of incr().
243 * Probably all callers actually want incr() to atomically initialise
244 * values to zero if they don't exist, as provided by the Redis INCR
245 * command. But we are constrained by the memcached-like interface to
246 * return null in that case. Once the key exists, further increments are
247 * atomic.
248 * @param string $key
249 * @param int $value
250 * @param bool|mixed
252 public function incr( $key, $value = 1 ) {
253 $section = new ProfileSection( __METHOD__ );
255 list( $server, $conn ) = $this->getConnection( $key );
256 if ( !$conn ) {
257 return false;
259 if ( !$conn->exists( $key ) ) {
260 return null;
262 try {
263 $result = $this->unserialize( $conn->incrBy( $key, $value ) );
264 } catch ( RedisException $e ) {
265 $result = false;
266 $this->handleException( $conn, $e );
269 $this->logRequest( 'incr', $key, $server, $result );
270 return $result;
274 * @param mixed $data
275 * @return string
277 protected function serialize( $data ) {
278 // Ignore digit strings and ints so INCR/DECR work
279 return ( is_int( $data ) || ctype_digit( $data ) ) ? $data : serialize( $data );
283 * @param string $data
284 * @return mixed
286 protected function unserialize( $data ) {
287 // Ignore digit strings and ints so INCR/DECR work
288 return ( is_int( $data ) || ctype_digit( $data ) ) ? $data : unserialize( $data );
292 * Get a Redis object with a connection suitable for fetching the specified key
293 * @return array (server, RedisConnRef) or (false, false)
295 protected function getConnection( $key ) {
296 if ( count( $this->servers ) === 1 ) {
297 $candidates = $this->servers;
298 } else {
299 $candidates = $this->servers;
300 ArrayUtils::consistentHashSort( $candidates, $key, '/' );
301 if ( !$this->automaticFailover ) {
302 $candidates = array_slice( $candidates, 0, 1 );
306 foreach ( $candidates as $server ) {
307 $conn = $this->redisPool->getConnection( $server );
308 if ( $conn ) {
309 return array( $server, $conn );
312 $this->setLastError( BagOStuff::ERR_UNREACHABLE );
313 return array( false, false );
317 * Log a fatal error
318 * @param string $msg
320 protected function logError( $msg ) {
321 wfDebugLog( 'redis', "Redis error: $msg" );
325 * The redis extension throws an exception in response to various read, write
326 * and protocol errors. Sometimes it also closes the connection, sometimes
327 * not. The safest response for us is to explicitly destroy the connection
328 * object and let it be reopened during the next request.
329 * @param RedisConnRef $conn
330 * @param Exception $e
332 protected function handleException( RedisConnRef $conn, $e ) {
333 $this->setLastError( BagOStuff::ERR_UNEXPECTED );
334 $this->redisPool->handleError( $conn, $e );
338 * Send information about a single request to the debug log
339 * @param string $method
340 * @param string $key
341 * @param string $server
342 * @param bool $result
344 public function logRequest( $method, $key, $server, $result ) {
345 $this->debug( "$method $key on $server: " .
346 ( $result === false ? "failure" : "success" ) );