RedisTrait.php 22 KB

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