RedisCluster.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.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 Predis\Connection\Aggregate;
  11. use Predis\Cluster\RedisStrategy as RedisClusterStrategy;
  12. use Predis\Cluster\StrategyInterface;
  13. use Predis\Command\CommandInterface;
  14. use Predis\Command\RawCommand;
  15. use Predis\Connection\FactoryInterface;
  16. use Predis\Connection\NodeConnectionInterface;
  17. use Predis\NotSupportedException;
  18. use Predis\Response\ErrorInterface as ErrorResponseInterface;
  19. /**
  20. * Abstraction for a Redis-backed cluster of nodes (Redis >= 3.0.0).
  21. *
  22. * This connection backend offers smart support for redis-cluster by handling
  23. * automatic slots map (re)generation upon -MOVED or -ASK responses returned by
  24. * Redis when redirecting a client to a different node.
  25. *
  26. * The cluster can be pre-initialized using only a subset of the actual nodes in
  27. * the cluster, Predis will do the rest by adjusting the slots map and creating
  28. * the missing underlying connection instances on the fly.
  29. *
  30. * It is possible to pre-associate connections to a slots range with the "slots"
  31. * parameter in the form "$first-$last". This can greatly reduce runtime node
  32. * guessing and redirections.
  33. *
  34. * It is also possible to ask for the full and updated slots map directly to one
  35. * of the nodes and optionally enable such a behaviour upon -MOVED redirections.
  36. * Asking for the cluster configuration to Redis is actually done by issuing a
  37. * CLUSTER SLOTS command to a random node in the pool.
  38. *
  39. * @author Daniele Alessandri <suppakilla@gmail.com>
  40. */
  41. class RedisCluster implements ClusterInterface, \IteratorAggregate, \Countable
  42. {
  43. private $useClusterSlots = true;
  44. private $pool = array();
  45. private $slots = array();
  46. private $slotsMap;
  47. private $strategy;
  48. private $connections;
  49. /**
  50. * @param FactoryInterface $connections Optional connection factory.
  51. * @param StrategyInterface $strategy Optional cluster strategy.
  52. */
  53. public function __construct(
  54. FactoryInterface $connections,
  55. StrategyInterface $strategy = null
  56. ) {
  57. $this->connections = $connections;
  58. $this->strategy = $strategy ?: new RedisClusterStrategy();
  59. }
  60. /**
  61. * {@inheritdoc}
  62. */
  63. public function isConnected()
  64. {
  65. foreach ($this->pool as $connection) {
  66. if ($connection->isConnected()) {
  67. return true;
  68. }
  69. }
  70. return false;
  71. }
  72. /**
  73. * {@inheritdoc}
  74. */
  75. public function connect()
  76. {
  77. if ($connection = $this->getRandomConnection()) {
  78. $connection->connect();
  79. }
  80. }
  81. /**
  82. * {@inheritdoc}
  83. */
  84. public function disconnect()
  85. {
  86. foreach ($this->pool as $connection) {
  87. $connection->disconnect();
  88. }
  89. }
  90. /**
  91. * {@inheritdoc}
  92. */
  93. public function add(NodeConnectionInterface $connection)
  94. {
  95. $this->pool[(string) $connection] = $connection;
  96. unset($this->slotsMap);
  97. }
  98. /**
  99. * {@inheritdoc}
  100. */
  101. public function remove(NodeConnectionInterface $connection)
  102. {
  103. if (false !== $id = array_search($connection, $this->pool, true)) {
  104. unset(
  105. $this->pool[$id],
  106. $this->slotsMap
  107. );
  108. return true;
  109. }
  110. return false;
  111. }
  112. /**
  113. * Removes a connection instance by using its identifier.
  114. *
  115. * @param string $connectionID Connection identifier.
  116. *
  117. * @return bool True if the connection was in the pool.
  118. */
  119. public function removeById($connectionID)
  120. {
  121. if (isset($this->pool[$connectionID])) {
  122. unset(
  123. $this->pool[$connectionID],
  124. $this->slotsMap
  125. );
  126. return true;
  127. }
  128. return false;
  129. }
  130. /**
  131. * Generates the current slots map by guessing the cluster configuration out
  132. * of the connection parameters of the connections in the pool.
  133. *
  134. * Generation is based on the same algorithm used by Redis to generate the
  135. * cluster, so it is most effective when all of the connections supplied on
  136. * initialization have the "slots" parameter properly set accordingly to the
  137. * current cluster configuration.
  138. */
  139. public function buildSlotsMap()
  140. {
  141. $this->slotsMap = array();
  142. foreach ($this->pool as $connectionID => $connection) {
  143. $parameters = $connection->getParameters();
  144. if (!isset($parameters->slots)) {
  145. continue;
  146. }
  147. $slots = explode('-', $parameters->slots, 2);
  148. $this->setSlots($slots[0], $slots[1], $connectionID);
  149. }
  150. }
  151. /**
  152. * Generates an updated slots map fetching the cluster configuration using
  153. * the CLUSTER SLOTS command against the specified node or a random one from
  154. * the pool.
  155. *
  156. * @param NodeConnectionInterface $connection Optional connection instance.
  157. *
  158. * @return array
  159. */
  160. public function askSlotsMap(NodeConnectionInterface $connection = null)
  161. {
  162. if (!$connection && !$connection = $this->getRandomConnection()) {
  163. return array();
  164. }
  165. $command = RawCommand::create('CLUSTER', 'SLOTS');
  166. $response = $connection->executeCommand($command);
  167. foreach ($response as $slots) {
  168. // We only support master servers for now, so we ignore subsequent
  169. // elements in the $slots array identifying slaves.
  170. list($start, $end, $master) = $slots;
  171. if ($master[0] === '') {
  172. $this->setSlots($start, $end, (string) $connection);
  173. } else {
  174. $this->setSlots($start, $end, "{$master[0]}:{$master[1]}");
  175. }
  176. }
  177. return $this->slotsMap;
  178. }
  179. /**
  180. * Returns the current slots map for the cluster.
  181. *
  182. * @return array
  183. */
  184. public function getSlotsMap()
  185. {
  186. if (!isset($this->slotsMap)) {
  187. $this->slotsMap = array();
  188. }
  189. return $this->slotsMap;
  190. }
  191. /**
  192. * Pre-associates a connection to a slots range to avoid runtime guessing.
  193. *
  194. * @param int $first Initial slot of the range.
  195. * @param int $last Last slot of the range.
  196. * @param NodeConnectionInterface|string $connection ID or connection instance.
  197. *
  198. * @throws \OutOfBoundsException
  199. */
  200. public function setSlots($first, $last, $connection)
  201. {
  202. if ($first < 0x0000 || $first > 0x3FFF ||
  203. $last < 0x0000 || $last > 0x3FFF ||
  204. $last < $first
  205. ) {
  206. throw new \OutOfBoundsException(
  207. "Invalid slot range for $connection: [$first-$last]."
  208. );
  209. }
  210. $slots = array_fill($first, $last - $first + 1, (string) $connection);
  211. $this->slotsMap = $this->getSlotsMap() + $slots;
  212. }
  213. /**
  214. * Guesses the correct node associated to a given slot using a precalculated
  215. * slots map, falling back to the same logic used by Redis to initialize a
  216. * cluster (best-effort).
  217. *
  218. * @param int $slot Slot index.
  219. *
  220. * @return string Connection ID.
  221. */
  222. protected function guessNode($slot)
  223. {
  224. if (!isset($this->slotsMap)) {
  225. $this->buildSlotsMap();
  226. }
  227. if (isset($this->slotsMap[$slot])) {
  228. return $this->slotsMap[$slot];
  229. }
  230. $count = count($this->pool);
  231. $index = min((int) ($slot / (int) (16384 / $count)), $count - 1);
  232. $nodes = array_keys($this->pool);
  233. return $nodes[$index];
  234. }
  235. /**
  236. * Creates a new connection instance from the given connection ID.
  237. *
  238. * @param string $connectionID Identifier for the connection.
  239. *
  240. * @return NodeConnectionInterface
  241. */
  242. protected function createConnection($connectionID)
  243. {
  244. $host = explode(':', $connectionID, 2);
  245. return $this->connections->create(array(
  246. 'host' => $host[0],
  247. 'port' => $host[1],
  248. ));
  249. }
  250. /**
  251. * {@inheritdoc}
  252. */
  253. public function getConnection(CommandInterface $command)
  254. {
  255. $slot = $this->strategy->getSlot($command);
  256. if (!isset($slot)) {
  257. throw new NotSupportedException(
  258. "Cannot use '{$command->getId()}' with redis-cluster."
  259. );
  260. }
  261. if (isset($this->slots[$slot])) {
  262. return $this->slots[$slot];
  263. } else {
  264. return $this->getConnectionBySlot($slot);
  265. }
  266. }
  267. /**
  268. * Returns the connection currently associated to a given slot.
  269. *
  270. * @param int $slot Slot index.
  271. *
  272. * @throws \OutOfBoundsException
  273. *
  274. * @return NodeConnectionInterface
  275. */
  276. public function getConnectionBySlot($slot)
  277. {
  278. if ($slot < 0x0000 || $slot > 0x3FFF) {
  279. throw new \OutOfBoundsException("Invalid slot [$slot].");
  280. }
  281. if (isset($this->slots[$slot])) {
  282. return $this->slots[$slot];
  283. }
  284. $connectionID = $this->guessNode($slot);
  285. if (!$connection = $this->getConnectionById($connectionID)) {
  286. $connection = $this->createConnection($connectionID);
  287. $this->pool[$connectionID] = $connection;
  288. }
  289. return $this->slots[$slot] = $connection;
  290. }
  291. /**
  292. * {@inheritdoc}
  293. */
  294. public function getConnectionById($connectionID)
  295. {
  296. if (isset($this->pool[$connectionID])) {
  297. return $this->pool[$connectionID];
  298. }
  299. }
  300. /**
  301. * Returns a random connection from the pool.
  302. *
  303. * @return NodeConnectionInterface|null
  304. */
  305. protected function getRandomConnection()
  306. {
  307. if ($this->pool) {
  308. return $this->pool[array_rand($this->pool)];
  309. }
  310. }
  311. /**
  312. * Permanently associates the connection instance to a new slot.
  313. * The connection is added to the connections pool if not yet included.
  314. *
  315. * @param NodeConnectionInterface $connection Connection instance.
  316. * @param int $slot Target slot index.
  317. */
  318. protected function move(NodeConnectionInterface $connection, $slot)
  319. {
  320. $this->pool[(string) $connection] = $connection;
  321. $this->slots[(int) $slot] = $connection;
  322. }
  323. /**
  324. * Handles -ERR responses returned by Redis.
  325. *
  326. * @param CommandInterface $command Command that generated the -ERR response.
  327. * @param ErrorResponseInterface $error Redis error response object.
  328. *
  329. * @return mixed
  330. */
  331. protected function onErrorResponse(CommandInterface $command, ErrorResponseInterface $error)
  332. {
  333. $details = explode(' ', $error->getMessage(), 2);
  334. switch ($details[0]) {
  335. case 'MOVED':
  336. return $this->onMovedResponse($command, $details[1]);
  337. case 'ASK':
  338. return $this->onAskResponse($command, $details[1]);
  339. default:
  340. return $error;
  341. }
  342. }
  343. /**
  344. * Handles -MOVED responses by executing again the command against the node
  345. * indicated by the Redis response.
  346. *
  347. * @param CommandInterface $command Command that generated the -MOVED response.
  348. * @param string $details Parameters of the -MOVED response.
  349. *
  350. * @return mixed
  351. */
  352. protected function onMovedResponse(CommandInterface $command, $details)
  353. {
  354. list($slot, $connectionID) = explode(' ', $details, 2);
  355. if (!$connection = $this->getConnectionById($connectionID)) {
  356. $connection = $this->createConnection($connectionID);
  357. }
  358. if ($this->useClusterSlots) {
  359. $this->askSlotsMap($connection);
  360. }
  361. $this->move($connection, $slot);
  362. $response = $this->executeCommand($command);
  363. return $response;
  364. }
  365. /**
  366. * Handles -ASK responses by executing again the command against the node
  367. * indicated by the Redis response.
  368. *
  369. * @param CommandInterface $command Command that generated the -ASK response.
  370. * @param string $details Parameters of the -ASK response.
  371. *
  372. * @return mixed
  373. */
  374. protected function onAskResponse(CommandInterface $command, $details)
  375. {
  376. list($slot, $connectionID) = explode(' ', $details, 2);
  377. if (!$connection = $this->getConnectionById($connectionID)) {
  378. $connection = $this->createConnection($connectionID);
  379. }
  380. $connection->executeCommand(RawCommand::create('ASKING'));
  381. $response = $connection->executeCommand($command);
  382. return $response;
  383. }
  384. /**
  385. * {@inheritdoc}
  386. */
  387. public function writeRequest(CommandInterface $command)
  388. {
  389. $this->getConnection($command)->writeRequest($command);
  390. }
  391. /**
  392. * {@inheritdoc}
  393. */
  394. public function readResponse(CommandInterface $command)
  395. {
  396. return $this->getConnection($command)->readResponse($command);
  397. }
  398. /**
  399. * {@inheritdoc}
  400. */
  401. public function executeCommand(CommandInterface $command)
  402. {
  403. $connection = $this->getConnection($command);
  404. $response = $connection->executeCommand($command);
  405. if ($response instanceof ErrorResponseInterface) {
  406. return $this->onErrorResponse($command, $response);
  407. }
  408. return $response;
  409. }
  410. /**
  411. * {@inheritdoc}
  412. */
  413. public function count()
  414. {
  415. return count($this->pool);
  416. }
  417. /**
  418. * {@inheritdoc}
  419. */
  420. public function getIterator()
  421. {
  422. return new \ArrayIterator(array_values($this->pool));
  423. }
  424. /**
  425. * Returns the underlying command hash strategy used to hash commands by
  426. * using keys found in their arguments.
  427. *
  428. * @return StrategyInterface
  429. */
  430. public function getClusterStrategy()
  431. {
  432. return $this->strategy;
  433. }
  434. /**
  435. * Returns the underlying connection factory used to create new connection
  436. * instances to Redis nodes indicated by redis-cluster.
  437. *
  438. * @return FactoryInterface
  439. */
  440. public function getConnectionFactory()
  441. {
  442. return $this->connections;
  443. }
  444. /**
  445. * Enables automatic fetching of the current slots map from one of the nodes
  446. * using the CLUSTER SLOTS command. This option is disabled by default but
  447. * asking the current slots map to Redis upon -MOVED responses may reduce
  448. * overhead by eliminating the trial-and-error nature of the node guessing
  449. * procedure, mostly when targeting many keys that would end up in a lot of
  450. * redirections.
  451. *
  452. * The slots map can still be manually fetched using the askSlotsMap()
  453. * method whether or not this option is enabled.
  454. *
  455. * @param bool $value Enable or disable the use of CLUSTER SLOTS.
  456. */
  457. public function useClusterSlots($value)
  458. {
  459. $this->useClusterSlots = (bool) $value;
  460. }
  461. }