RedisCluster.php 13 KB

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