RedisTrait.php 22 KB

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