3 * Redis client connection pooling manager.
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
21 * @defgroup Redis Redis
22 * @author Aaron Schulz
26 * Helper class to manage Redis connections.
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.
38 class RedisConnectionPool
{
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.
45 /** @var string Connection timeout in seconds */
46 protected $connectTimeout;
47 /** @var string Plaintext auth password */
49 /** @var bool Whether connections persist */
50 protected $persistent;
51 /** @var integer Serializer to use (Redis::SERIALIZER_*) */
52 protected $serializer;
55 /** @var int Current idle pool size */
56 protected $idlePoolSize = 0;
58 /** @var array (server name => ((connection info array),...) */
59 protected $connections = array();
60 /** @var array (server name => UNIX timestamp) */
61 protected $downServers = array();
63 /** @var array (pool ID => RedisConnectionPool) */
64 protected static $instances = array();
66 /** integer; seconds to cache servers as "down". */
67 const SERVER_DOWN_TTL
= 30;
70 * @param array $options
73 protected function __construct( array $options ) {
74 if ( !class_exists( 'Redis' ) ) {
75 throw new MWException( __CLASS__
. ' requires a Redis client library. ' .
76 'See https://www.mediawiki.org/wiki/Redis#Setup' );
78 $this->connectTimeout
= $options['connectTimeout'];
79 $this->persistent
= $options['persistent'];
80 $this->password
= $options['password'];
81 if ( !isset( $options['serializer'] ) ||
$options['serializer'] === 'php' ) {
82 $this->serializer
= Redis
::SERIALIZER_PHP
;
83 } elseif ( $options['serializer'] === 'igbinary' ) {
84 $this->serializer
= Redis
::SERIALIZER_IGBINARY
;
85 } elseif ( $options['serializer'] === 'none' ) {
86 $this->serializer
= Redis
::SERIALIZER_NONE
;
88 throw new MWException( "Invalid serializer specified." );
93 * @param array $options
96 protected static function applyDefaultConfig( array $options ) {
97 if ( !isset( $options['connectTimeout'] ) ) {
98 $options['connectTimeout'] = 1;
100 if ( !isset( $options['persistent'] ) ) {
101 $options['persistent'] = false;
103 if ( !isset( $options['password'] ) ) {
104 $options['password'] = null;
111 * @param array $options
113 * - connectTimeout : The timeout for new connections, in seconds.
114 * Optional, default is 1 second.
115 * - persistent : Set this to true to allow connections to persist across
116 * multiple web requests. False by default.
117 * - password : The authentication password, will be sent to Redis in clear text.
118 * Optional, if it is unspecified, no AUTH command will be sent.
119 * - serializer : Set to "php", "igbinary", or "none". Default is "php".
120 * @return RedisConnectionPool
122 public static function singleton( array $options ) {
123 $options = self
::applyDefaultConfig( $options );
124 // Map the options to a unique hash...
125 ksort( $options ); // normalize to avoid pool fragmentation
126 $id = sha1( serialize( $options ) );
127 // Initialize the object at the hash as needed...
128 if ( !isset( self
::$instances[$id] ) ) {
129 self
::$instances[$id] = new self( $options );
130 wfDebug( "Creating a new " . __CLASS__
. " instance with id $id." );
133 return self
::$instances[$id];
137 * Get a connection to a redis server. Based on code in RedisBagOStuff.php.
139 * @param string $server A hostname/port combination or the absolute path of a UNIX socket.
140 * If a hostname is specified but no port, port 6379 will be used.
141 * @return RedisConnRef|bool Returns false on failure
142 * @throws MWException
144 public function getConnection( $server ) {
145 // Check the listing "dead" servers which have had a connection errors.
146 // Servers are marked dead for a limited period of time, to
147 // avoid excessive overhead from repeated connection timeouts.
148 if ( isset( $this->downServers
[$server] ) ) {
150 if ( $now > $this->downServers
[$server] ) {
152 unset( $this->downServers
[$server] );
155 wfDebug( "server $server is marked down for another " .
156 ( $this->downServers
[$server] - $now ) . " seconds, can't get connection" );
162 // Check if a connection is already free for use
163 if ( isset( $this->connections
[$server] ) ) {
164 foreach ( $this->connections
[$server] as &$connection ) {
165 if ( $connection['free'] ) {
166 $connection['free'] = false;
167 --$this->idlePoolSize
;
169 return new RedisConnRef( $this, $server, $connection['conn'] );
174 if ( substr( $server, 0, 1 ) === '/' ) {
175 // UNIX domain socket
176 // These are required by the redis extension to start with a slash, but
177 // we still need to set the port to a special value to make it work.
182 $hostPort = IP
::splitHostAndPort( $server );
184 throw new MWException( __CLASS__
. ": invalid configured server \"$server\"" );
186 list( $host, $port ) = $hostPort;
187 if ( $port === false ) {
194 if ( $this->persistent
) {
195 $result = $conn->pconnect( $host, $port, $this->connectTimeout
);
197 $result = $conn->connect( $host, $port, $this->connectTimeout
);
200 wfDebugLog( 'redis', "Could not connect to server $server" );
201 // Mark server down for some time to avoid further timeouts
202 $this->downServers
[$server] = time() + self
::SERVER_DOWN_TTL
;
206 if ( $this->password
!== null ) {
207 if ( !$conn->auth( $this->password
) ) {
208 wfDebugLog( 'redis', "Authentication error connecting to $server" );
211 } catch ( RedisException
$e ) {
212 $this->downServers
[$server] = time() + self
::SERVER_DOWN_TTL
;
213 wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
219 $conn->setOption( Redis
::OPT_SERIALIZER
, $this->serializer
);
220 $this->connections
[$server][] = array( 'conn' => $conn, 'free' => false );
222 return new RedisConnRef( $this, $server, $conn );
229 * Mark a connection to a server as free to return to the pool
231 * @param string $server
235 public function freeConnection( $server, Redis
$conn ) {
238 foreach ( $this->connections
[$server] as &$connection ) {
239 if ( $connection['conn'] === $conn && !$connection['free'] ) {
240 $connection['free'] = true;
241 ++
$this->idlePoolSize
;
246 $this->closeExcessIdleConections();
252 * Close any extra idle connections if there are more than the limit
254 protected function closeExcessIdleConections() {
255 if ( $this->idlePoolSize
<= count( $this->connections
) ) {
256 return; // nothing to do (no more connections than servers)
259 foreach ( $this->connections
as &$serverConnections ) {
260 foreach ( $serverConnections as $key => &$connection ) {
261 if ( $connection['free'] ) {
262 unset( $serverConnections[$key] );
263 if ( --$this->idlePoolSize
<= count( $this->connections
) ) {
264 return; // done (no more connections than servers)
272 * The redis extension throws an exception in response to various read, write
273 * and protocol errors. Sometimes it also closes the connection, sometimes
274 * not. The safest response for us is to explicitly destroy the connection
275 * object and let it be reopened during the next request.
277 * @param string $server
278 * @param RedisConnRef $cref
279 * @param RedisException $e
281 public function handleException( $server, RedisConnRef
$cref, RedisException
$e ) {
282 wfDebugLog( 'redis', "Redis exception on server $server: " . $e->getMessage() . "\n" );
283 foreach ( $this->connections
[$server] as $key => $connection ) {
284 if ( $cref->isConnIdentical( $connection['conn'] ) ) {
285 $this->idlePoolSize
-= $connection['free'] ?
1 : 0;
286 unset( $this->connections
[$server][$key] );
293 * Re-send an AUTH request to the redis server (useful after disconnects).
295 * This works around an upstream bug in phpredis. phpredis hides disconnects by transparently
296 * reconnecting, but it neglects to re-authenticate the new connection. To the user of the
297 * phpredis client API this manifests as a seemingly random tendency of connections to lose
298 * their authentication status.
300 * This method is for internal use only.
302 * @see https://github.com/nicolasff/phpredis/issues/403
304 * @param string $server
306 * @return bool Success
308 public function reauthenticateConnection( $server, Redis
$conn ) {
309 if ( $this->password
!== null ) {
310 if ( !$conn->auth( $this->password
) ) {
311 wfDebugLog( 'redis', "Authentication error connecting to $server" );
321 * Make sure connections are closed for sanity
323 function __destruct() {
324 foreach ( $this->connections
as $server => &$serverConnections ) {
325 foreach ( $serverConnections as $key => &$connection ) {
326 $connection['conn']->close();
333 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
335 * This class simply wraps the Redis class and can be used the same way
341 /** @var RedisConnectionPool */
346 protected $server; // string
347 protected $lastError; // string
350 * @param RedisConnectionPool $pool
351 * @param string $server
354 public function __construct( RedisConnectionPool
$pool, $server, Redis
$conn ) {
356 $this->server
= $server;
364 public function getServer() {
365 return $this->server
;
368 public function getLastError() {
369 return $this->lastError
;
372 public function clearLastError() {
373 $this->lastError
= null;
376 public function __call( $name, $arguments ) {
377 $conn = $this->conn
; // convenience
379 $conn->clearLastError();
380 $res = call_user_func_array( array( $conn, $name ), $arguments );
381 if ( preg_match( '/^ERR operation not permitted\b/', $conn->getLastError() ) ) {
382 $this->pool
->reauthenticateConnection( $this->server
, $conn );
383 $conn->clearLastError();
384 $res = call_user_func_array( array( $conn, $name ), $arguments );
385 wfDebugLog( 'redis', "Used automatic re-authentication for method '$name'." );
388 $this->lastError
= $conn->getLastError() ?
: $this->lastError
;
394 * @param string $script
395 * @param array $params
396 * @param integer $numKeys
398 * @throws RedisException
400 public function luaEval( $script, array $params, $numKeys ) {
401 $sha1 = sha1( $script ); // 40 char hex
402 $conn = $this->conn
; // convenience
403 $server = $this->server
; // convenience
405 // Try to run the server-side cached copy of the script
406 $conn->clearLastError();
407 $res = $conn->evalSha( $sha1, $params, $numKeys );
408 // If we got a permission error reply that means that (a) we are not in
409 // multi()/pipeline() and (b) some connection problem likely occured. If
410 // the password the client gave was just wrong, an exception should have
411 // been thrown back in getConnection() previously.
412 if ( preg_match( '/^ERR operation not permitted\b/', $conn->getLastError() ) ) {
413 $this->pool
->reauthenticateConnection( $server, $conn );
414 $conn->clearLastError();
415 $res = $conn->eval( $script, $params, $numKeys );
416 wfDebugLog( 'redis', "Used automatic re-authentication for Lua script $sha1." );
418 // If the script is not in cache, use eval() to retry and cache it
419 if ( preg_match( '/^NOSCRIPT/', $conn->getLastError() ) ) {
420 $conn->clearLastError();
421 $res = $conn->eval( $script, $params, $numKeys );
422 wfDebugLog( 'redis', "Used eval() for Lua script $sha1." );
425 if ( $conn->getLastError() ) { // script bug?
426 wfDebugLog( 'redis', "Lua script error on server $server: " . $conn->getLastError() );
429 $this->lastError
= $conn->getLastError() ?
: $this->lastError
;
438 public function isConnIdentical( Redis
$conn ) {
439 return $this->conn
=== $conn;
442 function __destruct() {
443 $this->pool
->freeConnection( $this->server
, $this->conn
);