3 * Redis 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
25 use MediaWiki\Logger\LoggerFactory
;
26 use Psr\Log\LoggerAwareInterface
;
27 use Psr\Log\LoggerInterface
;
30 * Helper class to manage Redis connections.
32 * This can be used to get handle wrappers that free the handle when the wrapper
33 * leaves scope. The maximum number of free handles (connections) is configurable.
34 * This provides an easy way to cache connection handles that may also have state,
35 * such as a handle does between multi() and exec(), and without hoarding connections.
36 * The wrappers use PHP magic methods so that calling functions on them calls the
37 * function of the actual Redis object handle.
42 class RedisConnectionPool
implements LoggerAwareInterface
{
44 * @name Pool settings.
45 * Settings there are shared for any connection made in this pool.
46 * See the singleton() method documentation for more details.
49 /** @var string Connection timeout in seconds */
50 protected $connectTimeout;
51 /** @var string Read timeout in seconds */
52 protected $readTimeout;
53 /** @var string Plaintext auth password */
55 /** @var bool Whether connections persist */
56 protected $persistent;
57 /** @var int Serializer to use (Redis::SERIALIZER_*) */
58 protected $serializer;
61 /** @var int Current idle pool size */
62 protected $idlePoolSize = 0;
64 /** @var array (server name => ((connection info array),...) */
65 protected $connections = array();
66 /** @var array (server name => UNIX timestamp) */
67 protected $downServers = array();
69 /** @var array (pool ID => RedisConnectionPool) */
70 protected static $instances = array();
72 /** integer; seconds to cache servers as "down". */
73 const SERVER_DOWN_TTL
= 30;
76 * @var LoggerInterface
81 * @param array $options
84 protected function __construct( array $options ) {
85 if ( !class_exists( 'Redis' ) ) {
86 throw new Exception( __CLASS__
. ' requires a Redis client library. ' .
87 'See https://www.mediawiki.org/wiki/Redis#Setup' );
89 if ( isset( $options['logger'] ) ) {
90 $this->setLogger( $options['logger'] );
92 $this->setLogger( LoggerFactory
::getInstance( 'redis' ) );
94 $this->connectTimeout
= $options['connectTimeout'];
95 $this->readTimeout
= $options['readTimeout'];
96 $this->persistent
= $options['persistent'];
97 $this->password
= $options['password'];
98 if ( !isset( $options['serializer'] ) ||
$options['serializer'] === 'php' ) {
99 $this->serializer
= Redis
::SERIALIZER_PHP
;
100 } elseif ( $options['serializer'] === 'igbinary' ) {
101 $this->serializer
= Redis
::SERIALIZER_IGBINARY
;
102 } elseif ( $options['serializer'] === 'none' ) {
103 $this->serializer
= Redis
::SERIALIZER_NONE
;
105 throw new InvalidArgumentException( "Invalid serializer specified." );
110 * @param LoggerInterface $logger
113 public function setLogger( LoggerInterface
$logger ) {
114 $this->logger
= $logger;
118 * @param array $options
121 protected static function applyDefaultConfig( array $options ) {
122 if ( !isset( $options['connectTimeout'] ) ) {
123 $options['connectTimeout'] = 1;
125 if ( !isset( $options['readTimeout'] ) ) {
126 $options['readTimeout'] = 1;
128 if ( !isset( $options['persistent'] ) ) {
129 $options['persistent'] = false;
131 if ( !isset( $options['password'] ) ) {
132 $options['password'] = null;
139 * @param array $options
141 * - connectTimeout : The timeout for new connections, in seconds.
142 * Optional, default is 1 second.
143 * - readTimeout : The timeout for operation reads, in seconds.
144 * Commands like BLPOP can fail if told to wait longer than this.
145 * Optional, default is 1 second.
146 * - persistent : Set this to true to allow connections to persist across
147 * multiple web requests. False by default.
148 * - password : The authentication password, will be sent to Redis in clear text.
149 * Optional, if it is unspecified, no AUTH command will be sent.
150 * - serializer : Set to "php", "igbinary", or "none". Default is "php".
151 * @return RedisConnectionPool
153 public static function singleton( array $options ) {
154 $options = self
::applyDefaultConfig( $options );
155 // Map the options to a unique hash...
156 ksort( $options ); // normalize to avoid pool fragmentation
157 $id = sha1( serialize( $options ) );
158 // Initialize the object at the hash as needed...
159 if ( !isset( self
::$instances[$id] ) ) {
160 self
::$instances[$id] = new self( $options );
161 LoggerFactory
::getInstance( 'redis' )->debug(
162 "Creating a new " . __CLASS__
. " instance with id $id."
166 return self
::$instances[$id];
170 * Destroy all singleton() instances
173 public static function destroySingletons() {
174 self
::$instances = array();
178 * Get a connection to a redis server. Based on code in RedisBagOStuff.php.
180 * @param string $server A hostname/port combination or the absolute path of a UNIX socket.
181 * If a hostname is specified but no port, port 6379 will be used.
182 * @return RedisConnRef|bool Returns false on failure
183 * @throws MWException
185 public function getConnection( $server ) {
186 // Check the listing "dead" servers which have had a connection errors.
187 // Servers are marked dead for a limited period of time, to
188 // avoid excessive overhead from repeated connection timeouts.
189 if ( isset( $this->downServers
[$server] ) ) {
191 if ( $now > $this->downServers
[$server] ) {
193 unset( $this->downServers
[$server] );
196 $this->logger
->debug(
197 'Server "{redis_server}" is marked down for another ' .
198 ( $this->downServers
[$server] - $now ) . 'seconds',
199 array( 'redis_server' => $server )
206 // Check if a connection is already free for use
207 if ( isset( $this->connections
[$server] ) ) {
208 foreach ( $this->connections
[$server] as &$connection ) {
209 if ( $connection['free'] ) {
210 $connection['free'] = false;
211 --$this->idlePoolSize
;
213 return new RedisConnRef(
214 $this, $server, $connection['conn'], $this->logger
220 if ( substr( $server, 0, 1 ) === '/' ) {
221 // UNIX domain socket
222 // These are required by the redis extension to start with a slash, but
223 // we still need to set the port to a special value to make it work.
228 $hostPort = IP
::splitHostAndPort( $server );
229 if ( !$server ||
!$hostPort ) {
230 throw new InvalidArgumentException(
231 __CLASS__
. ": invalid configured server \"$server\""
234 list( $host, $port ) = $hostPort;
235 if ( $port === false ) {
242 if ( $this->persistent
) {
243 $result = $conn->pconnect( $host, $port, $this->connectTimeout
);
245 $result = $conn->connect( $host, $port, $this->connectTimeout
);
248 $this->logger
->error(
249 'Could not connect to server "{redis_server}"',
250 array( 'redis_server' => $server )
252 // Mark server down for some time to avoid further timeouts
253 $this->downServers
[$server] = time() + self
::SERVER_DOWN_TTL
;
257 if ( $this->password
!== null ) {
258 if ( !$conn->auth( $this->password
) ) {
259 $this->logger
->error(
260 'Authentication error connecting to "{redis_server}"',
261 array( 'redis_server' => $server )
265 } catch ( RedisException
$e ) {
266 $this->downServers
[$server] = time() + self
::SERVER_DOWN_TTL
;
267 $this->logger
->error(
268 'Redis exception connecting to "{redis_server}"',
270 'redis_server' => $server,
279 $conn->setOption( Redis
::OPT_READ_TIMEOUT
, $this->readTimeout
);
280 $conn->setOption( Redis
::OPT_SERIALIZER
, $this->serializer
);
281 $this->connections
[$server][] = array( 'conn' => $conn, 'free' => false );
283 return new RedisConnRef( $this, $server, $conn, $this->logger
);
290 * Mark a connection to a server as free to return to the pool
292 * @param string $server
296 public function freeConnection( $server, Redis
$conn ) {
299 foreach ( $this->connections
[$server] as &$connection ) {
300 if ( $connection['conn'] === $conn && !$connection['free'] ) {
301 $connection['free'] = true;
302 ++
$this->idlePoolSize
;
307 $this->closeExcessIdleConections();
313 * Close any extra idle connections if there are more than the limit
315 protected function closeExcessIdleConections() {
316 if ( $this->idlePoolSize
<= count( $this->connections
) ) {
317 return; // nothing to do (no more connections than servers)
320 foreach ( $this->connections
as &$serverConnections ) {
321 foreach ( $serverConnections as $key => &$connection ) {
322 if ( $connection['free'] ) {
323 unset( $serverConnections[$key] );
324 if ( --$this->idlePoolSize
<= count( $this->connections
) ) {
325 return; // done (no more connections than servers)
333 * The redis extension throws an exception in response to various read, write
334 * and protocol errors. Sometimes it also closes the connection, sometimes
335 * not. The safest response for us is to explicitly destroy the connection
336 * object and let it be reopened during the next request.
338 * @param string $server
339 * @param RedisConnRef $cref
340 * @param RedisException $e
341 * @deprecated since 1.23
343 public function handleException( $server, RedisConnRef
$cref, RedisException
$e ) {
344 $this->handleError( $cref, $e );
348 * The redis extension throws an exception in response to various read, write
349 * and protocol errors. Sometimes it also closes the connection, sometimes
350 * not. The safest response for us is to explicitly destroy the connection
351 * object and let it be reopened during the next request.
353 * @param RedisConnRef $cref
354 * @param RedisException $e
356 public function handleError( RedisConnRef
$cref, RedisException
$e ) {
357 $server = $cref->getServer();
358 $this->logger
->error(
359 'Redis exception on server "{redis_server}"',
361 'redis_server' => $server,
365 foreach ( $this->connections
[$server] as $key => $connection ) {
366 if ( $cref->isConnIdentical( $connection['conn'] ) ) {
367 $this->idlePoolSize
-= $connection['free'] ?
1 : 0;
368 unset( $this->connections
[$server][$key] );
375 * Re-send an AUTH request to the redis server (useful after disconnects).
377 * This works around an upstream bug in phpredis. phpredis hides disconnects by transparently
378 * reconnecting, but it neglects to re-authenticate the new connection. To the user of the
379 * phpredis client API this manifests as a seemingly random tendency of connections to lose
380 * their authentication status.
382 * This method is for internal use only.
384 * @see https://github.com/nicolasff/phpredis/issues/403
386 * @param string $server
388 * @return bool Success
390 public function reauthenticateConnection( $server, Redis
$conn ) {
391 if ( $this->password
!== null ) {
392 if ( !$conn->auth( $this->password
) ) {
393 $this->logger
->error(
394 'Authentication error connecting to "{redis_server}"',
395 array( 'redis_server' => $server )
406 * Adjust or reset the connection handle read timeout value
409 * @param int $timeout Optional
411 public function resetTimeout( Redis
$conn, $timeout = null ) {
412 $conn->setOption( Redis
::OPT_READ_TIMEOUT
, $timeout ?
: $this->readTimeout
);
416 * Make sure connections are closed for sanity
418 function __destruct() {
419 foreach ( $this->connections
as $server => &$serverConnections ) {
420 foreach ( $serverConnections as $key => &$connection ) {
421 $connection['conn']->close();
428 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
430 * This class simply wraps the Redis class and can be used the same way
436 /** @var RedisConnectionPool */
441 protected $server; // string
442 protected $lastError; // string
445 * @var LoggerInterface
450 * @param RedisConnectionPool $pool
451 * @param string $server
453 * @param LoggerInterface $logger
455 public function __construct(
456 RedisConnectionPool
$pool, $server, Redis
$conn, LoggerInterface
$logger
459 $this->server
= $server;
461 $this->logger
= $logger;
468 public function getServer() {
469 return $this->server
;
472 public function getLastError() {
473 return $this->lastError
;
476 public function clearLastError() {
477 $this->lastError
= null;
480 public function __call( $name, $arguments ) {
481 $conn = $this->conn
; // convenience
483 // Work around https://github.com/nicolasff/phpredis/issues/70
484 $lname = strtolower( $name );
485 if ( ( $lname === 'blpop' ||
$lname == 'brpop' )
486 && is_array( $arguments[0] ) && isset( $arguments[1] )
488 $this->pool
->resetTimeout( $conn, $arguments[1] +
1 );
489 } elseif ( $lname === 'brpoplpush' && isset( $arguments[2] ) ) {
490 $this->pool
->resetTimeout( $conn, $arguments[2] +
1 );
493 $conn->clearLastError();
495 $res = call_user_func_array( array( $conn, $name ), $arguments );
496 if ( preg_match( '/^ERR operation not permitted\b/', $conn->getLastError() ) ) {
497 $this->pool
->reauthenticateConnection( $this->server
, $conn );
498 $conn->clearLastError();
499 $res = call_user_func_array( array( $conn, $name ), $arguments );
501 "Used automatic re-authentication for method '$name'.",
502 array( 'redis_server' => $this->server
)
505 } catch ( RedisException
$e ) {
506 $this->pool
->resetTimeout( $conn ); // restore
510 $this->lastError
= $conn->getLastError() ?
: $this->lastError
;
512 $this->pool
->resetTimeout( $conn ); // restore
518 * @param string $script
519 * @param array $params
520 * @param int $numKeys
522 * @throws RedisException
524 public function luaEval( $script, array $params, $numKeys ) {
525 $sha1 = sha1( $script ); // 40 char hex
526 $conn = $this->conn
; // convenience
527 $server = $this->server
; // convenience
529 // Try to run the server-side cached copy of the script
530 $conn->clearLastError();
531 $res = $conn->evalSha( $sha1, $params, $numKeys );
532 // If we got a permission error reply that means that (a) we are not in
533 // multi()/pipeline() and (b) some connection problem likely occurred. If
534 // the password the client gave was just wrong, an exception should have
535 // been thrown back in getConnection() previously.
536 if ( preg_match( '/^ERR operation not permitted\b/', $conn->getLastError() ) ) {
537 $this->pool
->reauthenticateConnection( $server, $conn );
538 $conn->clearLastError();
539 $res = $conn->eval( $script, $params, $numKeys );
541 "Used automatic re-authentication for Lua script '$sha1'.",
542 array( 'redis_server' => $server )
545 // If the script is not in cache, use eval() to retry and cache it
546 if ( preg_match( '/^NOSCRIPT/', $conn->getLastError() ) ) {
547 $conn->clearLastError();
548 $res = $conn->eval( $script, $params, $numKeys );
550 "Used eval() for Lua script '$sha1'.",
551 array( 'redis_server' => $server )
555 if ( $conn->getLastError() ) { // script bug?
556 $this->logger
->error(
557 'Lua script error on server "{redis_server}": {lua_error}',
559 'redis_server' => $server,
560 'lua_error' => $conn->getLastError()
565 $this->lastError
= $conn->getLastError() ?
: $this->lastError
;
574 public function isConnIdentical( Redis
$conn ) {
575 return $this->conn
=== $conn;
578 function __destruct() {
579 $this->pool
->freeConnection( $this->server
, $this->conn
);