RedisTrait.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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\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__, get_debug_type($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. if (isset($params['query'])) {
  106. parse_str($params['query'], $query);
  107. if (isset($query['host'])) {
  108. if (!\is_array($hosts = $query['host'])) {
  109. throw new InvalidArgumentException(sprintf('Invalid Redis DSN: "%s".', $dsn));
  110. }
  111. foreach ($hosts as $host => $parameters) {
  112. if (\is_string($parameters)) {
  113. parse_str($parameters, $parameters);
  114. }
  115. if (false === $i = strrpos($host, ':')) {
  116. $hosts[$host] = ['scheme' => 'tcp', 'host' => $host, 'port' => 6379] + $parameters;
  117. } elseif ($port = (int) substr($host, 1 + $i)) {
  118. $hosts[$host] = ['scheme' => 'tcp', 'host' => substr($host, 0, $i), 'port' => $port] + $parameters;
  119. } else {
  120. $hosts[$host] = ['scheme' => 'unix', 'path' => substr($host, 0, $i)] + $parameters;
  121. }
  122. }
  123. $hosts = array_values($hosts);
  124. }
  125. }
  126. if (isset($params['host']) || isset($params['path'])) {
  127. if (!isset($params['dbindex']) && isset($params['path']) && preg_match('#/(\d+)$#', $params['path'], $m)) {
  128. $params['dbindex'] = $m[1];
  129. $params['path'] = substr($params['path'], 0, -\strlen($m[0]));
  130. }
  131. if (isset($params['host'])) {
  132. array_unshift($hosts, ['scheme' => 'tcp', 'host' => $params['host'], 'port' => $params['port'] ?? 6379]);
  133. } else {
  134. array_unshift($hosts, ['scheme' => 'unix', 'path' => $params['path']]);
  135. }
  136. }
  137. if (!$hosts) {
  138. throw new InvalidArgumentException(sprintf('Invalid Redis DSN: "%s".', $dsn));
  139. }
  140. $params += $query + $options + self::$defaultConnectionOptions;
  141. if (isset($params['redis_sentinel']) && !class_exists(\Predis\Client::class)) {
  142. throw new CacheException(sprintf('Redis Sentinel support requires the "predis/predis" package: "%s".', $dsn));
  143. }
  144. if (null === $params['class'] && !isset($params['redis_sentinel']) && \extension_loaded('redis')) {
  145. $class = $params['redis_cluster'] ? \RedisCluster::class : (1 < \count($hosts) ? \RedisArray::class : \Redis::class);
  146. } else {
  147. $class = null === $params['class'] ? \Predis\Client::class : $params['class'];
  148. }
  149. if (is_a($class, \Redis::class, true)) {
  150. $connect = $params['persistent'] || $params['persistent_id'] ? 'pconnect' : 'connect';
  151. $redis = new $class();
  152. $initializer = static function ($redis) use ($connect, $params, $dsn, $auth, $hosts) {
  153. try {
  154. @$redis->{$connect}($hosts[0]['host'] ?? $hosts[0]['path'], $hosts[0]['port'] ?? null, $params['timeout'], (string) $params['persistent_id'], $params['retry_interval'], $params['read_timeout']);
  155. set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
  156. $isConnected = $redis->isConnected();
  157. restore_error_handler();
  158. if (!$isConnected) {
  159. $error = preg_match('/^Redis::p?connect\(\): (.*)/', $error, $error) ? sprintf(' (%s)', $error[1]) : '';
  160. throw new InvalidArgumentException(sprintf('Redis connection "%s" failed: ', $dsn).$error.'.');
  161. }
  162. if ((null !== $auth && !$redis->auth($auth))
  163. || ($params['dbindex'] && !$redis->select($params['dbindex']))
  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 = static 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(string $id)
  290. {
  291. return (bool) $this->redis->exists($id);
  292. }
  293. /**
  294. * {@inheritdoc}
  295. */
  296. protected function doClear(string $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. $unlink = version_compare($info['redis_version'], '4.0', '>=') ? 'UNLINK' : 'DEL';
  316. $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;
  317. continue;
  318. }
  319. $cursor = null;
  320. do {
  321. $keys = $host instanceof \Predis\ClientInterface ? $host->scan($cursor, 'MATCH', $namespace.'*', 'COUNT', 1000) : $host->scan($cursor, $namespace.'*', 1000);
  322. if (isset($keys[1]) && \is_array($keys[1])) {
  323. $cursor = $keys[0];
  324. $keys = $keys[1];
  325. }
  326. if ($keys) {
  327. $this->doDelete($keys);
  328. }
  329. } while ($cursor = (int) $cursor);
  330. }
  331. return $cleared;
  332. }
  333. /**
  334. * {@inheritdoc}
  335. */
  336. protected function doDelete(array $ids)
  337. {
  338. if (!$ids) {
  339. return true;
  340. }
  341. if ($this->redis instanceof \Predis\ClientInterface && $this->redis->getConnection() instanceof ClusterInterface) {
  342. static $del;
  343. $del = $del ?? (class_exists(UNLINK::class) ? 'unlink' : 'del');
  344. $this->pipeline(function () use ($ids, $del) {
  345. foreach ($ids as $id) {
  346. yield $del => [$id];
  347. }
  348. })->rewind();
  349. } else {
  350. static $unlink = true;
  351. if ($unlink) {
  352. try {
  353. $unlink = false !== $this->redis->unlink($ids);
  354. } catch (\Throwable $e) {
  355. $unlink = false;
  356. }
  357. }
  358. if (!$unlink) {
  359. $this->redis->del($ids);
  360. }
  361. }
  362. return true;
  363. }
  364. /**
  365. * {@inheritdoc}
  366. */
  367. protected function doSave(array $values, int $lifetime)
  368. {
  369. if (!$values = $this->marshaller->marshall($values, $failed)) {
  370. return $failed;
  371. }
  372. $results = $this->pipeline(function () use ($values, $lifetime) {
  373. foreach ($values as $id => $value) {
  374. if (0 >= $lifetime) {
  375. yield 'set' => [$id, $value];
  376. } else {
  377. yield 'setEx' => [$id, $lifetime, $value];
  378. }
  379. }
  380. });
  381. foreach ($results as $id => $result) {
  382. if (true !== $result && (!$result instanceof Status || Status::get('OK') !== $result)) {
  383. $failed[] = $id;
  384. }
  385. }
  386. return $failed;
  387. }
  388. private function pipeline(\Closure $generator, $redis = null): \Generator
  389. {
  390. $ids = [];
  391. $redis = $redis ?? $this->redis;
  392. if ($redis instanceof RedisClusterProxy || $redis instanceof \RedisCluster || ($redis instanceof \Predis\ClientInterface && $redis->getConnection() instanceof RedisCluster)) {
  393. // phpredis & predis don't support pipelining with RedisCluster
  394. // see https://github.com/phpredis/phpredis/blob/develop/cluster.markdown#pipelining
  395. // see https://github.com/nrk/predis/issues/267#issuecomment-123781423
  396. $results = [];
  397. foreach ($generator() as $command => $args) {
  398. $results[] = $redis->{$command}(...$args);
  399. $ids[] = 'eval' === $command ? ($redis instanceof \Predis\ClientInterface ? $args[2] : $args[1][0]) : $args[0];
  400. }
  401. } elseif ($redis instanceof \Predis\ClientInterface) {
  402. $results = $redis->pipeline(static function ($redis) use ($generator, &$ids) {
  403. foreach ($generator() as $command => $args) {
  404. $redis->{$command}(...$args);
  405. $ids[] = 'eval' === $command ? $args[2] : $args[0];
  406. }
  407. });
  408. } elseif ($redis instanceof \RedisArray) {
  409. $connections = $results = $ids = [];
  410. foreach ($generator() as $command => $args) {
  411. $id = 'eval' === $command ? $args[1][0] : $args[0];
  412. if (!isset($connections[$h = $redis->_target($id)])) {
  413. $connections[$h] = [$redis->_instance($h), -1];
  414. $connections[$h][0]->multi(\Redis::PIPELINE);
  415. }
  416. $connections[$h][0]->{$command}(...$args);
  417. $results[] = [$h, ++$connections[$h][1]];
  418. $ids[] = $id;
  419. }
  420. foreach ($connections as $h => $c) {
  421. $connections[$h] = $c[0]->exec();
  422. }
  423. foreach ($results as $k => [$h, $c]) {
  424. $results[$k] = $connections[$h][$c];
  425. }
  426. } else {
  427. $redis->multi(\Redis::PIPELINE);
  428. foreach ($generator() as $command => $args) {
  429. $redis->{$command}(...$args);
  430. $ids[] = 'eval' === $command ? $args[1][0] : $args[0];
  431. }
  432. $results = $redis->exec();
  433. }
  434. foreach ($ids as $k => $id) {
  435. yield $id => $results[$k];
  436. }
  437. }
  438. private function getHosts(): array
  439. {
  440. $hosts = [$this->redis];
  441. if ($this->redis instanceof \Predis\ClientInterface) {
  442. $connection = $this->redis->getConnection();
  443. if ($connection instanceof ClusterInterface && $connection instanceof \Traversable) {
  444. $hosts = [];
  445. foreach ($connection as $c) {
  446. $hosts[] = new \Predis\Client($c);
  447. }
  448. }
  449. } elseif ($this->redis instanceof \RedisArray) {
  450. $hosts = [];
  451. foreach ($this->redis->_hosts() as $host) {
  452. $hosts[] = $this->redis->_instance($host);
  453. }
  454. } elseif ($this->redis instanceof RedisClusterProxy || $this->redis instanceof \RedisCluster) {
  455. $hosts = [];
  456. foreach ($this->redis->_masters() as $host) {
  457. $hosts[] = $h = new \Redis();
  458. $h->connect($host[0], $host[1]);
  459. }
  460. }
  461. return $hosts;
  462. }
  463. }