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 ksort( $options ); // normalize
102 $id = sha1( serialize( $options ) );
103 if ( !isset( self
::$instances[$id] ) ) {
104 self
::$instances[$id] = new self( $options );
105 wfDebug( "Creating a new " . __CLASS__
. " instance with id $id." );
107 return self
::$instances[$id];
111 * Get a connection to a redis server. Based on code in RedisBagOStuff.php.
113 * @param $server string A hostname/port combination or the absolute path of a UNIX socket.
114 * If a hostname is specified but no port, port 6379 will be used.
115 * @return RedisConnRef|bool Returns false on failure
116 * @throws MWException
118 public function getConnection( $server ) {
119 // Check the listing "dead" servers which have had a connection errors.
120 // Servers are marked dead for a limited period of time, to
121 // avoid excessive overhead from repeated connection timeouts.
122 if ( isset( $this->downServers
[$server] ) ) {
124 if ( $now > $this->downServers
[$server] ) {
126 unset( $this->downServers
[$server] );
129 wfDebug( "server $server is marked down for another " .
130 ( $this->downServers
[$server] - $now ) . " seconds, can't get connection" );
135 // Check if a connection is already free for use
136 if ( isset( $this->connections
[$server] ) ) {
137 foreach ( $this->connections
[$server] as &$connection ) {
138 if ( $connection['free'] ) {
139 $connection['free'] = false;
140 --$this->idlePoolSize
;
141 return new RedisConnRef( $this, $server, $connection['conn'] );
146 if ( substr( $server, 0, 1 ) === '/' ) {
147 // UNIX domain socket
148 // These are required by the redis extension to start with a slash, but
149 // we still need to set the port to a special value to make it work.
154 $hostPort = IP
::splitHostAndPort( $server );
156 throw new MWException( __CLASS__
.": invalid configured server \"$server\"" );
158 list( $host, $port ) = $hostPort;
159 if ( $port === false ) {
166 if ( $this->persistent
) {
167 $result = $conn->pconnect( $host, $port, $this->connectTimeout
);
169 $result = $conn->connect( $host, $port, $this->connectTimeout
);
172 wfDebugLog( 'redis', "Could not connect to server $server" );
173 // Mark server down for some time to avoid further timeouts
174 $this->downServers
[$server] = time() + self
::SERVER_DOWN_TTL
;
177 if ( $this->password
!== null ) {
178 if ( !$conn->auth( $this->password
) ) {
179 wfDebugLog( 'redis', "Authentication error connecting to $server" );
182 } catch ( RedisException
$e ) {
183 $this->downServers
[$server] = time() + self
::SERVER_DOWN_TTL
;
184 wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
189 $conn->setOption( Redis
::OPT_SERIALIZER
, $this->serializer
);
190 $this->connections
[$server][] = array( 'conn' => $conn, 'free' => false );
191 return new RedisConnRef( $this, $server, $conn );
198 * Mark a connection to a server as free to return to the pool
200 * @param $server string
204 public function freeConnection( $server, Redis
$conn ) {
207 foreach ( $this->connections
[$server] as &$connection ) {
208 if ( $connection['conn'] === $conn && !$connection['free'] ) {
209 $connection['free'] = true;
210 ++
$this->idlePoolSize
;
215 $this->closeExcessIdleConections();
221 * Close any extra idle connections if there are more than the limit
225 protected function closeExcessIdleConections() {
226 if ( $this->idlePoolSize
<= $this->poolSize
) {
227 return; // nothing to do
230 foreach ( $this->connections
as $server => &$serverConnections ) {
231 foreach ( $serverConnections as $key => &$connection ) {
232 if ( $connection['free'] ) {
233 unset( $serverConnections[$key] );
234 if ( --$this->idlePoolSize
<= $this->poolSize
) {
243 * The redis extension throws an exception in response to various read, write
244 * and protocol errors. Sometimes it also closes the connection, sometimes
245 * not. The safest response for us is to explicitly destroy the connection
246 * object and let it be reopened during the next request.
248 * @param $server string
249 * @param $conn RedisConnRef
250 * @param $e RedisException
253 public function handleException( $server, RedisConnRef
$conn, RedisException
$e ) {
255 "Redis exception on server $server: " . $e->getMessage() . "\n" );
256 foreach ( $this->connections
[$server] as $key => $connection ) {
257 if ( $connection['conn'] === $conn ) {
258 $this->idlePoolSize
-= $connection['free'] ?
1 : 0;
259 unset( $this->connections
[$server][$key] );
267 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
273 /** @var RedisConnectionPool */
276 protected $server; // string
282 * @param $pool RedisConnectionPool
283 * @param $server string
286 public function __construct( RedisConnectionPool
$pool, $server, Redis
$conn ) {
288 $this->server
= $server;
292 public function __call( $name, $arguments ) {
293 return call_user_func_array( array( $this->conn
, $name ), $arguments );
296 function __destruct() {
297 $this->pool
->freeConnection( $this->server
, $this->conn
);