Merge "American spelling - recognize/customize"
[lhc/web/wiklou.git] / includes / clientpool / RedisConnectionPool.php
1 <?php
2 /**
3 * PhpRedis client connection pooling manager.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @defgroup Redis Redis
22 * @author Aaron Schulz
23 */
24
25 /**
26 * Helper class to manage redis connections using PhpRedis.
27 *
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.
34 *
35 * @ingroup Redis
36 * @since 1.21
37 */
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_*)
45
46 protected $idlePoolSize = 0; // integer; current idle pool size
47
48 /** @var Array (server name => ((connection info array),...) */
49 protected $connections = array();
50 /** @var Array (server name => UNIX timestamp) */
51 protected $downServers = array();
52
53 /** @var Array */
54 protected static $instances = array(); // (pool ID => RedisConnectionPool)
55
56 const SERVER_DOWN_TTL = 30; // integer; seconds to cache servers as "down"
57
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
69 */
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' );
74 }
75 $this->connectTimeout = isset( $options['connectTimeout'] )
76 ? $options['connectTimeout']
77 : 1;
78 $this->persistent = isset( $options['persistent'] )
79 ? $options['persistent']
80 : false;
81 $this->password = isset( $options['password'] )
82 ? $options['password']
83 : '';
84 $this->poolSize = isset( $options['poolSize'] )
85 ? $options['poolSize']
86 : 5;
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;
91 } else {
92 throw new MWException( "Invalid serializer specified." );
93 }
94 }
95
96 /**
97 * @param $options Array
98 * @return RedisConnectionPool
99 */
100 public static function singleton( array $options ) {
101 // Map the options to a unique hash...
102 $poolOptions = $options;
103 unset( $poolOptions['poolSize'] ); // avoid pool fragmentation
104 ksort( $poolOptions ); // normalize to avoid pool fragmentation
105 $id = sha1( serialize( $poolOptions ) );
106 // Initialize the object at the hash as needed...
107 if ( !isset( self::$instances[$id] ) ) {
108 self::$instances[$id] = new self( $options );
109 wfDebug( "Creating a new " . __CLASS__ . " instance with id $id." );
110 }
111 // Simply grow the pool size if the existing one is too small
112 $psize = isset( $options['poolSize'] ) ? $options['poolSize'] : 1; // size requested
113 self::$instances[$id]->poolSize = max( $psize, self::$instances[$id]->poolSize );
114
115 return self::$instances[$id];
116 }
117
118 /**
119 * Get a connection to a redis server. Based on code in RedisBagOStuff.php.
120 *
121 * @param $server string A hostname/port combination or the absolute path of a UNIX socket.
122 * If a hostname is specified but no port, port 6379 will be used.
123 * @return RedisConnRef|bool Returns false on failure
124 * @throws MWException
125 */
126 public function getConnection( $server ) {
127 // Check the listing "dead" servers which have had a connection errors.
128 // Servers are marked dead for a limited period of time, to
129 // avoid excessive overhead from repeated connection timeouts.
130 if ( isset( $this->downServers[$server] ) ) {
131 $now = time();
132 if ( $now > $this->downServers[$server] ) {
133 // Dead time expired
134 unset( $this->downServers[$server] );
135 } else {
136 // Server is dead
137 wfDebug( "server $server is marked down for another " .
138 ( $this->downServers[$server] - $now ) . " seconds, can't get connection" );
139 return false;
140 }
141 }
142
143 // Check if a connection is already free for use
144 if ( isset( $this->connections[$server] ) ) {
145 foreach ( $this->connections[$server] as &$connection ) {
146 if ( $connection['free'] ) {
147 $connection['free'] = false;
148 --$this->idlePoolSize;
149 return new RedisConnRef( $this, $server, $connection['conn'] );
150 }
151 }
152 }
153
154 if ( substr( $server, 0, 1 ) === '/' ) {
155 // UNIX domain socket
156 // These are required by the redis extension to start with a slash, but
157 // we still need to set the port to a special value to make it work.
158 $host = $server;
159 $port = 0;
160 } else {
161 // TCP connection
162 $hostPort = IP::splitHostAndPort( $server );
163 if ( !$hostPort ) {
164 throw new MWException( __CLASS__.": invalid configured server \"$server\"" );
165 }
166 list( $host, $port ) = $hostPort;
167 if ( $port === false ) {
168 $port = 6379;
169 }
170 }
171
172 $conn = new Redis();
173 try {
174 if ( $this->persistent ) {
175 $result = $conn->pconnect( $host, $port, $this->connectTimeout );
176 } else {
177 $result = $conn->connect( $host, $port, $this->connectTimeout );
178 }
179 if ( !$result ) {
180 wfDebugLog( 'redis', "Could not connect to server $server" );
181 // Mark server down for some time to avoid further timeouts
182 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
183 return false;
184 }
185 if ( $this->password !== null ) {
186 if ( !$conn->auth( $this->password ) ) {
187 wfDebugLog( 'redis', "Authentication error connecting to $server" );
188 }
189 }
190 } catch ( RedisException $e ) {
191 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
192 wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
193 return false;
194 }
195
196 if ( $conn ) {
197 $conn->setOption( Redis::OPT_SERIALIZER, $this->serializer );
198 $this->connections[$server][] = array( 'conn' => $conn, 'free' => false );
199 return new RedisConnRef( $this, $server, $conn );
200 } else {
201 return false;
202 }
203 }
204
205 /**
206 * Mark a connection to a server as free to return to the pool
207 *
208 * @param $server string
209 * @param $conn Redis
210 * @return boolean
211 */
212 public function freeConnection( $server, Redis $conn ) {
213 $found = false;
214
215 foreach ( $this->connections[$server] as &$connection ) {
216 if ( $connection['conn'] === $conn && !$connection['free'] ) {
217 $connection['free'] = true;
218 ++$this->idlePoolSize;
219 break;
220 }
221 }
222
223 $this->closeExcessIdleConections();
224
225 return $found;
226 }
227
228 /**
229 * Close any extra idle connections if there are more than the limit
230 *
231 * @return void
232 */
233 protected function closeExcessIdleConections() {
234 if ( $this->idlePoolSize <= $this->poolSize ) {
235 return; // nothing to do
236 }
237
238 foreach ( $this->connections as $server => &$serverConnections ) {
239 foreach ( $serverConnections as $key => &$connection ) {
240 if ( $connection['free'] ) {
241 unset( $serverConnections[$key] );
242 if ( --$this->idlePoolSize <= $this->poolSize ) {
243 return; // done
244 }
245 }
246 }
247 }
248 }
249
250 /**
251 * The redis extension throws an exception in response to various read, write
252 * and protocol errors. Sometimes it also closes the connection, sometimes
253 * not. The safest response for us is to explicitly destroy the connection
254 * object and let it be reopened during the next request.
255 *
256 * @param $server string
257 * @param $conn RedisConnRef
258 * @param $e RedisException
259 * @return void
260 */
261 public function handleException( $server, RedisConnRef $conn, RedisException $e ) {
262 wfDebugLog( 'redis',
263 "Redis exception on server $server: " . $e->getMessage() . "\n" );
264 foreach ( $this->connections[$server] as $key => $connection ) {
265 if ( $connection['conn'] === $conn ) {
266 $this->idlePoolSize -= $connection['free'] ? 1 : 0;
267 unset( $this->connections[$server][$key] );
268 break;
269 }
270 }
271 }
272 }
273
274 /**
275 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
276 *
277 * @ingroup Redis
278 * @since 1.21
279 */
280 class RedisConnRef {
281 /** @var RedisConnectionPool */
282 protected $pool;
283
284 protected $server; // string
285
286 /** @var Redis */
287 protected $conn;
288
289 /**
290 * @param $pool RedisConnectionPool
291 * @param $server string
292 * @param $conn Redis
293 */
294 public function __construct( RedisConnectionPool $pool, $server, Redis $conn ) {
295 $this->pool = $pool;
296 $this->server = $server;
297 $this->conn = $conn;
298 }
299
300 public function __call( $name, $arguments ) {
301 return call_user_func_array( array( $this->conn, $name ), $arguments );
302 }
303
304 function __destruct() {
305 $this->pool->freeConnection( $this->server, $this->conn );
306 }
307 }