Merge "tipsy: using user class borks positioning of tip"
[lhc/web/wiklou.git] / includes / clientpool / RedisConnectionPool.php
1 <?php
2 /**
3 * Redis 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.
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 int 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 * @throws MWException
72 */
73 protected function __construct( array $options ) {
74 if ( !class_exists( 'Redis' ) ) {
75 throw new MWException( __CLASS__ . ' requires a Redis client library. ' .
76 'See https://www.mediawiki.org/wiki/Redis#Setup' );
77 }
78 $this->connectTimeout = $options['connectTimeout'];
79 $this->persistent = $options['persistent'];
80 $this->password = $options['password'];
81 if ( !isset( $options['serializer'] ) || $options['serializer'] === 'php' ) {
82 $this->serializer = Redis::SERIALIZER_PHP;
83 } elseif ( $options['serializer'] === 'igbinary' ) {
84 $this->serializer = Redis::SERIALIZER_IGBINARY;
85 } elseif ( $options['serializer'] === 'none' ) {
86 $this->serializer = Redis::SERIALIZER_NONE;
87 } else {
88 throw new MWException( "Invalid serializer specified." );
89 }
90 }
91
92 /**
93 * @param array $options
94 * @return array
95 */
96 protected static function applyDefaultConfig( array $options ) {
97 if ( !isset( $options['connectTimeout'] ) ) {
98 $options['connectTimeout'] = 1;
99 }
100 if ( !isset( $options['persistent'] ) ) {
101 $options['persistent'] = false;
102 }
103 if ( !isset( $options['password'] ) ) {
104 $options['password'] = null;
105 }
106
107 return $options;
108 }
109
110 /**
111 * @param array $options
112 * $options include:
113 * - connectTimeout : The timeout for new connections, in seconds.
114 * Optional, default is 1 second.
115 * - persistent : Set this to true to allow connections to persist across
116 * multiple web requests. False by default.
117 * - password : The authentication password, will be sent to Redis in clear text.
118 * Optional, if it is unspecified, no AUTH command will be sent.
119 * - serializer : Set to "php", "igbinary", or "none". Default is "php".
120 * @return RedisConnectionPool
121 */
122 public static function singleton( array $options ) {
123 $options = self::applyDefaultConfig( $options );
124 // Map the options to a unique hash...
125 ksort( $options ); // normalize to avoid pool fragmentation
126 $id = sha1( serialize( $options ) );
127 // Initialize the object at the hash as needed...
128 if ( !isset( self::$instances[$id] ) ) {
129 self::$instances[$id] = new self( $options );
130 wfDebug( "Creating a new " . __CLASS__ . " instance with id $id." );
131 }
132
133 return self::$instances[$id];
134 }
135
136 /**
137 * Get a connection to a redis server. Based on code in RedisBagOStuff.php.
138 *
139 * @param string $server A hostname/port combination or the absolute path of a UNIX socket.
140 * If a hostname is specified but no port, port 6379 will be used.
141 * @return RedisConnRef|bool Returns false on failure
142 * @throws MWException
143 */
144 public function getConnection( $server ) {
145 // Check the listing "dead" servers which have had a connection errors.
146 // Servers are marked dead for a limited period of time, to
147 // avoid excessive overhead from repeated connection timeouts.
148 if ( isset( $this->downServers[$server] ) ) {
149 $now = time();
150 if ( $now > $this->downServers[$server] ) {
151 // Dead time expired
152 unset( $this->downServers[$server] );
153 } else {
154 // Server is dead
155 wfDebug( "server $server is marked down for another " .
156 ( $this->downServers[$server] - $now ) . " seconds, can't get connection" );
157
158 return false;
159 }
160 }
161
162 // Check if a connection is already free for use
163 if ( isset( $this->connections[$server] ) ) {
164 foreach ( $this->connections[$server] as &$connection ) {
165 if ( $connection['free'] ) {
166 $connection['free'] = false;
167 --$this->idlePoolSize;
168
169 return new RedisConnRef( $this, $server, $connection['conn'] );
170 }
171 }
172 }
173
174 if ( substr( $server, 0, 1 ) === '/' ) {
175 // UNIX domain socket
176 // These are required by the redis extension to start with a slash, but
177 // we still need to set the port to a special value to make it work.
178 $host = $server;
179 $port = 0;
180 } else {
181 // TCP connection
182 $hostPort = IP::splitHostAndPort( $server );
183 if ( !$hostPort ) {
184 throw new MWException( __CLASS__ . ": invalid configured server \"$server\"" );
185 }
186 list( $host, $port ) = $hostPort;
187 if ( $port === false ) {
188 $port = 6379;
189 }
190 }
191
192 $conn = new Redis();
193 try {
194 if ( $this->persistent ) {
195 $result = $conn->pconnect( $host, $port, $this->connectTimeout );
196 } else {
197 $result = $conn->connect( $host, $port, $this->connectTimeout );
198 }
199 if ( !$result ) {
200 wfDebugLog( 'redis', "Could not connect to server $server" );
201 // Mark server down for some time to avoid further timeouts
202 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
203
204 return false;
205 }
206 if ( $this->password !== null ) {
207 if ( !$conn->auth( $this->password ) ) {
208 wfDebugLog( 'redis', "Authentication error connecting to $server" );
209 }
210 }
211 } catch ( RedisException $e ) {
212 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
213 wfDebugLog( 'redis', "Redis exception connecting to $server: " . $e->getMessage() );
214
215 return false;
216 }
217
218 if ( $conn ) {
219 $conn->setOption( Redis::OPT_SERIALIZER, $this->serializer );
220 $this->connections[$server][] = array( 'conn' => $conn, 'free' => false );
221
222 return new RedisConnRef( $this, $server, $conn );
223 } else {
224 return false;
225 }
226 }
227
228 /**
229 * Mark a connection to a server as free to return to the pool
230 *
231 * @param string $server
232 * @param Redis $conn
233 * @return bool
234 */
235 public function freeConnection( $server, Redis $conn ) {
236 $found = false;
237
238 foreach ( $this->connections[$server] as &$connection ) {
239 if ( $connection['conn'] === $conn && !$connection['free'] ) {
240 $connection['free'] = true;
241 ++$this->idlePoolSize;
242 break;
243 }
244 }
245
246 $this->closeExcessIdleConections();
247
248 return $found;
249 }
250
251 /**
252 * Close any extra idle connections if there are more than the limit
253 */
254 protected function closeExcessIdleConections() {
255 if ( $this->idlePoolSize <= count( $this->connections ) ) {
256 return; // nothing to do (no more connections than servers)
257 }
258
259 foreach ( $this->connections as &$serverConnections ) {
260 foreach ( $serverConnections as $key => &$connection ) {
261 if ( $connection['free'] ) {
262 unset( $serverConnections[$key] );
263 if ( --$this->idlePoolSize <= count( $this->connections ) ) {
264 return; // done (no more connections than servers)
265 }
266 }
267 }
268 }
269 }
270
271 /**
272 * The redis extension throws an exception in response to various read, write
273 * and protocol errors. Sometimes it also closes the connection, sometimes
274 * not. The safest response for us is to explicitly destroy the connection
275 * object and let it be reopened during the next request.
276 *
277 * @param string $server
278 * @param RedisConnRef $cref
279 * @param RedisException $e
280 */
281 public function handleException( $server, RedisConnRef $cref, RedisException $e ) {
282 wfDebugLog( 'redis', "Redis exception on server $server: " . $e->getMessage() );
283 foreach ( $this->connections[$server] as $key => $connection ) {
284 if ( $cref->isConnIdentical( $connection['conn'] ) ) {
285 $this->idlePoolSize -= $connection['free'] ? 1 : 0;
286 unset( $this->connections[$server][$key] );
287 break;
288 }
289 }
290 }
291
292 /**
293 * Re-send an AUTH request to the redis server (useful after disconnects).
294 *
295 * This works around an upstream bug in phpredis. phpredis hides disconnects by transparently
296 * reconnecting, but it neglects to re-authenticate the new connection. To the user of the
297 * phpredis client API this manifests as a seemingly random tendency of connections to lose
298 * their authentication status.
299 *
300 * This method is for internal use only.
301 *
302 * @see https://github.com/nicolasff/phpredis/issues/403
303 *
304 * @param string $server
305 * @param Redis $conn
306 * @return bool Success
307 */
308 public function reauthenticateConnection( $server, Redis $conn ) {
309 if ( $this->password !== null ) {
310 if ( !$conn->auth( $this->password ) ) {
311 wfDebugLog( 'redis', "Authentication error connecting to $server" );
312
313 return false;
314 }
315 }
316
317 return true;
318 }
319
320 /**
321 * Make sure connections are closed for sanity
322 */
323 function __destruct() {
324 foreach ( $this->connections as $server => &$serverConnections ) {
325 foreach ( $serverConnections as $key => &$connection ) {
326 $connection['conn']->close();
327 }
328 }
329 }
330 }
331
332 /**
333 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
334 *
335 * This class simply wraps the Redis class and can be used the same way
336 *
337 * @ingroup Redis
338 * @since 1.21
339 */
340 class RedisConnRef {
341 /** @var RedisConnectionPool */
342 protected $pool;
343 /** @var Redis */
344 protected $conn;
345
346 protected $server; // string
347 protected $lastError; // string
348
349 /**
350 * @param RedisConnectionPool $pool
351 * @param string $server
352 * @param Redis $conn
353 */
354 public function __construct( RedisConnectionPool $pool, $server, Redis $conn ) {
355 $this->pool = $pool;
356 $this->server = $server;
357 $this->conn = $conn;
358 }
359
360 /**
361 * @return string
362 * @since 1.23
363 */
364 public function getServer() {
365 return $this->server;
366 }
367
368 public function getLastError() {
369 return $this->lastError;
370 }
371
372 public function clearLastError() {
373 $this->lastError = null;
374 }
375
376 public function __call( $name, $arguments ) {
377 $conn = $this->conn; // convenience
378
379 $conn->clearLastError();
380 $res = call_user_func_array( array( $conn, $name ), $arguments );
381 if ( preg_match( '/^ERR operation not permitted\b/', $conn->getLastError() ) ) {
382 $this->pool->reauthenticateConnection( $this->server, $conn );
383 $conn->clearLastError();
384 $res = call_user_func_array( array( $conn, $name ), $arguments );
385 wfDebugLog( 'redis', "Used automatic re-authentication for method '$name'." );
386 }
387
388 $this->lastError = $conn->getLastError() ?: $this->lastError;
389
390 return $res;
391 }
392
393 /**
394 * @param string $script
395 * @param array $params
396 * @param integer $numKeys
397 * @return mixed
398 * @throws RedisException
399 */
400 public function luaEval( $script, array $params, $numKeys ) {
401 $sha1 = sha1( $script ); // 40 char hex
402 $conn = $this->conn; // convenience
403 $server = $this->server; // convenience
404
405 // Try to run the server-side cached copy of the script
406 $conn->clearLastError();
407 $res = $conn->evalSha( $sha1, $params, $numKeys );
408 // If we got a permission error reply that means that (a) we are not in
409 // multi()/pipeline() and (b) some connection problem likely occured. If
410 // the password the client gave was just wrong, an exception should have
411 // been thrown back in getConnection() previously.
412 if ( preg_match( '/^ERR operation not permitted\b/', $conn->getLastError() ) ) {
413 $this->pool->reauthenticateConnection( $server, $conn );
414 $conn->clearLastError();
415 $res = $conn->eval( $script, $params, $numKeys );
416 wfDebugLog( 'redis', "Used automatic re-authentication for Lua script $sha1." );
417 }
418 // If the script is not in cache, use eval() to retry and cache it
419 if ( preg_match( '/^NOSCRIPT/', $conn->getLastError() ) ) {
420 $conn->clearLastError();
421 $res = $conn->eval( $script, $params, $numKeys );
422 wfDebugLog( 'redis', "Used eval() for Lua script $sha1." );
423 }
424
425 if ( $conn->getLastError() ) { // script bug?
426 wfDebugLog( 'redis', "Lua script error on server $server: " . $conn->getLastError() );
427 }
428
429 $this->lastError = $conn->getLastError() ?: $this->lastError;
430
431 return $res;
432 }
433
434 /**
435 * @param Redis $conn
436 * @return bool
437 */
438 public function isConnIdentical( Redis $conn ) {
439 return $this->conn === $conn;
440 }
441
442 function __destruct() {
443 $this->pool->freeConnection( $this->server, $this->conn );
444 }
445 }