3 * PhpRedis 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 using PhpRedis.
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
{
39 // Settings for all connections in this pool
40 protected $connectTimeout; // string; connection timeout
41 protected $persistent; // bool; whether connections persist
42 protected $password; // string; plaintext auth password
43 protected $poolSize; // integer; maximum number of idle connections
44 protected $serializer; // integer; the serializer to use (Redis::SERIALIZER_*)
46 protected $idlePoolSize = 0; // integer; current idle pool size
48 /** @var Array (server name => ((connection info array),...) */
49 protected $connections = array();
50 /** @var Array (server name => UNIX timestamp) */
51 protected $downServers = array();
54 protected static $instances = array(); // (pool ID => RedisConnectionPool)
56 const SERVER_DOWN_TTL
= 30; // integer; seconds to cache servers as "down"
60 * - connectTimeout : The timeout for new connections, in seconds.
61 * Optional, default is 1 second.
62 * - persistent : Set this to true to allow connections to persist across
63 * multiple web requests. False by default.
64 * - poolSize : Maximim number of idle connections. Default is 5.
65 * - password : The authentication password, will be sent to Redis in clear text.
66 * Optional, if it is unspecified, no AUTH command will be sent.
67 * - serializer : Set to "php" or "igbinary". Default is "php".
68 * @param array $options
70 protected function __construct( array $options ) {
71 if ( !extension_loaded( 'redis' ) ) {
72 throw new MWException( __CLASS__
. ' requires the phpredis extension: ' .
73 'https://github.com/nicolasff/phpredis' );
75 $this->connectTimeout
= isset( $options['connectTimeout'] )
76 ?
$options['connectTimeout']
78 $this->persistent
= isset( $options['persistent'] )
79 ?
$options['persistent']
81 $this->password
= isset( $options['password'] )
82 ?
$options['password']
84 $this->poolSize
= isset( $options['poolSize'] )
85 ?
$options['poolSize']
87 if ( !isset( $options['serializer'] ) ||
$options['serializer'] === 'php' ) {
88 $this->serializer
= Redis
::SERIALIZER_PHP
;
89 } elseif ( $options['serializer'] === 'igbinary' ) {
90 $this->serializer
= Redis
::SERIALIZER_IGBINARY
;
92 throw new MWException( "Invalid serializer specified." );
97 * @param $options Array
98 * @return RedisConnectionPool
100 public static function singleton( array $options ) {
101 // Map the options to a unique hash...
102 $poolOptions = $options;
103 unset( $poolOptions['poolSize'] ); // avoid pool fragmentation
104 ksort( $poolOptions ); // normalize to avoid pool fragmentation
105 $id = sha1( serialize( $poolOptions ) );
106 // Initialize the object at the hash as needed...
107 if ( !isset( self
::$instances[$id] ) ) {
108 self
::$instances[$id] = new self( $options );
109 wfDebug( "Creating a new " . __CLASS__
. " instance with id $id." );
111 // Simply grow the pool size if the existing one is too small
112 $psize = isset( $options['poolSize'] ) ?
$options['poolSize'] : 1; // size requested
113 self
::$instances[$id]->poolSize
= max( $psize, self
::$instances[$id]->poolSize
);
115 return self
::$instances[$id];
119 * Get a connection to a redis server. Based on code in RedisBagOStuff.php.
121 * @param $server string A hostname/port combination or the absolute path of a UNIX socket.
122 * If a hostname is specified but no port, port 6379 will be used.
123 * @return RedisConnRef|bool Returns false on failure
124 * @throws MWException
126 public function getConnection( $server ) {
127 // Check the listing "dead" servers which have had a connection errors.
128 // Servers are marked dead for a limited period of time, to
129 // avoid excessive overhead from repeated connection timeouts.
130 if ( isset( $this->downServers
[$server] ) ) {
132 if ( $now > $this->downServers
[$server] ) {
134 unset( $this->downServers
[$server] );
137 wfDebug( "server $server is marked down for another " .
138 ( $this->downServers
[$server] - $now ) . " seconds, can't get connection" );
143 // Check if a connection is already free for use
144 if ( isset( $this->connections
[$server] ) ) {
145 foreach ( $this->connections
[$server] as &$connection ) {
146 if ( $connection['free'] ) {
147 $connection['free'] = false;
148 --$this->idlePoolSize
;
149 return new RedisConnRef( $this, $server, $connection['conn'] );
154 if ( substr( $server, 0, 1 ) === '/' ) {
155 // UNIX domain socket
156 // These are required by the redis extension to start with a slash, but
157 // we still need to set the port to a special value to make it work.
162 $hostPort = IP
::splitHostAndPort( $server );
164 throw new MWException( __CLASS__
.": invalid configured server \"$server\"" );
166 list( $host, $port ) = $hostPort;
167 if ( $port === false ) {
174 if ( $this->persistent
) {
175 $result = $conn->pconnect( $host, $port, $this->connectTimeout
);
177 $result = $conn->connect( $host, $port, $this->connectTimeout
);
180 wfDebugLog( 'redis', "Could not connect to server $server" );
181 // Mark server down for some time to avoid further timeouts
182 $this->downServers
[$server] = time() + self
::SERVER_DOWN_TTL
;
185 if ( $this->password
!== null ) {
186 if ( !$conn->auth( $this->password
) ) {
187 wfDebugLog( 'redis', "Authentication error connecting to $server" );
190 } catch ( RedisException
$e ) {
191 $this->downServers
[$server] = time() + self
::SERVER_DOWN_TTL
;
192 wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
197 $conn->setOption( Redis
::OPT_SERIALIZER
, $this->serializer
);
198 $this->connections
[$server][] = array( 'conn' => $conn, 'free' => false );
199 return new RedisConnRef( $this, $server, $conn );
206 * Mark a connection to a server as free to return to the pool
208 * @param $server string
212 public function freeConnection( $server, Redis
$conn ) {
215 foreach ( $this->connections
[$server] as &$connection ) {
216 if ( $connection['conn'] === $conn && !$connection['free'] ) {
217 $connection['free'] = true;
218 ++
$this->idlePoolSize
;
223 $this->closeExcessIdleConections();
229 * Close any extra idle connections if there are more than the limit
233 protected function closeExcessIdleConections() {
234 if ( $this->idlePoolSize
<= $this->poolSize
) {
235 return; // nothing to do
238 foreach ( $this->connections
as $server => &$serverConnections ) {
239 foreach ( $serverConnections as $key => &$connection ) {
240 if ( $connection['free'] ) {
241 unset( $serverConnections[$key] );
242 if ( --$this->idlePoolSize
<= $this->poolSize
) {
251 * The redis extension throws an exception in response to various read, write
252 * and protocol errors. Sometimes it also closes the connection, sometimes
253 * not. The safest response for us is to explicitly destroy the connection
254 * object and let it be reopened during the next request.
256 * @param $server string
257 * @param $conn RedisConnRef
258 * @param $e RedisException
261 public function handleException( $server, RedisConnRef
$conn, RedisException
$e ) {
263 "Redis exception on server $server: " . $e->getMessage() . "\n" );
264 foreach ( $this->connections
[$server] as $key => $connection ) {
265 if ( $connection['conn'] === $conn ) {
266 $this->idlePoolSize
-= $connection['free'] ?
1 : 0;
267 unset( $this->connections
[$server][$key] );
275 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
281 /** @var RedisConnectionPool */
284 protected $server; // string
290 * @param $pool RedisConnectionPool
291 * @param $server string
294 public function __construct( RedisConnectionPool
$pool, $server, Redis
$conn ) {
296 $this->server
= $server;
300 public function __call( $name, $arguments ) {
301 return call_user_func_array( array( $this->conn
, $name ), $arguments );
304 function __destruct() {
305 $this->pool
->freeConnection( $this->server
, $this->conn
);