MediaWiki 1.43.1
RedisConnectionPool.php
Go to the documentation of this file.
1<?php
21namespace Wikimedia\ObjectCache;
22
23use Exception;
24use InvalidArgumentException;
25use Psr\Log\LoggerAwareInterface;
26use Psr\Log\LoggerInterface;
27use Psr\Log\NullLogger;
28use Redis;
29use RedisException;
30use RuntimeException;
31
47class RedisConnectionPool implements LoggerAwareInterface {
49 protected $connectTimeout;
51 protected $readTimeout;
53 protected $password;
55 protected $persistent;
57 protected $serializer;
59 protected $id;
60
62 protected $idlePoolSize = 0;
63
68 protected $connections = [];
70 protected $downServers = [];
71
73 protected static $instances = [];
74
76 private const SERVER_DOWN_TTL = 30;
77
81 protected $logger;
82
88 protected function __construct( array $options, $id ) {
89 if ( !class_exists( Redis::class ) ) {
90 throw new RuntimeException(
91 __CLASS__ . ' requires a Redis client library. ' .
92 'See https://www.mediawiki.org/wiki/Redis#Setup' );
93 }
94 $this->logger = $options['logger'] ?? new NullLogger();
95 $this->connectTimeout = $options['connectTimeout'];
96 $this->readTimeout = $options['readTimeout'];
97 $this->persistent = $options['persistent'];
98 $this->password = $options['password'];
99 if ( !isset( $options['serializer'] ) || $options['serializer'] === 'php' ) {
100 $this->serializer = Redis::SERIALIZER_PHP;
101 } elseif ( $options['serializer'] === 'igbinary' ) {
102 if ( !defined( 'Redis::SERIALIZER_IGBINARY' ) ) {
103 throw new InvalidArgumentException(
104 __CLASS__ . ': configured serializer "igbinary" not available' );
105 }
106 $this->serializer = Redis::SERIALIZER_IGBINARY;
107 } elseif ( $options['serializer'] === 'none' ) {
108 $this->serializer = Redis::SERIALIZER_NONE;
109 } else {
110 throw new InvalidArgumentException( "Invalid serializer specified." );
111 }
112 $this->id = $id;
113 }
114
115 public function setLogger( LoggerInterface $logger ) {
116 $this->logger = $logger;
117 }
118
123 protected static function applyDefaultConfig( array $options ) {
124 if ( !isset( $options['connectTimeout'] ) ) {
125 $options['connectTimeout'] = 1;
126 }
127 if ( !isset( $options['readTimeout'] ) ) {
128 $options['readTimeout'] = 1;
129 }
130 if ( !isset( $options['persistent'] ) ) {
131 $options['persistent'] = false;
132 }
133 if ( !isset( $options['password'] ) ) {
134 $options['password'] = null;
135 }
136
137 return $options;
138 }
139
155 public static function singleton( array $options ) {
156 $options = self::applyDefaultConfig( $options );
157 // Map the options to a unique hash...
158 ksort( $options ); // normalize to avoid pool fragmentation
159 $id = sha1( serialize( $options ) );
160 // Initialize the object at the hash as needed...
161 if ( !isset( self::$instances[$id] ) ) {
162 self::$instances[$id] = new self( $options, $id );
163 }
164
165 return self::$instances[$id];
166 }
167
172 public static function destroySingletons() {
173 self::$instances = [];
174 }
175
185 public function getConnection( $server, ?LoggerInterface $logger = null ) {
186 // The above @return also documents 'Redis' for convenience with IDEs.
187 // RedisConnRef uses PHP magic methods, which wouldn't be recognised.
188
190 // Check the listing "dead" servers which have had a connection errors.
191 // Servers are marked dead for a limited period of time, to
192 // avoid excessive overhead from repeated connection timeouts.
193 if ( isset( $this->downServers[$server] ) ) {
194 $now = time();
195 if ( $now > $this->downServers[$server] ) {
196 // Dead time expired
197 unset( $this->downServers[$server] );
198 } else {
199 // Server is dead
200 $logger->debug(
201 'Server "{redis_server}" is marked down for another ' .
202 ( $this->downServers[$server] - $now ) . ' seconds',
203 [ 'redis_server' => $server ]
204 );
205
206 return false;
207 }
208 }
209
210 // Check if a connection is already free for use
211 if ( isset( $this->connections[$server] ) ) {
212 foreach ( $this->connections[$server] as &$connection ) {
213 if ( $connection['free'] ) {
214 $connection['free'] = false;
216
217 return new RedisConnRef(
218 $this, $server, $connection['conn'], $logger
219 );
220 }
221 }
222 }
223
224 if ( !$server ) {
225 throw new InvalidArgumentException(
226 __CLASS__ . ": invalid configured server \"$server\"" );
227 } elseif ( substr( $server, 0, 1 ) === '/' ) {
228 // UNIX domain socket
229 // These are required by the redis extension to start with a slash, but
230 // we still need to set the port to a special value to make it work.
231 $host = $server;
232 $port = 0;
233 } else {
234 // TCP connection
235 if ( preg_match( '/^\[(.+)\]:(\d+)$/', $server, $m ) ) {
236 // (ip, port)
237 [ $host, $port ] = [ $m[1], (int)$m[2] ];
238 } elseif ( preg_match( '/^((?:[\w]+\:\/\/)?[^:]+):(\d+)$/', $server, $m ) ) {
239 // (ip, uri or path, port)
240 [ $host, $port ] = [ $m[1], (int)$m[2] ];
241 if (
242 substr( $host, 0, 6 ) === 'tls://'
243 && version_compare( phpversion( 'redis' ), '5.0.0' ) < 0
244 ) {
245 throw new RuntimeException(
246 'A newer version of the Redis client library is required to use TLS. ' .
247 'See https://www.mediawiki.org/wiki/Redis#Setup' );
248 }
249 } else {
250 // (ip or path, port)
251 [ $host, $port ] = [ $server, 6379 ];
252 }
253 }
254
255 $conn = new Redis();
256 try {
257 if ( $this->persistent ) {
258 $result = $conn->pconnect( $host, $port, $this->connectTimeout, $this->id );
259 } else {
260 $result = $conn->connect( $host, $port, $this->connectTimeout );
261 }
262 if ( !$result ) {
263 $logger->error(
264 'Could not connect to server "{redis_server}"',
265 [ 'redis_server' => $server ]
266 );
267 // Mark server down for some time to avoid further timeouts
268 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
269
270 return false;
271 }
272 if ( ( $this->password !== null ) && !$conn->auth( $this->password ) ) {
273 $logger->error(
274 'Authentication error connecting to "{redis_server}"',
275 [ 'redis_server' => $server ]
276 );
277 }
278 } catch ( RedisException $e ) {
279 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
280 $logger->error(
281 'Redis exception connecting to "{redis_server}"',
282 [
283 'redis_server' => $server,
284 'exception' => $e,
285 ]
286 );
287
288 return false;
289 }
290
291 $conn->setOption( Redis::OPT_READ_TIMEOUT, $this->readTimeout );
292 $conn->setOption( Redis::OPT_SERIALIZER, $this->serializer );
293 $this->connections[$server][] = [ 'conn' => $conn, 'free' => false ];
294
295 return new RedisConnRef( $this, $server, $conn, $logger );
296 }
297
305 public function freeConnection( $server, Redis $conn ) {
306 $found = false;
307
308 foreach ( $this->connections[$server] as &$connection ) {
309 if ( $connection['conn'] === $conn && !$connection['free'] ) {
310 $connection['free'] = true;
312 break;
313 }
314 }
315
317
318 return $found;
319 }
320
324 protected function closeExcessIdleConections() {
325 if ( $this->idlePoolSize <= count( $this->connections ) ) {
326 return; // nothing to do (no more connections than servers)
327 }
328
329 foreach ( $this->connections as &$serverConnections ) {
330 foreach ( $serverConnections as $key => &$connection ) {
331 if ( $connection['free'] ) {
332 unset( $serverConnections[$key] );
333 if ( --$this->idlePoolSize <= count( $this->connections ) ) {
334 return; // done (no more connections than servers)
335 }
336 }
337 }
338 }
339 }
340
350 public function handleError( RedisConnRef $cref, RedisException $e ) {
351 $server = $cref->getServer();
352 $this->logger->error(
353 'Redis exception on server "{redis_server}"',
354 [
355 'redis_server' => $server,
356 'exception' => $e,
357 ]
358 );
359 foreach ( $this->connections[$server] as $key => $connection ) {
360 if ( $cref->isConnIdentical( $connection['conn'] ) ) {
361 $this->idlePoolSize -= $connection['free'] ? 1 : 0;
362 unset( $this->connections[$server][$key] );
363 break;
364 }
365 }
366 }
367
384 public function reauthenticateConnection( $server, Redis $conn ) {
385 if ( $this->password !== null && !$conn->auth( $this->password ) ) {
386 $this->logger->error(
387 'Authentication error connecting to "{redis_server}"',
388 [ 'redis_server' => $server ]
389 );
390
391 return false;
392 }
393
394 return true;
395 }
396
403 public function resetTimeout( Redis $conn, $timeout = null ) {
404 $conn->setOption( Redis::OPT_READ_TIMEOUT, $timeout ?: $this->readTimeout );
405 }
406
410 public function __destruct() {
411 foreach ( $this->connections as &$serverConnections ) {
412 foreach ( $serverConnections as &$connection ) {
413 try {
415 $conn = $connection['conn'];
416 $conn->close();
417 } catch ( RedisException $e ) {
418 // The destructor can be called on shutdown when random parts of the system
419 // have been destructed already, causing weird errors. Ignore them.
420 }
421 }
422 }
423 }
424}
425
427class_alias( RedisConnectionPool::class, 'RedisConnectionPool' );
Wrapper class for Redis connections that automatically reuses connections (via RAII pattern)
Manage one or more Redis client connection.
int $connectTimeout
Connection timeout in seconds.
string $readTimeout
Read timeout in seconds.
static destroySingletons()
Destroy all singleton() instances.
bool $persistent
Whether connections persist.
__destruct()
Make sure connections are closed.
array $downServers
(server name => UNIX timestamp)
freeConnection( $server, Redis $conn)
Mark a connection to a server as free to return to the pool.
string $id
ID for persistent connections.
array $connections
(server name => ((connection info array),...)
handleError(RedisConnRef $cref, RedisException $e)
The redis extension throws an exception in response to various read, write and protocol errors.
resetTimeout(Redis $conn, $timeout=null)
Adjust or reset the connection handle read timeout value.
getConnection( $server, ?LoggerInterface $logger=null)
Get a connection to a redis server.
reauthenticateConnection( $server, Redis $conn)
Re-send an AUTH request to the redis server (useful after disconnects).
closeExcessIdleConections()
Close any extra idle connections if there are more than the limit.
static array $instances
(pool ID => RedisConnectionPool)
int $serializer
Serializer to use (Redis::SERIALIZER_*)