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 $serializer; // integer; the serializer to use (Redis::SERIALIZER_*)
45 protected $idlePoolSize = 0; // integer; current idle pool size
47 /** @var Array (server name => ((connection info array),...) */
48 protected $connections = array();
49 /** @var Array (server name => UNIX timestamp) */
50 protected $downServers = array();
53 protected static $instances = array(); // (pool ID => RedisConnectionPool)
55 const SERVER_DOWN_TTL
= 30; // integer; seconds to cache servers as "down"
59 * - connectTimeout : The timeout for new connections, in seconds.
60 * Optional, default is 1 second.
61 * - persistent : Set this to true to allow connections to persist across
62 * multiple web requests. False by default.
63 * - password : The authentication password, will be sent to Redis in clear text.
64 * Optional, if it is unspecified, no AUTH command will be sent.
65 * - serializer : Set to "php" or "igbinary". Default is "php".
66 * @param array $options
68 protected function __construct( array $options ) {
69 if ( !extension_loaded( 'redis' ) ) {
70 throw new MWException( __CLASS__
. ' requires the phpredis extension: ' .
71 'https://github.com/nicolasff/phpredis' );
73 $this->connectTimeout
= $options['connectTimeout'];
74 $this->persistent
= $options['persistent'];
75 $this->password
= $options['password'];
76 if ( !isset( $options['serializer'] ) ||
$options['serializer'] === 'php' ) {
77 $this->serializer
= Redis
::SERIALIZER_PHP
;
78 } elseif ( $options['serializer'] === 'igbinary' ) {
79 $this->serializer
= Redis
::SERIALIZER_IGBINARY
;
81 throw new MWException( "Invalid serializer specified." );
86 * @param $options Array
89 protected static function applyDefaultConfig( array $options ) {
90 if ( !isset( $options['connectTimeout'] ) ) {
91 $options['connectTimeout'] = 1;
93 if ( !isset( $options['persistent'] ) ) {
94 $options['persistent'] = false;
96 if ( !isset( $options['password'] ) ) {
97 $options['password'] = null;
103 * @param $options Array
104 * @return RedisConnectionPool
106 public static function singleton( array $options ) {
107 $options = self
::applyDefaultConfig( $options );
108 // Map the options to a unique hash...
109 ksort( $options ); // normalize to avoid pool fragmentation
110 $id = sha1( serialize( $options ) );
111 // Initialize the object at the hash as needed...
112 if ( !isset( self
::$instances[$id] ) ) {
113 self
::$instances[$id] = new self( $options );
114 wfDebug( "Creating a new " . __CLASS__
. " instance with id $id." );
116 return self
::$instances[$id];
120 * Get a connection to a redis server. Based on code in RedisBagOStuff.php.
122 * @param string $server A hostname/port combination or the absolute path of a UNIX socket.
123 * If a hostname is specified but no port, port 6379 will be used.
124 * @return RedisConnRef|bool Returns false on failure
125 * @throws MWException
127 public function getConnection( $server ) {
128 // Check the listing "dead" servers which have had a connection errors.
129 // Servers are marked dead for a limited period of time, to
130 // avoid excessive overhead from repeated connection timeouts.
131 if ( isset( $this->downServers
[$server] ) ) {
133 if ( $now > $this->downServers
[$server] ) {
135 unset( $this->downServers
[$server] );
138 wfDebug( "server $server is marked down for another " .
139 ( $this->downServers
[$server] - $now ) . " seconds, can't get connection" );
144 // Check if a connection is already free for use
145 if ( isset( $this->connections
[$server] ) ) {
146 foreach ( $this->connections
[$server] as &$connection ) {
147 if ( $connection['free'] ) {
148 $connection['free'] = false;
149 --$this->idlePoolSize
;
150 return new RedisConnRef( $this, $server, $connection['conn'] );
155 if ( substr( $server, 0, 1 ) === '/' ) {
156 // UNIX domain socket
157 // These are required by the redis extension to start with a slash, but
158 // we still need to set the port to a special value to make it work.
163 $hostPort = IP
::splitHostAndPort( $server );
165 throw new MWException( __CLASS__
.": invalid configured server \"$server\"" );
167 list( $host, $port ) = $hostPort;
168 if ( $port === false ) {
175 if ( $this->persistent
) {
176 $result = $conn->pconnect( $host, $port, $this->connectTimeout
);
178 $result = $conn->connect( $host, $port, $this->connectTimeout
);
181 wfDebugLog( 'redis', "Could not connect to server $server" );
182 // Mark server down for some time to avoid further timeouts
183 $this->downServers
[$server] = time() + self
::SERVER_DOWN_TTL
;
186 if ( $this->password
!== null ) {
187 if ( !$conn->auth( $this->password
) ) {
188 wfDebugLog( 'redis', "Authentication error connecting to $server" );
191 } catch ( RedisException
$e ) {
192 $this->downServers
[$server] = time() + self
::SERVER_DOWN_TTL
;
193 wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
198 $conn->setOption( Redis
::OPT_SERIALIZER
, $this->serializer
);
199 $this->connections
[$server][] = array( 'conn' => $conn, 'free' => false );
200 return new RedisConnRef( $this, $server, $conn );
207 * Mark a connection to a server as free to return to the pool
209 * @param $server string
213 public function freeConnection( $server, Redis
$conn ) {
216 foreach ( $this->connections
[$server] as &$connection ) {
217 if ( $connection['conn'] === $conn && !$connection['free'] ) {
218 $connection['free'] = true;
219 ++
$this->idlePoolSize
;
224 $this->closeExcessIdleConections();
230 * Close any extra idle connections if there are more than the limit
234 protected function closeExcessIdleConections() {
235 if ( $this->idlePoolSize
<= count( $this->connections
) ) {
236 return; // nothing to do (no more connections than servers)
239 foreach ( $this->connections
as $server => &$serverConnections ) {
240 foreach ( $serverConnections as $key => &$connection ) {
241 if ( $connection['free'] ) {
242 unset( $serverConnections[$key] );
243 if ( --$this->idlePoolSize
<= count( $this->connections
) ) {
244 return; // done (no more connections than servers)
252 * The redis extension throws an exception in response to various read, write
253 * and protocol errors. Sometimes it also closes the connection, sometimes
254 * not. The safest response for us is to explicitly destroy the connection
255 * object and let it be reopened during the next request.
257 * @param $server string
258 * @param $cref RedisConnRef
259 * @param $e RedisException
262 public function handleException( $server, RedisConnRef
$cref, RedisException
$e ) {
263 wfDebugLog( 'redis', "Redis exception on server $server: " . $e->getMessage() . "\n" );
264 foreach ( $this->connections
[$server] as $key => $connection ) {
265 if ( $cref->isConnIdentical( $connection['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 */
286 protected $server; // string
289 * @param $pool RedisConnectionPool
290 * @param $server string
293 public function __construct( RedisConnectionPool
$pool, $server, Redis
$conn ) {
295 $this->server
= $server;
299 public function __call( $name, $arguments ) {
300 return call_user_func_array( array( $this->conn
, $name ), $arguments );
303 public function isConnIdentical( Redis
$conn ) {
304 return $this->conn
=== $conn;
307 function __destruct() {
308 $this->pool
->freeConnection( $this->server
, $this->conn
);