Merge "Adding hlist module to mediawiki"
[lhc/web/wiklou.git] / includes / clientpool / RedisConnectionPool.php
1 <?php
2 /**
3 * Redis client connection pooling manager.
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 * @defgroup Redis Redis
22 * @author Aaron Schulz
23 */
24
25 /**
26 * Helper class to manage Redis connections.
27 *
28 * This can be used to get handle wrappers that free the handle when the wrapper
29 * leaves scope. The maximum number of free handles (connections) is configurable.
30 * This provides an easy way to cache connection handles that may also have state,
31 * such as a handle does between multi() and exec(), and without hoarding connections.
32 * The wrappers use PHP magic methods so that calling functions on them calls the
33 * function of the actual Redis object handle.
34 *
35 * @ingroup Redis
36 * @since 1.21
37 */
38 class RedisConnectionPool {
39 /**
40 * @name Pool settings.
41 * Settings there are shared for any connection made in this pool.
42 * See the singleton() method documentation for more details.
43 * @{
44 */
45 /** @var string Connection timeout in seconds */
46 protected $connectTimeout;
47 /** @var string Plaintext auth password */
48 protected $password;
49 /** @var bool Whether connections persist */
50 protected $persistent;
51 /** @var integer Serializer to use (Redis::SERIALIZER_*) */
52 protected $serializer;
53 /** @} */
54
55 /** @var integer Current idle pool size */
56 protected $idlePoolSize = 0;
57
58 /** @var Array (server name => ((connection info array),...) */
59 protected $connections = array();
60 /** @var Array (server name => UNIX timestamp) */
61 protected $downServers = array();
62
63 /** @var Array (pool ID => RedisConnectionPool) */
64 protected static $instances = array();
65
66 /** integer; seconds to cache servers as "down". */
67 const SERVER_DOWN_TTL = 30;
68
69 /**
70 * @param array $options
71 */
72 protected function __construct( array $options ) {
73 if ( !class_exists( 'Redis' ) ) {
74 throw new MWException( __CLASS__ . ' requires a Redis client library. ' .
75 'See https://www.mediawiki.org/wiki/Redis#Setup' );
76 }
77 $this->connectTimeout = $options['connectTimeout'];
78 $this->persistent = $options['persistent'];
79 $this->password = $options['password'];
80 if ( !isset( $options['serializer'] ) || $options['serializer'] === 'php' ) {
81 $this->serializer = Redis::SERIALIZER_PHP;
82 } elseif ( $options['serializer'] === 'igbinary' ) {
83 $this->serializer = Redis::SERIALIZER_IGBINARY;
84 } elseif ( $options['serializer'] === 'none' ) {
85 $this->serializer = Redis::SERIALIZER_NONE;
86 } else {
87 throw new MWException( "Invalid serializer specified." );
88 }
89 }
90
91 /**
92 * @param $options Array
93 * @return Array
94 */
95 protected static function applyDefaultConfig( array $options ) {
96 if ( !isset( $options['connectTimeout'] ) ) {
97 $options['connectTimeout'] = 1;
98 }
99 if ( !isset( $options['persistent'] ) ) {
100 $options['persistent'] = false;
101 }
102 if ( !isset( $options['password'] ) ) {
103 $options['password'] = null;
104 }
105 return $options;
106 }
107
108 /**
109 * @param $options Array
110 * $options include:
111 * - connectTimeout : The timeout for new connections, in seconds.
112 * Optional, default is 1 second.
113 * - persistent : Set this to true to allow connections to persist across
114 * multiple web requests. False by default.
115 * - password : The authentication password, will be sent to Redis in clear text.
116 * Optional, if it is unspecified, no AUTH command will be sent.
117 * - serializer : Set to "php", "igbinary", or "none". Default is "php".
118 * @return RedisConnectionPool
119 */
120 public static function singleton( array $options ) {
121 $options = self::applyDefaultConfig( $options );
122 // Map the options to a unique hash...
123 ksort( $options ); // normalize to avoid pool fragmentation
124 $id = sha1( serialize( $options ) );
125 // Initialize the object at the hash as needed...
126 if ( !isset( self::$instances[$id] ) ) {
127 self::$instances[$id] = new self( $options );
128 wfDebug( "Creating a new " . __CLASS__ . " instance with id $id." );
129 }
130 return self::$instances[$id];
131 }
132
133 /**
134 * Get a connection to a redis server. Based on code in RedisBagOStuff.php.
135 *
136 * @param string $server A hostname/port combination or the absolute path of a UNIX socket.
137 * If a hostname is specified but no port, port 6379 will be used.
138 * @return RedisConnRef|bool Returns false on failure
139 * @throws MWException
140 */
141 public function getConnection( $server ) {
142 // Check the listing "dead" servers which have had a connection errors.
143 // Servers are marked dead for a limited period of time, to
144 // avoid excessive overhead from repeated connection timeouts.
145 if ( isset( $this->downServers[$server] ) ) {
146 $now = time();
147 if ( $now > $this->downServers[$server] ) {
148 // Dead time expired
149 unset( $this->downServers[$server] );
150 } else {
151 // Server is dead
152 wfDebug( "server $server is marked down for another " .
153 ( $this->downServers[$server] - $now ) . " seconds, can't get connection" );
154 return false;
155 }
156 }
157
158 // Check if a connection is already free for use
159 if ( isset( $this->connections[$server] ) ) {
160 foreach ( $this->connections[$server] as &$connection ) {
161 if ( $connection['free'] ) {
162 $connection['free'] = false;
163 --$this->idlePoolSize;
164 return new RedisConnRef( $this, $server, $connection['conn'] );
165 }
166 }
167 }
168
169 if ( substr( $server, 0, 1 ) === '/' ) {
170 // UNIX domain socket
171 // These are required by the redis extension to start with a slash, but
172 // we still need to set the port to a special value to make it work.
173 $host = $server;
174 $port = 0;
175 } else {
176 // TCP connection
177 $hostPort = IP::splitHostAndPort( $server );
178 if ( !$hostPort ) {
179 throw new MWException( __CLASS__ . ": invalid configured server \"$server\"" );
180 }
181 list( $host, $port ) = $hostPort;
182 if ( $port === false ) {
183 $port = 6379;
184 }
185 }
186
187 $conn = new Redis();
188 try {
189 if ( $this->persistent ) {
190 $result = $conn->pconnect( $host, $port, $this->connectTimeout );
191 } else {
192 $result = $conn->connect( $host, $port, $this->connectTimeout );
193 }
194 if ( !$result ) {
195 wfDebugLog( 'redis', "Could not connect to server $server" );
196 // Mark server down for some time to avoid further timeouts
197 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
198 return false;
199 }
200 if ( $this->password !== null ) {
201 if ( !$conn->auth( $this->password ) ) {
202 wfDebugLog( 'redis', "Authentication error connecting to $server" );
203 }
204 }
205 } catch ( RedisException $e ) {
206 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
207 wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
208 return false;
209 }
210
211 if ( $conn ) {
212 $conn->setOption( Redis::OPT_SERIALIZER, $this->serializer );
213 $this->connections[$server][] = array( 'conn' => $conn, 'free' => false );
214 return new RedisConnRef( $this, $server, $conn );
215 } else {
216 return false;
217 }
218 }
219
220 /**
221 * Mark a connection to a server as free to return to the pool
222 *
223 * @param $server string
224 * @param $conn Redis
225 * @return boolean
226 */
227 public function freeConnection( $server, Redis $conn ) {
228 $found = false;
229
230 foreach ( $this->connections[$server] as &$connection ) {
231 if ( $connection['conn'] === $conn && !$connection['free'] ) {
232 $connection['free'] = true;
233 ++$this->idlePoolSize;
234 break;
235 }
236 }
237
238 $this->closeExcessIdleConections();
239
240 return $found;
241 }
242
243 /**
244 * Close any extra idle connections if there are more than the limit
245 *
246 * @return void
247 */
248 protected function closeExcessIdleConections() {
249 if ( $this->idlePoolSize <= count( $this->connections ) ) {
250 return; // nothing to do (no more connections than servers)
251 }
252
253 foreach ( $this->connections as $server => &$serverConnections ) {
254 foreach ( $serverConnections as $key => &$connection ) {
255 if ( $connection['free'] ) {
256 unset( $serverConnections[$key] );
257 if ( --$this->idlePoolSize <= count( $this->connections ) ) {
258 return; // done (no more connections than servers)
259 }
260 }
261 }
262 }
263 }
264
265 /**
266 * The redis extension throws an exception in response to various read, write
267 * and protocol errors. Sometimes it also closes the connection, sometimes
268 * not. The safest response for us is to explicitly destroy the connection
269 * object and let it be reopened during the next request.
270 *
271 * @param $server string
272 * @param $cref RedisConnRef
273 * @param $e RedisException
274 * @return void
275 */
276 public function handleException( $server, RedisConnRef $cref, RedisException $e ) {
277 wfDebugLog( 'redis', "Redis exception on server $server: " . $e->getMessage() . "\n" );
278 foreach ( $this->connections[$server] as $key => $connection ) {
279 if ( $cref->isConnIdentical( $connection['conn'] ) ) {
280 $this->idlePoolSize -= $connection['free'] ? 1 : 0;
281 unset( $this->connections[$server][$key] );
282 break;
283 }
284 }
285 }
286
287 /**
288 * Re-send an AUTH request to the redis server (useful after disconnects).
289 *
290 * This works around an upstream bug in phpredis. phpredis hides disconnects by transparently
291 * reconnecting, but it neglects to re-authenticate the new connection. To the user of the
292 * phpredis client API this manifests as a seemingly random tendency of connections to lose
293 * their authentication status.
294 *
295 * This method is for internal use only.
296 *
297 * @see https://github.com/nicolasff/phpredis/issues/403
298 *
299 * @param string $server
300 * @param Redis $conn
301 * @return bool Success
302 */
303 public function reauthenticateConnection( $server, Redis $conn ) {
304 if ( $this->password !== null ) {
305 if ( !$conn->auth( $this->password ) ) {
306 wfDebugLog( 'redis', "Authentication error connecting to $server" );
307 return false;
308 }
309 }
310 return true;
311 }
312 }
313
314 /**
315 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
316 *
317 * This class simply wraps the Redis class and can be used the same way
318 *
319 * @ingroup Redis
320 * @since 1.21
321 */
322 class RedisConnRef {
323 /** @var RedisConnectionPool */
324 protected $pool;
325 /** @var Redis */
326 protected $conn;
327
328 protected $server; // string
329 protected $lastError; // string
330
331 /**
332 * @param $pool RedisConnectionPool
333 * @param $server string
334 * @param $conn Redis
335 */
336 public function __construct( RedisConnectionPool $pool, $server, Redis $conn ) {
337 $this->pool = $pool;
338 $this->server = $server;
339 $this->conn = $conn;
340 }
341
342 /**
343 * @return string
344 * @since 1.23
345 */
346 public function getServer() {
347 return $this->server;
348 }
349
350 public function getLastError() {
351 return $this->lastError;
352 }
353
354 public function clearLastError() {
355 $this->lastError = null;
356 }
357
358 public function __call( $name, $arguments ) {
359 $conn = $this->conn; // convenience
360
361 $conn->clearLastError();
362 $res = call_user_func_array( array( $conn, $name ), $arguments );
363 if ( preg_match( '/^ERR operation not permitted\b/', $conn->getLastError() ) ) {
364 $this->pool->reauthenticateConnection( $this->server, $conn );
365 $conn->clearLastError();
366 $res = call_user_func_array( array( $conn, $name ), $arguments );
367 wfDebugLog( 'redis', "Used automatic re-authentication for method '$name'." );
368 }
369
370 $this->lastError = $conn->getLastError() ?: $this->lastError;
371
372 return $res;
373 }
374
375 /**
376 * @param string $script
377 * @param array $params
378 * @param integer $numKeys
379 * @return mixed
380 * @throws RedisException
381 */
382 public function luaEval( $script, array $params, $numKeys ) {
383 $sha1 = sha1( $script ); // 40 char hex
384 $conn = $this->conn; // convenience
385 $server = $this->server; // convenience
386
387 // Try to run the server-side cached copy of the script
388 $conn->clearLastError();
389 $res = $conn->evalSha( $sha1, $params, $numKeys );
390 // If we got a permission error reply that means that (a) we are not in
391 // multi()/pipeline() and (b) some connection problem likely occured. If
392 // the password the client gave was just wrong, an exception should have
393 // been thrown back in getConnection() previously.
394 if ( preg_match( '/^ERR operation not permitted\b/', $conn->getLastError() ) ) {
395 $this->pool->reauthenticateConnection( $server, $conn );
396 $conn->clearLastError();
397 $res = $conn->eval( $script, $params, $numKeys );
398 wfDebugLog( 'redis', "Used automatic re-authentication for Lua script $sha1." );
399 }
400 // If the script is not in cache, use eval() to retry and cache it
401 if ( preg_match( '/^NOSCRIPT/', $conn->getLastError() ) ) {
402 $conn->clearLastError();
403 $res = $conn->eval( $script, $params, $numKeys );
404 wfDebugLog( 'redis', "Used eval() for Lua script $sha1." );
405 }
406
407 if ( $conn->getLastError() ) { // script bug?
408 wfDebugLog( 'redis', "Lua script error on server $server: " . $conn->getLastError() );
409 }
410
411 $this->lastError = $conn->getLastError() ?: $this->lastError;
412
413 return $res;
414 }
415
416 /**
417 * @param RedisConnRef $conn
418 * @return bool
419 */
420 public function isConnIdentical( Redis $conn ) {
421 return $this->conn === $conn;
422 }
423
424 function __destruct() {
425 $this->pool->freeConnection( $this->server, $this->conn );
426 }
427 }