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
{
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 integer 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
72 protected function __construct( array $options ) {
73 if ( !extension_loaded( 'redis' ) ) {
74 throw new MWException( __CLASS__
. ' requires the phpredis extension: ' .
75 'https://github.com/nicolasff/phpredis' );
77 $this->connectTimeout
= $options['connectTimeout'];
78 $this->persistent
= $options['persistent'];
79 $this->password
= $options['password'];
80 if ( !isset( $options['serializer'] ) ||
$options['serializer'] === 'php' ) {
81 $this->serializer
= Redis
::SERIALIZER_PHP
;
82 } elseif ( $options['serializer'] === 'igbinary' ) {
83 $this->serializer
= Redis
::SERIALIZER_IGBINARY
;
84 } elseif ( $options['serializer'] === 'none' ) {
85 $this->serializer
= Redis
::SERIALIZER_NONE
;
87 throw new MWException( "Invalid serializer specified." );
92 * @param $options Array
95 protected static function applyDefaultConfig( array $options ) {
96 if ( !isset( $options['connectTimeout'] ) ) {
97 $options['connectTimeout'] = 1;
99 if ( !isset( $options['persistent'] ) ) {
100 $options['persistent'] = false;
102 if ( !isset( $options['password'] ) ) {
103 $options['password'] = null;
109 * @param $options Array
111 * - connectTimeout : The timeout for new connections, in seconds.
112 * Optional, default is 1 second.
113 * - persistent : Set this to true to allow connections to persist across
114 * multiple web requests. False by default.
115 * - password : The authentication password, will be sent to Redis in clear text.
116 * Optional, if it is unspecified, no AUTH command will be sent.
117 * - serializer : Set to "php", "igbinary", or "none". Default is "php".
118 * @return RedisConnectionPool
120 public static function singleton( array $options ) {
121 $options = self
::applyDefaultConfig( $options );
122 // Map the options to a unique hash...
123 ksort( $options ); // normalize to avoid pool fragmentation
124 $id = sha1( serialize( $options ) );
125 // Initialize the object at the hash as needed...
126 if ( !isset( self
::$instances[$id] ) ) {
127 self
::$instances[$id] = new self( $options );
128 wfDebug( "Creating a new " . __CLASS__
. " instance with id $id." );
130 return self
::$instances[$id];
134 * Get a connection to a redis server. Based on code in RedisBagOStuff.php.
136 * @param string $server A hostname/port combination or the absolute path of a UNIX socket.
137 * If a hostname is specified but no port, port 6379 will be used.
138 * @return RedisConnRef|bool Returns false on failure
139 * @throws MWException
141 public function getConnection( $server ) {
142 // Check the listing "dead" servers which have had a connection errors.
143 // Servers are marked dead for a limited period of time, to
144 // avoid excessive overhead from repeated connection timeouts.
145 if ( isset( $this->downServers
[$server] ) ) {
147 if ( $now > $this->downServers
[$server] ) {
149 unset( $this->downServers
[$server] );
152 wfDebug( "server $server is marked down for another " .
153 ( $this->downServers
[$server] - $now ) . " seconds, can't get connection" );
158 // Check if a connection is already free for use
159 if ( isset( $this->connections
[$server] ) ) {
160 foreach ( $this->connections
[$server] as &$connection ) {
161 if ( $connection['free'] ) {
162 $connection['free'] = false;
163 --$this->idlePoolSize
;
164 return new RedisConnRef( $this, $server, $connection['conn'] );
169 if ( substr( $server, 0, 1 ) === '/' ) {
170 // UNIX domain socket
171 // These are required by the redis extension to start with a slash, but
172 // we still need to set the port to a special value to make it work.
177 $hostPort = IP
::splitHostAndPort( $server );
179 throw new MWException( __CLASS__
. ": invalid configured server \"$server\"" );
181 list( $host, $port ) = $hostPort;
182 if ( $port === false ) {
189 if ( $this->persistent
) {
190 $result = $conn->pconnect( $host, $port, $this->connectTimeout
);
192 $result = $conn->connect( $host, $port, $this->connectTimeout
);
195 wfDebugLog( 'redis', "Could not connect to server $server" );
196 // Mark server down for some time to avoid further timeouts
197 $this->downServers
[$server] = time() + self
::SERVER_DOWN_TTL
;
200 if ( $this->password
!== null ) {
201 if ( !$conn->auth( $this->password
) ) {
202 wfDebugLog( 'redis', "Authentication error connecting to $server" );
205 } catch ( RedisException
$e ) {
206 $this->downServers
[$server] = time() + self
::SERVER_DOWN_TTL
;
207 wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
212 $conn->setOption( Redis
::OPT_SERIALIZER
, $this->serializer
);
213 $this->connections
[$server][] = array( 'conn' => $conn, 'free' => false );
214 return new RedisConnRef( $this, $server, $conn );
221 * Mark a connection to a server as free to return to the pool
223 * @param $server string
227 public function freeConnection( $server, Redis
$conn ) {
230 foreach ( $this->connections
[$server] as &$connection ) {
231 if ( $connection['conn'] === $conn && !$connection['free'] ) {
232 $connection['free'] = true;
233 ++
$this->idlePoolSize
;
238 $this->closeExcessIdleConections();
244 * Close any extra idle connections if there are more than the limit
248 protected function closeExcessIdleConections() {
249 if ( $this->idlePoolSize
<= count( $this->connections
) ) {
250 return; // nothing to do (no more connections than servers)
253 foreach ( $this->connections
as $server => &$serverConnections ) {
254 foreach ( $serverConnections as $key => &$connection ) {
255 if ( $connection['free'] ) {
256 unset( $serverConnections[$key] );
257 if ( --$this->idlePoolSize
<= count( $this->connections
) ) {
258 return; // done (no more connections than servers)
266 * The redis extension throws an exception in response to various read, write
267 * and protocol errors. Sometimes it also closes the connection, sometimes
268 * not. The safest response for us is to explicitly destroy the connection
269 * object and let it be reopened during the next request.
271 * @param $server string
272 * @param $cref RedisConnRef
273 * @param $e RedisException
276 public function handleException( $server, RedisConnRef
$cref, RedisException
$e ) {
277 wfDebugLog( 'redis', "Redis exception on server $server: " . $e->getMessage() . "\n" );
278 foreach ( $this->connections
[$server] as $key => $connection ) {
279 if ( $cref->isConnIdentical( $connection['conn'] ) ) {
280 $this->idlePoolSize
-= $connection['free'] ?
1 : 0;
281 unset( $this->connections
[$server][$key] );
289 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
295 /** @var RedisConnectionPool */
300 protected $server; // string
303 * @param $pool RedisConnectionPool
304 * @param $server string
307 public function __construct( RedisConnectionPool
$pool, $server, Redis
$conn ) {
309 $this->server
= $server;
313 public function __call( $name, $arguments ) {
314 return call_user_func_array( array( $this->conn
, $name ), $arguments );
318 * @param string $script
319 * @param array $params
320 * @param integer $numKeys
322 * @throws RedisException
324 public function luaEval( $script, array $params, $numKeys ) {
325 $sha1 = sha1( $script ); // 40 char hex
326 $conn = $this->conn
; // convenience
328 // Try to run the server-side cached copy of the script
329 $conn->clearLastError();
330 $res = $conn->evalSha( $sha1, $params, $numKeys );
331 // If the script is not in cache, use eval() to retry and cache it
332 if ( preg_match( '/^NOSCRIPT/', $conn->getLastError() ) ) {
333 $conn->clearLastError();
334 $res = $conn->eval( $script, $params, $numKeys );
335 wfDebugLog( 'redis', "Used eval() for Lua script $sha1." );
338 if ( $conn->getLastError() ) { // script bug?
339 wfDebugLog( 'redis', "Lua script error: " . $conn->getLastError() );
346 * @param RedisConnRef $conn
349 public function isConnIdentical( Redis
$conn ) {
350 return $this->conn
=== $conn;
353 function __destruct() {
354 $this->pool
->freeConnection( $this->server
, $this->conn
);