Merge "Installer: page refresh should refresh list of supported DBs"
[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 /**
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.
43 * @{
44 */
45 /** @var string Connection timeout in seconds */
46 protected $connectTimeout;
47 /** @var string Plaintext auth password */
48 protected $password;
49 /** @var bool Whether connections persist */
50 protected $persistent;
51 /** @var integer Serializer to use (Redis::SERIALIZER_*) */
52 protected $serializer;
53 /** @} */
54
55 /** @var integer Current idle pool size */
56 protected $idlePoolSize = 0;
57
58 /** @var Array (server name => ((connection info array),...) */
59 protected $connections = array();
60 /** @var Array (server name => UNIX timestamp) */
61 protected $downServers = array();
62
63 /** @var Array (pool ID => RedisConnectionPool) */
64 protected static $instances = array();
65
66 /** integer; seconds to cache servers as "down". */
67 const SERVER_DOWN_TTL = 30;
68
69 /**
70 * @param array $options
71 */
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' );
76 }
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;
86 } else {
87 throw new MWException( "Invalid serializer specified." );
88 }
89 }
90
91 /**
92 * @param $options Array
93 * @return Array
94 */
95 protected static function applyDefaultConfig( array $options ) {
96 if ( !isset( $options['connectTimeout'] ) ) {
97 $options['connectTimeout'] = 1;
98 }
99 if ( !isset( $options['persistent'] ) ) {
100 $options['persistent'] = false;
101 }
102 if ( !isset( $options['password'] ) ) {
103 $options['password'] = null;
104 }
105 return $options;
106 }
107
108 /**
109 * @param $options Array
110 * $options include:
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
119 */
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." );
129 }
130 return self::$instances[$id];
131 }
132
133 /**
134 * Get a connection to a redis server. Based on code in RedisBagOStuff.php.
135 *
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
140 */
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] ) ) {
146 $now = time();
147 if ( $now > $this->downServers[$server] ) {
148 // Dead time expired
149 unset( $this->downServers[$server] );
150 } else {
151 // Server is dead
152 wfDebug( "server $server is marked down for another " .
153 ( $this->downServers[$server] - $now ) . " seconds, can't get connection" );
154 return false;
155 }
156 }
157
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'] );
165 }
166 }
167 }
168
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.
173 $host = $server;
174 $port = 0;
175 } else {
176 // TCP connection
177 $hostPort = IP::splitHostAndPort( $server );
178 if ( !$hostPort ) {
179 throw new MWException( __CLASS__ . ": invalid configured server \"$server\"" );
180 }
181 list( $host, $port ) = $hostPort;
182 if ( $port === false ) {
183 $port = 6379;
184 }
185 }
186
187 $conn = new Redis();
188 try {
189 if ( $this->persistent ) {
190 $result = $conn->pconnect( $host, $port, $this->connectTimeout );
191 } else {
192 $result = $conn->connect( $host, $port, $this->connectTimeout );
193 }
194 if ( !$result ) {
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;
198 return false;
199 }
200 if ( $this->password !== null ) {
201 if ( !$conn->auth( $this->password ) ) {
202 wfDebugLog( 'redis', "Authentication error connecting to $server" );
203 }
204 }
205 } catch ( RedisException $e ) {
206 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
207 wfDebugLog( 'redis', "Redis exception: " . $e->getMessage() . "\n" );
208 return false;
209 }
210
211 if ( $conn ) {
212 $conn->setOption( Redis::OPT_SERIALIZER, $this->serializer );
213 $this->connections[$server][] = array( 'conn' => $conn, 'free' => false );
214 return new RedisConnRef( $this, $server, $conn );
215 } else {
216 return false;
217 }
218 }
219
220 /**
221 * Mark a connection to a server as free to return to the pool
222 *
223 * @param $server string
224 * @param $conn Redis
225 * @return boolean
226 */
227 public function freeConnection( $server, Redis $conn ) {
228 $found = false;
229
230 foreach ( $this->connections[$server] as &$connection ) {
231 if ( $connection['conn'] === $conn && !$connection['free'] ) {
232 $connection['free'] = true;
233 ++$this->idlePoolSize;
234 break;
235 }
236 }
237
238 $this->closeExcessIdleConections();
239
240 return $found;
241 }
242
243 /**
244 * Close any extra idle connections if there are more than the limit
245 *
246 * @return void
247 */
248 protected function closeExcessIdleConections() {
249 if ( $this->idlePoolSize <= count( $this->connections ) ) {
250 return; // nothing to do (no more connections than servers)
251 }
252
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)
259 }
260 }
261 }
262 }
263 }
264
265 /**
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.
270 *
271 * @param $server string
272 * @param $cref RedisConnRef
273 * @param $e RedisException
274 * @return void
275 */
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] );
282 break;
283 }
284 }
285 }
286 }
287
288 /**
289 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
290 *
291 * @ingroup Redis
292 * @since 1.21
293 */
294 class RedisConnRef {
295 /** @var RedisConnectionPool */
296 protected $pool;
297 /** @var Redis */
298 protected $conn;
299
300 protected $server; // string
301
302 /**
303 * @param $pool RedisConnectionPool
304 * @param $server string
305 * @param $conn Redis
306 */
307 public function __construct( RedisConnectionPool $pool, $server, Redis $conn ) {
308 $this->pool = $pool;
309 $this->server = $server;
310 $this->conn = $conn;
311 }
312
313 public function __call( $name, $arguments ) {
314 return call_user_func_array( array( $this->conn, $name ), $arguments );
315 }
316
317 /**
318 * @param string $script
319 * @param array $params
320 * @param integer $numKeys
321 * @return mixed
322 * @throws RedisException
323 */
324 public function luaEval( $script, array $params, $numKeys ) {
325 $sha1 = sha1( $script ); // 40 char hex
326 $conn = $this->conn; // convenience
327
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." );
336 }
337
338 if ( $conn->getLastError() ) { // script bug?
339 wfDebugLog( 'redis', "Lua script error: " . $conn->getLastError() );
340 }
341
342 return $res;
343 }
344
345 /**
346 * @param RedisConnRef $conn
347 * @return bool
348 */
349 public function isConnIdentical( Redis $conn ) {
350 return $this->conn === $conn;
351 }
352
353 function __destruct() {
354 $this->pool->freeConnection( $this->server, $this->conn );
355 }
356 }