Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 150
0.00% covered (danger)
0.00%
0 / 12
CRAP
0.00% covered (danger)
0.00%
0 / 1
RedisConnectionPool
0.00% covered (danger)
0.00%
0 / 149
0.00% covered (danger)
0.00%
0 / 12
3540
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
56
 setLogger
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 applyDefaultConfig
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
42
 singleton
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 destroySingletons
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getConnection
0.00% covered (danger)
0.00%
0 / 67
0.00% covered (danger)
0.00%
0 / 1
380
 freeConnection
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 closeExcessIdleConections
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
42
 handleError
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 reauthenticateConnection
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 resetTimeout
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 __destruct
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7namespace Wikimedia\ObjectCache;
8
9use Exception;
10use InvalidArgumentException;
11use Psr\Log\LoggerAwareInterface;
12use Psr\Log\LoggerInterface;
13use Psr\Log\NullLogger;
14use Redis;
15use RedisException;
16use RuntimeException;
17
18/**
19 * Manage one or more Redis client connection.
20 *
21 * This can be used to get RedisConnRef objects that automatically reuses
22 * connections internally after the calling function has returned (and thus
23 * your RedisConnRef instance leaves scope/destructs).
24 *
25 * This provides an easy way to cache connection handles that may also have state,
26 * such as a handle does between multi() and exec(), and without hoarding connections.
27 * The wrappers use PHP magic methods so that calling functions on them calls the
28 * function of the actual Redis object handle.
29 *
30 * @ingroup Cache
31 * @since 1.21
32 */
33class RedisConnectionPool implements LoggerAwareInterface {
34    /** @var int Connection timeout in seconds */
35    protected $connectTimeout;
36    /** @var string Read timeout in seconds */
37    protected $readTimeout;
38    /** @var string|string[]|null Plaintext auth password or array containing username and password */
39    protected $password;
40    /** @var string|null Key prefix automatically added to all operations */
41    protected $prefix;
42    /** @var bool Whether connections persist */
43    protected $persistent;
44    /** @var int Serializer to use (Redis::SERIALIZER_*) */
45    protected $serializer;
46    /** @var string ID for persistent connections */
47    protected $id;
48
49    /** @var int Current idle pool size */
50    protected $idlePoolSize = 0;
51
52    /**
53     * @var array (server name => ((connection info array),...)
54     * @phan-var array<string,array{conn:Redis,free:bool}[]>
55     */
56    protected $connections = [];
57    /** @var array (server name => UNIX timestamp) */
58    protected $downServers = [];
59
60    /** @var array (pool ID => RedisConnectionPool) */
61    protected static $instances = [];
62
63    /** integer; seconds to cache servers as "down". */
64    private const SERVER_DOWN_TTL = 30;
65
66    /**
67     * @var LoggerInterface
68     */
69    protected $logger;
70
71    /**
72     * @param array $options
73     * @param string $id
74     * @throws Exception
75     */
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
108    /**
109     * @param array $options
110     * @return array
111     */
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
132    /**
133     * @param array $options
134     * $options include:
135     *   - connectTimeout : The timeout for new connections, in seconds.
136     *                      Optional, default is 1 second.
137     *   - readTimeout    : The timeout for operation reads, in seconds.
138     *                      Commands like BLPOP can fail if told to wait longer than this.
139     *                      Optional, default is 1 second.
140     *   - persistent     : Set this to true to allow connections to persist across
141     *                      multiple web requests. False by default.
142     *   - password       : The authentication password, will be sent to Redis in clear text.
143     *                      Optional, if it is unspecified, no AUTH command will be sent.
144     *   - serializer     : Set to "php", "igbinary", or "none". Default is "php".
145     * @return RedisConnectionPool
146     */
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
160    /**
161     * Destroy all singleton() instances
162     * @since 1.27
163     */
164    public static function destroySingletons() {
165        self::$instances = [];
166    }
167
168    /**
169     * Get a connection to a redis server. Based on code in RedisBagOStuff.php.
170     *
171     * @param string $server A hostname/port combination or the absolute path of a UNIX socket.
172     *                       If a hostname is specified but no port, port 6379 will be used.
173     * @param LoggerInterface|null $logger PSR-3 logger instance. [optional]
174     * @return RedisConnRef|Redis|false Returns false on failure
175     * @throws InvalidArgumentException
176     */
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
294    /**
295     * Mark a connection to a server as free to return to the pool
296     *
297     * @param string $server
298     * @param Redis $conn
299     * @return bool
300     */
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
317    /**
318     * Close any extra idle connections if there are more than the limit
319     */
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
337    /**
338     * The redis extension throws an exception in response to various read, write
339     * and protocol errors. Sometimes it also closes the connection, sometimes
340     * not. The safest response for us is to explicitly destroy the connection
341     * object and let it be reopened during the next request.
342     *
343     * @param RedisConnRef $cref
344     * @param RedisException $e
345     */
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
364    /**
365     * Re-send an AUTH request to the redis server (useful after disconnects).
366     *
367     * This works around an upstream bug in phpredis. phpredis hides disconnects by transparently
368     * reconnecting, but it neglects to re-authenticate the new connection. To the user of the
369     * phpredis client API this manifests as a seemingly random tendency of connections to lose
370     * their authentication status.
371     *
372     * This method is for internal use only.
373     *
374     * @see https://github.com/nicolasff/phpredis/issues/403
375     *
376     * @param string $server
377     * @param Redis $conn
378     * @return bool Success
379     */
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
393    /**
394     * Adjust or reset the connection handle read timeout value
395     *
396     * @param Redis $conn
397     * @param int|null $timeout Optional
398     */
399    public function resetTimeout( Redis $conn, $timeout = null ) {
400        $conn->setOption( Redis::OPT_READ_TIMEOUT, $timeout ?: $this->readTimeout );
401    }
402
403    /**
404     * Make sure connections are closed
405     */
406    public function __destruct() {
407        foreach ( $this->connections as &$serverConnections ) {
408            foreach ( $serverConnections as &$connection ) {
409                try {
410                    /** @var Redis $conn */
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
422/** @deprecated class alias since 1.43 */
423class_alias( RedisConnectionPool::class, 'RedisConnectionPool' );