RedisConnectionPool.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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. */
  23. use Psr\Log\LoggerAwareInterface;
  24. use Psr\Log\LoggerInterface;
  25. use Psr\Log\NullLogger;
  26. /**
  27. * Helper class to manage Redis connections.
  28. *
  29. * This can be used to get handle wrappers that free the handle when the wrapper
  30. * leaves scope. The maximum number of free handles (connections) is configurable.
  31. * This provides an easy way to cache connection handles that may also have state,
  32. * such as a handle does between multi() and exec(), and without hoarding connections.
  33. * The wrappers use PHP magic methods so that calling functions on them calls the
  34. * function of the actual Redis object handle.
  35. *
  36. * @ingroup Redis
  37. * @since 1.21
  38. */
  39. class RedisConnectionPool implements LoggerAwareInterface {
  40. /** @var string Connection timeout in seconds */
  41. protected $connectTimeout;
  42. /** @var string Read timeout in seconds */
  43. protected $readTimeout;
  44. /** @var string Plaintext auth password */
  45. protected $password;
  46. /** @var bool Whether connections persist */
  47. protected $persistent;
  48. /** @var int Serializer to use (Redis::SERIALIZER_*) */
  49. protected $serializer;
  50. /** @var string ID for persistent connections */
  51. protected $id;
  52. /** @var int Current idle pool size */
  53. protected $idlePoolSize = 0;
  54. /** @var array (server name => ((connection info array),...) */
  55. protected $connections = [];
  56. /** @var array (server name => UNIX timestamp) */
  57. protected $downServers = [];
  58. /** @var array (pool ID => RedisConnectionPool) */
  59. protected static $instances = [];
  60. /** integer; seconds to cache servers as "down". */
  61. const SERVER_DOWN_TTL = 30;
  62. /**
  63. * @var LoggerInterface
  64. */
  65. protected $logger;
  66. /**
  67. * @param array $options
  68. * @param string $id
  69. * @throws Exception
  70. */
  71. protected function __construct( array $options, $id ) {
  72. if ( !class_exists( 'Redis' ) ) {
  73. throw new RuntimeException(
  74. __CLASS__ . ' requires a Redis client library. ' .
  75. 'See https://www.mediawiki.org/wiki/Redis#Setup' );
  76. }
  77. $this->logger = $options['logger'] ?? new NullLogger();
  78. $this->connectTimeout = $options['connectTimeout'];
  79. $this->readTimeout = $options['readTimeout'];
  80. $this->persistent = $options['persistent'];
  81. $this->password = $options['password'];
  82. if ( !isset( $options['serializer'] ) || $options['serializer'] === 'php' ) {
  83. $this->serializer = Redis::SERIALIZER_PHP;
  84. } elseif ( $options['serializer'] === 'igbinary' ) {
  85. if ( !defined( 'Redis::SERIALIZER_IGBINARY' ) ) {
  86. throw new InvalidArgumentException(
  87. __CLASS__ . ': configured serializer "igbinary" not available' );
  88. }
  89. $this->serializer = Redis::SERIALIZER_IGBINARY;
  90. } elseif ( $options['serializer'] === 'none' ) {
  91. $this->serializer = Redis::SERIALIZER_NONE;
  92. } else {
  93. throw new InvalidArgumentException( "Invalid serializer specified." );
  94. }
  95. $this->id = $id;
  96. }
  97. public function setLogger( LoggerInterface $logger ) {
  98. $this->logger = $logger;
  99. }
  100. /**
  101. * @param array $options
  102. * @return array
  103. */
  104. protected static function applyDefaultConfig( array $options ) {
  105. if ( !isset( $options['connectTimeout'] ) ) {
  106. $options['connectTimeout'] = 1;
  107. }
  108. if ( !isset( $options['readTimeout'] ) ) {
  109. $options['readTimeout'] = 1;
  110. }
  111. if ( !isset( $options['persistent'] ) ) {
  112. $options['persistent'] = false;
  113. }
  114. if ( !isset( $options['password'] ) ) {
  115. $options['password'] = null;
  116. }
  117. return $options;
  118. }
  119. /**
  120. * @param array $options
  121. * $options include:
  122. * - connectTimeout : The timeout for new connections, in seconds.
  123. * Optional, default is 1 second.
  124. * - readTimeout : The timeout for operation reads, in seconds.
  125. * Commands like BLPOP can fail if told to wait longer than this.
  126. * Optional, default is 1 second.
  127. * - persistent : Set this to true to allow connections to persist across
  128. * multiple web requests. False by default.
  129. * - password : The authentication password, will be sent to Redis in clear text.
  130. * Optional, if it is unspecified, no AUTH command will be sent.
  131. * - serializer : Set to "php", "igbinary", or "none". Default is "php".
  132. * @return RedisConnectionPool
  133. */
  134. public static function singleton( array $options ) {
  135. $options = self::applyDefaultConfig( $options );
  136. // Map the options to a unique hash...
  137. ksort( $options ); // normalize to avoid pool fragmentation
  138. $id = sha1( serialize( $options ) );
  139. // Initialize the object at the hash as needed...
  140. if ( !isset( self::$instances[$id] ) ) {
  141. self::$instances[$id] = new self( $options, $id );
  142. }
  143. return self::$instances[$id];
  144. }
  145. /**
  146. * Destroy all singleton() instances
  147. * @since 1.27
  148. */
  149. public static function destroySingletons() {
  150. self::$instances = [];
  151. }
  152. /**
  153. * Get a connection to a redis server. Based on code in RedisBagOStuff.php.
  154. *
  155. * @param string $server A hostname/port combination or the absolute path of a UNIX socket.
  156. * If a hostname is specified but no port, port 6379 will be used.
  157. * @param LoggerInterface|null $logger PSR-3 logger intance. [optional]
  158. * @return RedisConnRef|Redis|bool Returns false on failure
  159. * @throws MWException
  160. */
  161. public function getConnection( $server, LoggerInterface $logger = null ) {
  162. // The above @return also documents 'Redis' for convenience with IDEs.
  163. // RedisConnRef uses PHP magic methods, which wouldn't be recognised.
  164. $logger = $logger ?: $this->logger;
  165. // Check the listing "dead" servers which have had a connection errors.
  166. // Servers are marked dead for a limited period of time, to
  167. // avoid excessive overhead from repeated connection timeouts.
  168. if ( isset( $this->downServers[$server] ) ) {
  169. $now = time();
  170. if ( $now > $this->downServers[$server] ) {
  171. // Dead time expired
  172. unset( $this->downServers[$server] );
  173. } else {
  174. // Server is dead
  175. $logger->debug(
  176. 'Server "{redis_server}" is marked down for another ' .
  177. ( $this->downServers[$server] - $now ) . 'seconds',
  178. [ 'redis_server' => $server ]
  179. );
  180. return false;
  181. }
  182. }
  183. // Check if a connection is already free for use
  184. if ( isset( $this->connections[$server] ) ) {
  185. foreach ( $this->connections[$server] as &$connection ) {
  186. if ( $connection['free'] ) {
  187. $connection['free'] = false;
  188. --$this->idlePoolSize;
  189. return new RedisConnRef(
  190. $this, $server, $connection['conn'], $logger
  191. );
  192. }
  193. }
  194. }
  195. if ( !$server ) {
  196. throw new InvalidArgumentException(
  197. __CLASS__ . ": invalid configured server \"$server\"" );
  198. } elseif ( substr( $server, 0, 1 ) === '/' ) {
  199. // UNIX domain socket
  200. // These are required by the redis extension to start with a slash, but
  201. // we still need to set the port to a special value to make it work.
  202. $host = $server;
  203. $port = 0;
  204. } else {
  205. // TCP connection
  206. if ( preg_match( '/^\[(.+)\]:(\d+)$/', $server, $m ) ) {
  207. list( $host, $port ) = [ $m[1], (int)$m[2] ]; // (ip, port)
  208. } elseif ( preg_match( '/^([^:]+):(\d+)$/', $server, $m ) ) {
  209. list( $host, $port ) = [ $m[1], (int)$m[2] ]; // (ip or path, port)
  210. } else {
  211. list( $host, $port ) = [ $server, 6379 ]; // (ip or path, port)
  212. }
  213. }
  214. $conn = new Redis();
  215. try {
  216. if ( $this->persistent ) {
  217. $result = $conn->pconnect( $host, $port, $this->connectTimeout, $this->id );
  218. } else {
  219. $result = $conn->connect( $host, $port, $this->connectTimeout );
  220. }
  221. if ( !$result ) {
  222. $logger->error(
  223. 'Could not connect to server "{redis_server}"',
  224. [ 'redis_server' => $server ]
  225. );
  226. // Mark server down for some time to avoid further timeouts
  227. $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
  228. return false;
  229. }
  230. if ( ( $this->password !== null ) && !$conn->auth( $this->password ) ) {
  231. $logger->error(
  232. 'Authentication error connecting to "{redis_server}"',
  233. [ 'redis_server' => $server ]
  234. );
  235. }
  236. } catch ( RedisException $e ) {
  237. $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
  238. $logger->error(
  239. 'Redis exception connecting to "{redis_server}"',
  240. [
  241. 'redis_server' => $server,
  242. 'exception' => $e,
  243. ]
  244. );
  245. return false;
  246. }
  247. if ( $conn ) {
  248. $conn->setOption( Redis::OPT_READ_TIMEOUT, $this->readTimeout );
  249. $conn->setOption( Redis::OPT_SERIALIZER, $this->serializer );
  250. $this->connections[$server][] = [ 'conn' => $conn, 'free' => false ];
  251. return new RedisConnRef( $this, $server, $conn, $logger );
  252. } else {
  253. return false;
  254. }
  255. }
  256. /**
  257. * Mark a connection to a server as free to return to the pool
  258. *
  259. * @param string $server
  260. * @param Redis $conn
  261. * @return bool
  262. */
  263. public function freeConnection( $server, Redis $conn ) {
  264. $found = false;
  265. foreach ( $this->connections[$server] as &$connection ) {
  266. if ( $connection['conn'] === $conn && !$connection['free'] ) {
  267. $connection['free'] = true;
  268. ++$this->idlePoolSize;
  269. break;
  270. }
  271. }
  272. $this->closeExcessIdleConections();
  273. return $found;
  274. }
  275. /**
  276. * Close any extra idle connections if there are more than the limit
  277. */
  278. protected function closeExcessIdleConections() {
  279. if ( $this->idlePoolSize <= count( $this->connections ) ) {
  280. return; // nothing to do (no more connections than servers)
  281. }
  282. foreach ( $this->connections as &$serverConnections ) {
  283. foreach ( $serverConnections as $key => &$connection ) {
  284. if ( $connection['free'] ) {
  285. unset( $serverConnections[$key] );
  286. if ( --$this->idlePoolSize <= count( $this->connections ) ) {
  287. return; // done (no more connections than servers)
  288. }
  289. }
  290. }
  291. }
  292. }
  293. /**
  294. * The redis extension throws an exception in response to various read, write
  295. * and protocol errors. Sometimes it also closes the connection, sometimes
  296. * not. The safest response for us is to explicitly destroy the connection
  297. * object and let it be reopened during the next request.
  298. *
  299. * @param RedisConnRef $cref
  300. * @param RedisException $e
  301. */
  302. public function handleError( RedisConnRef $cref, RedisException $e ) {
  303. $server = $cref->getServer();
  304. $this->logger->error(
  305. 'Redis exception on server "{redis_server}"',
  306. [
  307. 'redis_server' => $server,
  308. 'exception' => $e,
  309. ]
  310. );
  311. foreach ( $this->connections[$server] as $key => $connection ) {
  312. if ( $cref->isConnIdentical( $connection['conn'] ) ) {
  313. $this->idlePoolSize -= $connection['free'] ? 1 : 0;
  314. unset( $this->connections[$server][$key] );
  315. break;
  316. }
  317. }
  318. }
  319. /**
  320. * Re-send an AUTH request to the redis server (useful after disconnects).
  321. *
  322. * This works around an upstream bug in phpredis. phpredis hides disconnects by transparently
  323. * reconnecting, but it neglects to re-authenticate the new connection. To the user of the
  324. * phpredis client API this manifests as a seemingly random tendency of connections to lose
  325. * their authentication status.
  326. *
  327. * This method is for internal use only.
  328. *
  329. * @see https://github.com/nicolasff/phpredis/issues/403
  330. *
  331. * @param string $server
  332. * @param Redis $conn
  333. * @return bool Success
  334. */
  335. public function reauthenticateConnection( $server, Redis $conn ) {
  336. if ( $this->password !== null && !$conn->auth( $this->password ) ) {
  337. $this->logger->error(
  338. 'Authentication error connecting to "{redis_server}"',
  339. [ 'redis_server' => $server ]
  340. );
  341. return false;
  342. }
  343. return true;
  344. }
  345. /**
  346. * Adjust or reset the connection handle read timeout value
  347. *
  348. * @param Redis $conn
  349. * @param int|null $timeout Optional
  350. */
  351. public function resetTimeout( Redis $conn, $timeout = null ) {
  352. $conn->setOption( Redis::OPT_READ_TIMEOUT, $timeout ?: $this->readTimeout );
  353. }
  354. /**
  355. * Make sure connections are closed for sanity
  356. */
  357. function __destruct() {
  358. foreach ( $this->connections as $server => &$serverConnections ) {
  359. foreach ( $serverConnections as $key => &$connection ) {
  360. try {
  361. /** @var Redis $conn */
  362. $conn = $connection['conn'];
  363. $conn->close();
  364. } catch ( RedisException $e ) {
  365. // The destructor can be called on shutdown when random parts of the system
  366. // have been destructed already, causing weird errors. Ignore them.
  367. }
  368. }
  369. }
  370. }
  371. }