MediaWiki master
RedisConnectionPool.php
Go to the documentation of this file.
1<?php
8
9use Exception;
10use InvalidArgumentException;
11use Psr\Log\LoggerAwareInterface;
12use Psr\Log\LoggerInterface;
13use Psr\Log\NullLogger;
14use Redis;
15use RedisException;
16use RuntimeException;
17
33class RedisConnectionPool implements LoggerAwareInterface {
35 protected $connectTimeout;
37 protected $readTimeout;
39 protected $password;
41 protected $prefix;
43 protected $persistent;
45 protected $serializer;
47 protected $id;
48
50 protected $idlePoolSize = 0;
51
56 protected $connections = [];
58 protected $downServers = [];
59
61 protected static $instances = [];
62
64 private const SERVER_DOWN_TTL = 30;
65
69 protected $logger;
70
76 protected function __construct( array $options, $id ) {
77 if ( !class_exists( Redis::class ) ) {
78 throw new RuntimeException(
79 __CLASS__ . ' requires a Redis client library. ' .
80 'See https://www.mediawiki.org/wiki/Redis#Setup' );
81 }
82 $this->logger = $options['logger'] ?? new NullLogger();
83 $this->connectTimeout = $options['connectTimeout'];
84 $this->readTimeout = $options['readTimeout'];
85 $this->persistent = $options['persistent'];
86 $this->password = $options['password'];
87 $this->prefix = $options['prefix'];
88 if ( !isset( $options['serializer'] ) || $options['serializer'] === 'php' ) {
89 $this->serializer = Redis::SERIALIZER_PHP;
90 } elseif ( $options['serializer'] === 'igbinary' ) {
91 if ( !defined( 'Redis::SERIALIZER_IGBINARY' ) ) {
92 throw new InvalidArgumentException(
93 __CLASS__ . ': configured serializer "igbinary" not available' );
94 }
95 $this->serializer = Redis::SERIALIZER_IGBINARY;
96 } elseif ( $options['serializer'] === 'none' ) {
97 $this->serializer = Redis::SERIALIZER_NONE;
98 } else {
99 throw new InvalidArgumentException( "Invalid serializer specified." );
100 }
101 $this->id = $id;
102 }
103
104 public function setLogger( LoggerInterface $logger ): void {
105 $this->logger = $logger;
106 }
107
112 protected static function applyDefaultConfig( array $options ) {
113 if ( !isset( $options['connectTimeout'] ) ) {
114 $options['connectTimeout'] = 1;
115 }
116 if ( !isset( $options['readTimeout'] ) ) {
117 $options['readTimeout'] = 1;
118 }
119 if ( !isset( $options['persistent'] ) ) {
120 $options['persistent'] = false;
121 }
122 if ( !isset( $options['password'] ) ) {
123 $options['password'] = null;
124 }
125 if ( !isset( $options['prefix'] ) ) {
126 $options['prefix'] = null;
127 }
128
129 return $options;
130 }
131
147 public static function singleton( array $options ) {
148 $options = self::applyDefaultConfig( $options );
149 // Map the options to a unique hash...
150 ksort( $options ); // normalize to avoid pool fragmentation
151 $id = sha1( serialize( $options ) );
152 // Initialize the object at the hash as needed...
153 if ( !isset( self::$instances[$id] ) ) {
154 self::$instances[$id] = new self( $options, $id );
155 }
156
157 return self::$instances[$id];
158 }
159
164 public static function destroySingletons() {
165 self::$instances = [];
166 }
167
177 public function getConnection( $server, ?LoggerInterface $logger = null ) {
178 // The above @return also documents 'Redis' for convenience with IDEs.
179 // RedisConnRef uses PHP magic methods, which wouldn't be recognised.
180
181 $logger = $logger ?: $this->logger;
182 // Check the listing "dead" servers which have had a connection errors.
183 // Servers are marked dead for a limited period of time, to
184 // avoid excessive overhead from repeated connection timeouts.
185 if ( isset( $this->downServers[$server] ) ) {
186 $now = time();
187 if ( $now > $this->downServers[$server] ) {
188 // Dead time expired
189 unset( $this->downServers[$server] );
190 } else {
191 // Server is dead
192 $logger->debug(
193 'Server "{redis_server}" is marked down for another ' .
194 ( $this->downServers[$server] - $now ) . ' seconds',
195 [ 'redis_server' => $server ]
196 );
197
198 return false;
199 }
200 }
201
202 // Check if a connection is already free for use
203 if ( isset( $this->connections[$server] ) ) {
204 foreach ( $this->connections[$server] as &$connection ) {
205 if ( $connection['free'] ) {
206 $connection['free'] = false;
207 --$this->idlePoolSize;
208
209 return new RedisConnRef(
210 $this, $server, $connection['conn'], $logger
211 );
212 }
213 }
214 }
215
216 if ( !$server ) {
217 throw new InvalidArgumentException(
218 __CLASS__ . ": invalid configured server \"$server\"" );
219 } elseif ( str_starts_with( $server, '/' ) ) {
220 // UNIX domain socket
221 // These are required by the redis extension to start with a slash, but
222 // we still need to set the port to a special value to make it work.
223 $host = $server;
224 $port = 0;
225 } else {
226 // TCP connection
227 if ( preg_match( '/^\[(.+)\]:(\d+)$/', $server, $m ) ) {
228 // (ip, port)
229 [ $host, $port ] = [ $m[1], (int)$m[2] ];
230 } elseif ( preg_match( '/^((?:[\w]+\:\/\/)?[^:]+):(\d+)$/', $server, $m ) ) {
231 // (ip, uri or path, port)
232 [ $host, $port ] = [ $m[1], (int)$m[2] ];
233 if (
234 str_starts_with( $host, 'tls://' )
235 && version_compare( phpversion( 'redis' ), '5.0.0' ) < 0
236 ) {
237 throw new RuntimeException(
238 'A newer version of the Redis client library is required to use TLS. ' .
239 'See https://www.mediawiki.org/wiki/Redis#Setup' );
240 }
241 } else {
242 // (ip or path, port)
243 [ $host, $port ] = [ $server, 6379 ];
244 }
245 }
246
247 $conn = new Redis();
248 try {
249 if ( $this->persistent ) {
250 $result = $conn->pconnect( $host, $port, $this->connectTimeout, $this->id );
251 } else {
252 $result = $conn->connect( $host, $port, $this->connectTimeout );
253 }
254 if ( !$result ) {
255 $logger->error(
256 'Could not connect to server "{redis_server}"',
257 [ 'redis_server' => $server ]
258 );
259 // Mark server down for some time to avoid further timeouts
260 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
261
262 return false;
263 }
264 if ( ( $this->password !== null ) && !$conn->auth( $this->password ) ) {
265 $logger->error(
266 'Authentication error connecting to "{redis_server}"',
267 [ 'redis_server' => $server ]
268 );
269 }
270 } catch ( RedisException $e ) {
271 $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
272 $logger->error(
273 'Redis exception connecting to "{redis_server}"',
274 [
275 'redis_server' => $server,
276 'exception' => $e,
277 ]
278 );
279
280 return false;
281 }
282
283 if ( $this->prefix !== null ) {
284 $conn->setOption( Redis::OPT_PREFIX, $this->prefix );
285 }
286
287 $conn->setOption( Redis::OPT_READ_TIMEOUT, $this->readTimeout );
288 $conn->setOption( Redis::OPT_SERIALIZER, $this->serializer );
289 $this->connections[$server][] = [ 'conn' => $conn, 'free' => false ];
290
291 return new RedisConnRef( $this, $server, $conn, $logger );
292 }
293
301 public function freeConnection( $server, Redis $conn ) {
302 $found = false;
303
304 foreach ( $this->connections[$server] as &$connection ) {
305 if ( $connection['conn'] === $conn && !$connection['free'] ) {
306 $connection['free'] = true;
307 ++$this->idlePoolSize;
308 break;
309 }
310 }
311
312 $this->closeExcessIdleConections();
313
314 return $found;
315 }
316
320 protected function closeExcessIdleConections() {
321 if ( $this->idlePoolSize <= count( $this->connections ) ) {
322 return; // nothing to do (no more connections than servers)
323 }
324
325 foreach ( $this->connections as &$serverConnections ) {
326 foreach ( $serverConnections as $key => &$connection ) {
327 if ( $connection['free'] ) {
328 unset( $serverConnections[$key] );
329 if ( --$this->idlePoolSize <= count( $this->connections ) ) {
330 return; // done (no more connections than servers)
331 }
332 }
333 }
334 }
335 }
336
346 public function handleError( RedisConnRef $cref, RedisException $e ) {
347 $server = $cref->getServer();
348 $this->logger->error(
349 'Redis exception on server "{redis_server}"',
350 [
351 'redis_server' => $server,
352 'exception' => $e,
353 ]
354 );
355 foreach ( $this->connections[$server] as $key => $connection ) {
356 if ( $cref->isConnIdentical( $connection['conn'] ) ) {
357 $this->idlePoolSize -= $connection['free'] ? 1 : 0;
358 unset( $this->connections[$server][$key] );
359 break;
360 }
361 }
362 }
363
380 public function reauthenticateConnection( $server, Redis $conn ) {
381 if ( $this->password !== null && !$conn->auth( $this->password ) ) {
382 $this->logger->error(
383 'Authentication error connecting to "{redis_server}"',
384 [ 'redis_server' => $server ]
385 );
386
387 return false;
388 }
389
390 return true;
391 }
392
399 public function resetTimeout( Redis $conn, $timeout = null ) {
400 $conn->setOption( Redis::OPT_READ_TIMEOUT, $timeout ?: $this->readTimeout );
401 }
402
406 public function __destruct() {
407 foreach ( $this->connections as &$serverConnections ) {
408 foreach ( $serverConnections as &$connection ) {
409 try {
411 $conn = $connection['conn'];
412 $conn->close();
413 } catch ( RedisException ) {
414 // The destructor can be called on shutdown when random parts of the system
415 // have been destructed already, causing weird errors. Ignore them.
416 }
417 }
418 }
419 }
420}
421
423class_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)
string string[] null $password
Plaintext auth password or array containing username and password.
int $serializer
Serializer to use (Redis::SERIALIZER_*)
string null $prefix
Key prefix automatically added to all operations.