Resolve config defaults in RedisConnectionPool in the singleton().
[mediawiki.git] / includes / clientpool / RedisConnectionPool.php
blobe81bc5debd7de1408a1ead172c437e3ddea2b986
1 <?php
2 /**
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
20 * @file
21 * @defgroup Redis Redis
22 * @author Aaron Schulz
25 /**
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.
35 * @ingroup Redis
36 * @since 1.21
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();
53 /** @var Array */
54 protected static $instances = array(); // (pool ID => RedisConnectionPool)
56 const SERVER_DOWN_TTL = 30; // integer; seconds to cache servers as "down"
58 /**
59 * $options include:
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 = $options['connectTimeout'];
76 $this->persistent = $options['persistent'];
77 $this->password = $options['password'];
78 $this->poolSize = $options['poolSize'];
79 if ( !isset( $options['serializer'] ) || $options['serializer'] === 'php' ) {
80 $this->serializer = Redis::SERIALIZER_PHP;
81 } elseif ( $options['serializer'] === 'igbinary' ) {
82 $this->serializer = Redis::SERIALIZER_IGBINARY;
83 } else {
84 throw new MWException( "Invalid serializer specified." );
88 /**
89 * @param $options Array
90 * @return Array
92 protected static function applyDefaultConfig( array $options ) {
93 if ( !isset( $options['connectTimeout'] ) ) {
94 $options['connectTimeout'] = 1;
96 if ( !isset( $options['persistent'] ) ) {
97 $options['persistent'] = false;
99 if ( !isset( $options['password'] ) ) {
100 $options['password'] = '';
102 if ( !isset( $options['poolSize'] ) ) {
103 $options['poolSize'] = 1;
105 return $options;
109 * @param $options Array
110 * @return RedisConnectionPool
112 public static function singleton( array $options ) {
113 $options = self::applyDefaultConfig( $options );
114 // Map the options to a unique hash...
115 $poolOptions = $options;
116 unset( $poolOptions['poolSize'] ); // avoid pool fragmentation
117 ksort( $poolOptions ); // normalize to avoid pool fragmentation
118 $id = sha1( serialize( $poolOptions ) );
119 // Initialize the object at the hash as needed...
120 if ( !isset( self::$instances[$id] ) ) {
121 self::$instances[$id] = new self( $options );
122 wfDebug( "Creating a new " . __CLASS__ . " instance with id $id." );
124 // Simply grow the pool size if the existing one is too small
125 $psize = $options['poolSize']; // size requested
126 self::$instances[$id]->poolSize = max( $psize, self::$instances[$id]->poolSize );
128 return self::$instances[$id];
132 * Get a connection to a redis server. Based on code in RedisBagOStuff.php.
134 * @param $server string A hostname/port combination or the absolute path of a UNIX socket.
135 * If a hostname is specified but no port, port 6379 will be used.
136 * @return RedisConnRef|bool Returns false on failure
137 * @throws MWException
139 public function getConnection( $server ) {
140 // Check the listing "dead" servers which have had a connection errors.
141 // Servers are marked dead for a limited period of time, to
142 // avoid excessive overhead from repeated connection timeouts.
143 if ( isset( $this->downServers[$server] ) ) {
144 $now = time();
145 if ( $now > $this->downServers[$server] ) {
146 // Dead time expired
147 unset( $this->downServers[$server] );
148 } else {
149 // Server is dead
150 wfDebug( "server $server is marked down for another " .
151 ( $this->downServers[$server] - $now ) . " seconds, can't get connection" );
152 return false;
156 // Check if a connection is already free for use
157 if ( isset( $this->connections[$server] ) ) {
158 foreach ( $this->connections[$server] as &$connection ) {
159 if ( $connection['free'] ) {
160 $connection['free'] = false;
161 --$this->idlePoolSize;
162 return new RedisConnRef( $this, $server, $connection['conn'] );
167 if ( substr( $server, 0, 1 ) === '/' ) {
168 // UNIX domain socket
169 // These are required by the redis extension to start with a slash, but
170 // we still need to set the port to a special value to make it work.
171 $host = $server;
172 $port = 0;
173 } else {
174 // TCP connection
175 $hostPort = IP::splitHostAndPort( $server );
176 if ( !$hostPort ) {
177 throw new MWException( __CLASS__.": invalid configured server \"$server\"" );
179 list( $host, $port ) = $hostPort;
180 if ( $port === false ) {
181 $port = 6379;
185 $conn = new Redis();
186 try {
187 if ( $this->persistent ) {
188 $result = $conn->pconnect( $host, $port, $this->connectTimeout );
189 } else {
190 $result = $conn->connect( $host, $port, $this->connectTimeout );
192 if ( !$result ) {
193 wfDebugLog( 'redis', "Could not connect to server $server" );
194 // Mark server down for some time to avoid further timeouts
195 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
196 return false;
198 if ( $this->password !== null ) {
199 if ( !$conn->auth( $this->password ) ) {
200 wfDebugLog( 'redis', "Authentication error connecting to $server" );
203 } catch ( RedisException $e ) {
204 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
205 wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
206 return false;
209 if ( $conn ) {
210 $conn->setOption( Redis::OPT_SERIALIZER, $this->serializer );
211 $this->connections[$server][] = array( 'conn' => $conn, 'free' => false );
212 return new RedisConnRef( $this, $server, $conn );
213 } else {
214 return false;
219 * Mark a connection to a server as free to return to the pool
221 * @param $server string
222 * @param $conn Redis
223 * @return boolean
225 public function freeConnection( $server, Redis $conn ) {
226 $found = false;
228 foreach ( $this->connections[$server] as &$connection ) {
229 if ( $connection['conn'] === $conn && !$connection['free'] ) {
230 $connection['free'] = true;
231 ++$this->idlePoolSize;
232 break;
236 $this->closeExcessIdleConections();
238 return $found;
242 * Close any extra idle connections if there are more than the limit
244 * @return void
246 protected function closeExcessIdleConections() {
247 if ( $this->idlePoolSize <= $this->poolSize ) {
248 return; // nothing to do
251 foreach ( $this->connections as $server => &$serverConnections ) {
252 foreach ( $serverConnections as $key => &$connection ) {
253 if ( $connection['free'] ) {
254 unset( $serverConnections[$key] );
255 if ( --$this->idlePoolSize <= $this->poolSize ) {
256 return; // done
264 * The redis extension throws an exception in response to various read, write
265 * and protocol errors. Sometimes it also closes the connection, sometimes
266 * not. The safest response for us is to explicitly destroy the connection
267 * object and let it be reopened during the next request.
269 * @param $server string
270 * @param $conn RedisConnRef
271 * @param $e RedisException
272 * @return void
274 public function handleException( $server, RedisConnRef $conn, RedisException $e ) {
275 wfDebugLog( 'redis',
276 "Redis exception on server $server: " . $e->getMessage() . "\n" );
277 foreach ( $this->connections[$server] as $key => $connection ) {
278 if ( $connection['conn'] === $conn ) {
279 $this->idlePoolSize -= $connection['free'] ? 1 : 0;
280 unset( $this->connections[$server][$key] );
281 break;
288 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
290 * @ingroup Redis
291 * @since 1.21
293 class RedisConnRef {
294 /** @var RedisConnectionPool */
295 protected $pool;
297 protected $server; // string
299 /** @var Redis */
300 protected $conn;
303 * @param $pool RedisConnectionPool
304 * @param $server string
305 * @param $conn Redis
307 public function __construct( RedisConnectionPool $pool, $server, Redis $conn ) {
308 $this->pool = $pool;
309 $this->server = $server;
310 $this->conn = $conn;
313 public function __call( $name, $arguments ) {
314 return call_user_func_array( array( $this->conn, $name ), $arguments );
317 function __destruct() {
318 $this->pool->freeConnection( $this->server, $this->conn );