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"
58 * @param array $options
60 protected function __construct( array $options ) {
61 if ( !extension_loaded( 'redis' ) ) {
62 throw new MWException( __CLASS__
. ' requires the phpredis extension: ' .
63 'https://github.com/nicolasff/phpredis' );
65 $this->connectTimeout
= $options['connectTimeout'];
66 $this->persistent
= $options['persistent'];
67 $this->password
= $options['password'];
68 if ( !isset( $options['serializer'] ) ||
$options['serializer'] === 'php' ) {
69 $this->serializer
= Redis
::SERIALIZER_PHP
;
70 } elseif ( $options['serializer'] === 'igbinary' ) {
71 $this->serializer
= Redis
::SERIALIZER_IGBINARY
;
72 } elseif ( $options['serializer'] === 'none' ) {
73 $this->serializer
= Redis
::SERIALIZER_NONE
;
75 throw new MWException( "Invalid serializer specified." );
80 * @param $options Array
83 protected static function applyDefaultConfig( array $options ) {
84 if ( !isset( $options['connectTimeout'] ) ) {
85 $options['connectTimeout'] = 1;
87 if ( !isset( $options['persistent'] ) ) {
88 $options['persistent'] = false;
90 if ( !isset( $options['password'] ) ) {
91 $options['password'] = null;
97 * @param $options Array
99 * - connectTimeout : The timeout for new connections, in seconds.
100 * Optional, default is 1 second.
101 * - persistent : Set this to true to allow connections to persist across
102 * multiple web requests. False by default.
103 * - password : The authentication password, will be sent to Redis in clear text.
104 * Optional, if it is unspecified, no AUTH command will be sent.
105 * - serializer : Set to "php", "igbinary", or "none". Default is "php".
106 * @return RedisConnectionPool
108 public static function singleton( array $options ) {
109 $options = self
::applyDefaultConfig( $options );
110 // Map the options to a unique hash...
111 ksort( $options ); // normalize to avoid pool fragmentation
112 $id = sha1( serialize( $options ) );
113 // Initialize the object at the hash as needed...
114 if ( !isset( self
::$instances[$id] ) ) {
115 self
::$instances[$id] = new self( $options );
116 wfDebug( "Creating a new " . __CLASS__
. " instance with id $id." );
118 return self
::$instances[$id];
122 * Get a connection to a redis server. Based on code in RedisBagOStuff.php.
124 * @param string $server A hostname/port combination or the absolute path of a UNIX socket.
125 * If a hostname is specified but no port, port 6379 will be used.
126 * @return RedisConnRef|bool Returns false on failure
127 * @throws MWException
129 public function getConnection( $server ) {
130 // Check the listing "dead" servers which have had a connection errors.
131 // Servers are marked dead for a limited period of time, to
132 // avoid excessive overhead from repeated connection timeouts.
133 if ( isset( $this->downServers
[$server] ) ) {
135 if ( $now > $this->downServers
[$server] ) {
137 unset( $this->downServers
[$server] );
140 wfDebug( "server $server is marked down for another " .
141 ( $this->downServers
[$server] - $now ) . " seconds, can't get connection" );
146 // Check if a connection is already free for use
147 if ( isset( $this->connections
[$server] ) ) {
148 foreach ( $this->connections
[$server] as &$connection ) {
149 if ( $connection['free'] ) {
150 $connection['free'] = false;
151 --$this->idlePoolSize
;
152 return new RedisConnRef( $this, $server, $connection['conn'] );
157 if ( substr( $server, 0, 1 ) === '/' ) {
158 // UNIX domain socket
159 // These are required by the redis extension to start with a slash, but
160 // we still need to set the port to a special value to make it work.
165 $hostPort = IP
::splitHostAndPort( $server );
167 throw new MWException( __CLASS__
. ": invalid configured server \"$server\"" );
169 list( $host, $port ) = $hostPort;
170 if ( $port === false ) {
177 if ( $this->persistent
) {
178 $result = $conn->pconnect( $host, $port, $this->connectTimeout
);
180 $result = $conn->connect( $host, $port, $this->connectTimeout
);
183 wfDebugLog( 'redis', "Could not connect to server $server" );
184 // Mark server down for some time to avoid further timeouts
185 $this->downServers
[$server] = time() + self
::SERVER_DOWN_TTL
;
188 if ( $this->password
!== null ) {
189 if ( !$conn->auth( $this->password
) ) {
190 wfDebugLog( 'redis', "Authentication error connecting to $server" );
193 } catch ( RedisException
$e ) {
194 $this->downServers
[$server] = time() + self
::SERVER_DOWN_TTL
;
195 wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
200 $conn->setOption( Redis
::OPT_SERIALIZER
, $this->serializer
);
201 $this->connections
[$server][] = array( 'conn' => $conn, 'free' => false );
202 return new RedisConnRef( $this, $server, $conn );
209 * Mark a connection to a server as free to return to the pool
211 * @param $server string
215 public function freeConnection( $server, Redis
$conn ) {
218 foreach ( $this->connections
[$server] as &$connection ) {
219 if ( $connection['conn'] === $conn && !$connection['free'] ) {
220 $connection['free'] = true;
221 ++
$this->idlePoolSize
;
226 $this->closeExcessIdleConections();
232 * Close any extra idle connections if there are more than the limit
236 protected function closeExcessIdleConections() {
237 if ( $this->idlePoolSize
<= count( $this->connections
) ) {
238 return; // nothing to do (no more connections than servers)
241 foreach ( $this->connections
as $server => &$serverConnections ) {
242 foreach ( $serverConnections as $key => &$connection ) {
243 if ( $connection['free'] ) {
244 unset( $serverConnections[$key] );
245 if ( --$this->idlePoolSize
<= count( $this->connections
) ) {
246 return; // done (no more connections than servers)
254 * The redis extension throws an exception in response to various read, write
255 * and protocol errors. Sometimes it also closes the connection, sometimes
256 * not. The safest response for us is to explicitly destroy the connection
257 * object and let it be reopened during the next request.
259 * @param $server string
260 * @param $cref RedisConnRef
261 * @param $e RedisException
264 public function handleException( $server, RedisConnRef
$cref, RedisException
$e ) {
265 wfDebugLog( 'redis', "Redis exception on server $server: " . $e->getMessage() . "\n" );
266 foreach ( $this->connections
[$server] as $key => $connection ) {
267 if ( $cref->isConnIdentical( $connection['conn'] ) ) {
268 $this->idlePoolSize
-= $connection['free'] ?
1 : 0;
269 unset( $this->connections
[$server][$key] );
277 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
283 /** @var RedisConnectionPool */
288 protected $server; // string
291 * @param $pool RedisConnectionPool
292 * @param $server string
295 public function __construct( RedisConnectionPool
$pool, $server, Redis
$conn ) {
297 $this->server
= $server;
301 public function __call( $name, $arguments ) {
302 return call_user_func_array( array( $this->conn
, $name ), $arguments );
306 * @param string $script
307 * @param array $params
308 * @param integer $numKeys
310 * @throws RedisException
312 public function luaEval( $script, array $params, $numKeys ) {
313 $sha1 = sha1( $script ); // 40 char hex
314 $conn = $this->conn
; // convenience
316 // Try to run the server-side cached copy of the script
317 $conn->clearLastError();
318 $res = $conn->evalSha( $sha1, $params, $numKeys );
319 // If the script is not in cache, use eval() to retry and cache it
320 if ( preg_match( '/^NOSCRIPT/', $conn->getLastError() ) ) {
321 $conn->clearLastError();
322 $res = $conn->eval( $script, $params, $numKeys );
323 wfDebugLog( 'redis', "Used eval() for Lua script $sha1." );
326 if ( $conn->getLastError() ) { // script bug?
327 wfDebugLog( 'redis', "Lua script error: " . $conn->getLastError() );
334 * @param RedisConnRef $conn
337 public function isConnIdentical( Redis
$conn ) {
338 return $this->conn
=== $conn;
341 function __destruct() {
342 $this->pool
->freeConnection( $this->server
, $this->conn
);