RedisTrait.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Cache\Traits;
  11. use Predis\Connection\Aggregate\ClusterInterface;
  12. use Predis\Connection\Aggregate\RedisCluster;
  13. use Predis\Response\Status;
  14. use Symfony\Component\Cache\Exception\CacheException;
  15. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  16. use Symfony\Component\Cache\Marshaller\DefaultMarshaller;
  17. use Symfony\Component\Cache\Marshaller\MarshallerInterface;
  18. /**
  19. * @author Aurimas Niekis <aurimas@niekis.lt>
  20. * @author Nicolas Grekas <p@tchwork.com>
  21. *
  22. * @internal
  23. */
  24. trait RedisTrait
  25. {
  26. private static $defaultConnectionOptions = [
  27. 'class' => null,
  28. 'persistent' => 0,
  29. 'persistent_id' => null,
  30. 'timeout' => 30,
  31. 'read_timeout' => 0,
  32. 'retry_interval' => 0,
  33. 'tcp_keepalive' => 0,
  34. 'lazy' => null,
  35. 'redis_cluster' => false,
  36. 'redis_sentinel' => null,
  37. 'dbindex' => 0,
  38. 'failover' => 'none',
  39. ];
  40. private $redis;
  41. private $marshaller;
  42. /**
  43. * @param \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface $redisClient
  44. */
  45. private function init($redisClient, string $namespace, int $defaultLifetime, ?MarshallerInterface $marshaller)
  46. {
  47. parent::__construct($namespace, $defaultLifetime);
  48. if (preg_match('#[^-+_.A-Za-z0-9]#', $namespace, $match)) {
  49. throw new InvalidArgumentException(sprintf('RedisAdapter namespace contains "%s" but only characters in [-+_.A-Za-z0-9] are allowed.', $match[0]));
  50. }
  51. if (!$redisClient instanceof \Redis && !$redisClient instanceof \RedisArray && !$redisClient instanceof \RedisCluster && !$redisClient instanceof \Predis\ClientInterface && !$redisClient instanceof RedisProxy && !$redisClient instanceof RedisClusterProxy) {
  52. throw new InvalidArgumentException(sprintf('"%s()" expects parameter 1 to be Redis, RedisArray, RedisCluster or Predis\ClientInterface, "%s" given.', __METHOD__, \is_object($redisClient) ? \get_class($redisClient) : \gettype($redisClient)));
  53. }
  54. if ($redisClient instanceof \Predis\ClientInterface && $redisClient->getOptions()->exceptions) {
  55. $options = clone $redisClient->getOptions();
  56. \Closure::bind(function () { $this->options['exceptions'] = false; }, $options, $options)();
  57. $redisClient = new $redisClient($redisClient->getConnection(), $options);
  58. }
  59. $this->redis = $redisClient;
  60. $this->marshaller = $marshaller ?? new DefaultMarshaller();
  61. }
  62. /**
  63. * Creates a Redis connection using a DSN configuration.
  64. *
  65. * Example DSN:
  66. * - redis://localhost
  67. * - redis://example.com:1234
  68. * - redis://secret@example.com/13
  69. * - redis:///var/run/redis.sock
  70. * - redis://secret@/var/run/redis.sock/13
  71. *
  72. * @param string $dsn
  73. * @param array $options See self::$defaultConnectionOptions
  74. *
  75. * @throws InvalidArgumentException when the DSN is invalid
  76. *
  77. * @return \Redis|\RedisCluster|RedisClusterProxy|RedisProxy|\Predis\ClientInterface According to the "class" option
  78. */
  79. public static function createConnection($dsn, array $options = [])
  80. {
  81. if (0 === strpos($dsn, 'redis:')) {
  82. $scheme = 'redis';
  83. } elseif (0 === strpos($dsn, 'rediss:')) {
  84. $scheme = 'rediss';
  85. } else {
  86. throw new InvalidArgumentException(sprintf('Invalid Redis DSN: "%s" does not start with "redis:" or "rediss".', $dsn));
  87. }
  88. if (!\extension_loaded('redis') && !class_exists(\Predis\Client::class)) {
  89. throw new CacheException(sprintf('Cannot find the "redis" extension nor the "predis/predis" package: "%s".', $dsn));
  90. }
  91. $params = preg_replace_callback('#^'.$scheme.':(//)?(?:(?:[^:@]*+:)?([^@]*+)@)?#', function ($m) use (&$auth) {
  92. if (isset($m[2])) {
  93. $auth = $m[2];
  94. if ('' === $auth) {
  95. $auth = null;
  96. }
  97. }
  98. return 'file:'.($m[1] ?? '');
  99. }, $dsn);
  100. if (false === $params = parse_url($params)) {
  101. throw new InvalidArgumentException(sprintf('Invalid Redis DSN: "%s".', $dsn));
  102. }
  103. $query = $hosts = [];
  104. if (isset($params['query'])) {
  105. parse_str($params['query'], $query);
  106. if (isset($query['host'])) {
  107. if (!\is_array($hosts = $query['host'])) {
  108. throw new InvalidArgumentException(sprintf('Invalid Redis DSN: "%s".', $dsn));
  109. }
  110. foreach ($hosts as $host => $parameters) {
  111. if (\is_string($parameters)) {
  112. parse_str($parameters, $parameters);
  113. }
  114. if (false === $i = strrpos($host, ':')) {
  115. $hosts[$host] = ['scheme' => 'tcp', 'host' => $host, 'port' => 6379] + $parameters;
  116. } elseif ($port = (int) substr($host, 1 + $i)) {
  117. $hosts[$host] = ['scheme' => 'tcp', 'host' => substr($host, 0, $i), 'port' => $port] + $parameters;
  118. } else {
  119. $hosts[$host] = ['scheme' => 'unix', 'path' => substr($host, 0, $i)] + $parameters;
  120. }
  121. }
  122. $hosts = array_values($hosts);
  123. }
  124. }
  125. if (isset($params['host']) || isset($params['path'])) {
  126. if (!isset($params['dbindex']) && isset($params['path']) && preg_match('#/(\d+)$#', $params['path'], $m)) {
  127. $params['dbindex'] = $m[1];
  128. $params['path'] = substr($params['path'], 0, -\strlen($m[0]));
  129. }
  130. if (isset($params['host'])) {
  131. array_unshift($hosts, ['scheme' => 'tcp', 'host' => $params['host'], 'port' => $params['port'] ?? 6379]);
  132. } else {
  133. array_unshift($hosts, ['scheme' => 'unix', 'path' => $params['path']]);
  134. }
  135. }
  136. if (!$hosts) {
  137. throw new InvalidArgumentException(sprintf('Invalid Redis DSN: "%s".', $dsn));
  138. }
  139. if (isset($params['redis_sentinel']) && !class_exists(\Predis\Client::class)) {
  140. throw new CacheException(sprintf('Redis Sentinel support requires the "predis/predis" package: "%s".', $dsn));
  141. }
  142. $params += $query + $options + self::$defaultConnectionOptions;
  143. if (null === $params['class'] && !isset($params['redis_sentinel']) && \extension_loaded('redis')) {
  144. $class = $params['redis_cluster'] ? \RedisCluster::class : (1 < \count($hosts) ? \RedisArray::class : \Redis::class);
  145. } else {
  146. $class = null === $params['class'] ? \Predis\Client::class : $params['class'];
  147. }
  148. if (is_a($class, \Redis::class, true)) {
  149. $connect = $params['persistent'] || $params['persistent_id'] ? 'pconnect' : 'connect';
  150. $redis = new $class();
  151. $initializer = function ($redis) use ($connect, $params, $dsn, $auth, $hosts) {
  152. try {
  153. @$redis->{$connect}($hosts[0]['host'] ?? $hosts[0]['path'], $hosts[0]['port'] ?? null, $params['timeout'], (string) $params['persistent_id'], $params['retry_interval']);
  154. set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
  155. $isConnected = $redis->isConnected();
  156. restore_error_handler();
  157. if (!$isConnected) {
  158. $error = preg_match('/^Redis::p?connect\(\): (.*)/', $error, $error) ? sprintf(' (%s)', $error[1]) : '';
  159. throw new InvalidArgumentException(sprintf('Redis connection "%s" failed: ', $dsn).$error.'.');
  160. }
  161. if ((null !== $auth && !$redis->auth($auth))
  162. || ($params['dbindex'] && !$redis->select($params['dbindex']))
  163. || ($params['read_timeout'] && !$redis->setOption(\Redis::OPT_READ_TIMEOUT, $params['read_timeout']))
  164. ) {
  165. $e = preg_replace('/^ERR /', '', $redis->getLastError());
  166. throw new InvalidArgumentException(sprintf('Redis connection "%s" failed: ', $dsn).$e.'.');
  167. }
  168. if (0 < $params['tcp_keepalive'] && \defined('Redis::OPT_TCP_KEEPALIVE')) {
  169. $redis->setOption(\Redis::OPT_TCP_KEEPALIVE, $params['tcp_keepalive']);
  170. }
  171. } catch (\RedisException $e) {
  172. throw new InvalidArgumentException(sprintf('Redis connection "%s" failed: ', $dsn).$e->getMessage());
  173. }
  174. return true;
  175. };
  176. if ($params['lazy']) {
  177. $redis = new RedisProxy($redis, $initializer);
  178. } else {
  179. $initializer($redis);
  180. }
  181. } elseif (is_a($class, \RedisArray::class, true)) {
  182. foreach ($hosts as $i => $host) {
  183. $hosts[$i] = 'tcp' === $host['scheme'] ? $host['host'].':'.$host['port'] : $host['path'];
  184. }
  185. $params['lazy_connect'] = $params['lazy'] ?? true;
  186. $params['connect_timeout'] = $params['timeout'];
  187. try {
  188. $redis = new $class($hosts, $params);
  189. } catch (\RedisClusterException $e) {
  190. throw new InvalidArgumentException(sprintf('Redis connection "%s" failed: ', $dsn).$e->getMessage());
  191. }
  192. if (0 < $params['tcp_keepalive'] && \defined('Redis::OPT_TCP_KEEPALIVE')) {
  193. $redis->setOption(\Redis::OPT_TCP_KEEPALIVE, $params['tcp_keepalive']);
  194. }
  195. } elseif (is_a($class, \RedisCluster::class, true)) {
  196. $initializer = function () use ($class, $params, $dsn, $hosts) {
  197. foreach ($hosts as $i => $host) {
  198. $hosts[$i] = 'tcp' === $host['scheme'] ? $host['host'].':'.$host['port'] : $host['path'];
  199. }
  200. try {
  201. $redis = new $class(null, $hosts, $params['timeout'], $params['read_timeout'], (bool) $params['persistent'], $params['auth'] ?? '');
  202. } catch (\RedisClusterException $e) {
  203. throw new InvalidArgumentException(sprintf('Redis connection "%s" failed: ', $dsn).$e->getMessage());
  204. }
  205. if (0 < $params['tcp_keepalive'] && \defined('Redis::OPT_TCP_KEEPALIVE')) {
  206. $redis->setOption(\Redis::OPT_TCP_KEEPALIVE, $params['tcp_keepalive']);
  207. }
  208. switch ($params['failover']) {
  209. case 'error': $redis->setOption(\RedisCluster::OPT_SLAVE_FAILOVER, \RedisCluster::FAILOVER_ERROR); break;
  210. case 'distribute': $redis->setOption(\RedisCluster::OPT_SLAVE_FAILOVER, \RedisCluster::FAILOVER_DISTRIBUTE); break;
  211. case 'slaves': $redis->setOption(\RedisCluster::OPT_SLAVE_FAILOVER, \RedisCluster::FAILOVER_DISTRIBUTE_SLAVES); break;
  212. }
  213. return $redis;
  214. };
  215. $redis = $params['lazy'] ? new RedisClusterProxy($initializer) : $initializer();
  216. } elseif (is_a($class, \Predis\ClientInterface::class, true)) {
  217. if ($params['redis_cluster']) {
  218. $params['cluster'] = 'redis';
  219. if (isset($params['redis_sentinel'])) {
  220. throw new InvalidArgumentException(sprintf('Cannot use both "redis_cluster" and "redis_sentinel" at the same time: "%s".', $dsn));
  221. }
  222. } elseif (isset($params['redis_sentinel'])) {
  223. $params['replication'] = 'sentinel';
  224. $params['service'] = $params['redis_sentinel'];
  225. }
  226. $params += ['parameters' => []];
  227. $params['parameters'] += [
  228. 'persistent' => $params['persistent'],
  229. 'timeout' => $params['timeout'],
  230. 'read_write_timeout' => $params['read_timeout'],
  231. 'tcp_nodelay' => true,
  232. ];
  233. if ($params['dbindex']) {
  234. $params['parameters']['database'] = $params['dbindex'];
  235. }
  236. if (null !== $auth) {
  237. $params['parameters']['password'] = $auth;
  238. }
  239. if (1 === \count($hosts) && !($params['redis_cluster'] || $params['redis_sentinel'])) {
  240. $hosts = $hosts[0];
  241. } elseif (\in_array($params['failover'], ['slaves', 'distribute'], true) && !isset($params['replication'])) {
  242. $params['replication'] = true;
  243. $hosts[0] += ['alias' => 'master'];
  244. }
  245. $params['exceptions'] = false;
  246. $redis = new $class($hosts, array_diff_key($params, self::$defaultConnectionOptions));
  247. if (isset($params['redis_sentinel'])) {
  248. $redis->getConnection()->setSentinelTimeout($params['timeout']);
  249. }
  250. } elseif (class_exists($class, false)) {
  251. throw new InvalidArgumentException(sprintf('"%s" is not a subclass of "Redis", "RedisArray", "RedisCluster" nor "Predis\ClientInterface".', $class));
  252. } else {
  253. throw new InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
  254. }
  255. return $redis;
  256. }
  257. /**
  258. * {@inheritdoc}
  259. */
  260. protected function doFetch(array $ids)
  261. {
  262. if (!$ids) {
  263. return [];
  264. }
  265. $result = [];
  266. if ($this->redis instanceof \Predis\ClientInterface && $this->redis->getConnection() instanceof ClusterInterface) {
  267. $values = $this->pipeline(function () use ($ids) {
  268. foreach ($ids as $id) {
  269. yield 'get' => [$id];
  270. }
  271. });
  272. } else {
  273. $values = $this->redis->mget($ids);
  274. if (!\is_array($values) || \count($values) !== \count($ids)) {
  275. return [];
  276. }
  277. $values = array_combine($ids, $values);
  278. }
  279. foreach ($values as $id => $v) {
  280. if ($v) {
  281. $result[$id] = $this->marshaller->unmarshall($v);
  282. }
  283. }
  284. return $result;
  285. }
  286. /**
  287. * {@inheritdoc}
  288. */
  289. protected function doHave($id)
  290. {
  291. return (bool) $this->redis->exists($id);
  292. }
  293. /**
  294. * {@inheritdoc}
  295. */
  296. protected function doClear($namespace)
  297. {
  298. $cleared = true;
  299. if ($this->redis instanceof \Predis\ClientInterface) {
  300. $evalArgs = [0, $namespace];
  301. } else {
  302. $evalArgs = [[$namespace], 0];
  303. }
  304. foreach ($this->getHosts() as $host) {
  305. if (!isset($namespace[0])) {
  306. $cleared = $host->flushDb() && $cleared;
  307. continue;
  308. }
  309. $info = $host->info('Server');
  310. $info = isset($info['Server']) ? $info['Server'] : $info;
  311. if (!version_compare($info['redis_version'], '2.8', '>=')) {
  312. // As documented in Redis documentation (http://redis.io/commands/keys) using KEYS
  313. // can hang your server when it is executed against large databases (millions of items).
  314. // Whenever you hit this scale, you should really consider upgrading to Redis 2.8 or above.
  315. $cleared = $host->eval("local keys=redis.call('KEYS',ARGV[1]..'*') for i=1,#keys,5000 do redis.call('DEL',unpack(keys,i,math.min(i+4999,#keys))) end return 1", $evalArgs[0], $evalArgs[1]) && $cleared;
  316. continue;
  317. }
  318. $cursor = null;
  319. do {
  320. $keys = $host instanceof \Predis\ClientInterface ? $host->scan($cursor, 'MATCH', $namespace.'*', 'COUNT', 1000) : $host->scan($cursor, $namespace.'*', 1000);
  321. if (isset($keys[1]) && \is_array($keys[1])) {
  322. $cursor = $keys[0];
  323. $keys = $keys[1];
  324. }
  325. if ($keys) {
  326. $this->doDelete($keys);
  327. }
  328. } while ($cursor = (int) $cursor);
  329. }
  330. return $cleared;
  331. }
  332. /**
  333. * {@inheritdoc}
  334. */
  335. protected function doDelete(array $ids)
  336. {
  337. if (!$ids) {
  338. return true;
  339. }
  340. if ($this->redis instanceof \Predis\ClientInterface && $this->redis->getConnection() instanceof ClusterInterface) {
  341. $this->pipeline(function () use ($ids) {
  342. foreach ($ids as $id) {
  343. yield 'del' => [$id];
  344. }
  345. })->rewind();
  346. } else {
  347. $this->redis->del($ids);
  348. }
  349. return true;
  350. }
  351. /**
  352. * {@inheritdoc}
  353. */
  354. protected function doSave(array $values, int $lifetime)
  355. {
  356. if (!$values = $this->marshaller->marshall($values, $failed)) {
  357. return $failed;
  358. }
  359. $results = $this->pipeline(function () use ($values, $lifetime) {
  360. foreach ($values as $id => $value) {
  361. if (0 >= $lifetime) {
  362. yield 'set' => [$id, $value];
  363. } else {
  364. yield 'setEx' => [$id, $lifetime, $value];
  365. }
  366. }
  367. });
  368. foreach ($results as $id => $result) {
  369. if (true !== $result && (!$result instanceof Status || Status::get('OK') !== $result)) {
  370. $failed[] = $id;
  371. }
  372. }
  373. return $failed;
  374. }
  375. private function pipeline(\Closure $generator, $redis = null): \Generator
  376. {
  377. $ids = [];
  378. $redis = $redis ?? $this->redis;
  379. if ($redis instanceof RedisClusterProxy || $redis instanceof \RedisCluster || ($redis instanceof \Predis\ClientInterface && $redis->getConnection() instanceof RedisCluster)) {
  380. // phpredis & predis don't support pipelining with RedisCluster
  381. // see https://github.com/phpredis/phpredis/blob/develop/cluster.markdown#pipelining
  382. // see https://github.com/nrk/predis/issues/267#issuecomment-123781423
  383. $results = [];
  384. foreach ($generator() as $command => $args) {
  385. $results[] = $redis->{$command}(...$args);
  386. $ids[] = 'eval' === $command ? ($redis instanceof \Predis\ClientInterface ? $args[2] : $args[1][0]) : $args[0];
  387. }
  388. } elseif ($redis instanceof \Predis\ClientInterface) {
  389. $results = $redis->pipeline(static function ($redis) use ($generator, &$ids) {
  390. foreach ($generator() as $command => $args) {
  391. $redis->{$command}(...$args);
  392. $ids[] = 'eval' === $command ? $args[2] : $args[0];
  393. }
  394. });
  395. } elseif ($redis instanceof \RedisArray) {
  396. $connections = $results = $ids = [];
  397. foreach ($generator() as $command => $args) {
  398. $id = 'eval' === $command ? $args[1][0] : $args[0];
  399. if (!isset($connections[$h = $redis->_target($id)])) {
  400. $connections[$h] = [$redis->_instance($h), -1];
  401. $connections[$h][0]->multi(\Redis::PIPELINE);
  402. }
  403. $connections[$h][0]->{$command}(...$args);
  404. $results[] = [$h, ++$connections[$h][1]];
  405. $ids[] = $id;
  406. }
  407. foreach ($connections as $h => $c) {
  408. $connections[$h] = $c[0]->exec();
  409. }
  410. foreach ($results as $k => list($h, $c)) {
  411. $results[$k] = $connections[$h][$c];
  412. }
  413. } else {
  414. $redis->multi(\Redis::PIPELINE);
  415. foreach ($generator() as $command => $args) {
  416. $redis->{$command}(...$args);
  417. $ids[] = 'eval' === $command ? $args[1][0] : $args[0];
  418. }
  419. $results = $redis->exec();
  420. }
  421. foreach ($ids as $k => $id) {
  422. yield $id => $results[$k];
  423. }
  424. }
  425. private function getHosts(): array
  426. {
  427. $hosts = [$this->redis];
  428. if ($this->redis instanceof \Predis\ClientInterface) {
  429. $connection = $this->redis->getConnection();
  430. if ($connection instanceof ClusterInterface && $connection instanceof \Traversable) {
  431. $hosts = [];
  432. foreach ($connection as $c) {
  433. $hosts[] = new \Predis\Client($c);
  434. }
  435. }
  436. } elseif ($this->redis instanceof \RedisArray) {
  437. $hosts = [];
  438. foreach ($this->redis->_hosts() as $host) {
  439. $hosts[] = $this->redis->_instance($host);
  440. }
  441. } elseif ($this->redis instanceof RedisClusterProxy || $this->redis instanceof \RedisCluster) {
  442. $hosts = [];
  443. foreach ($this->redis->_masters() as $host) {
  444. $hosts[] = $h = new \Redis();
  445. $h->connect($host[0], $host[1]);
  446. }
  447. }
  448. return $hosts;
  449. }
  450. }