RedisCluster.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 Predis\ClientException;
  12. use Predis\NotSupportedException;
  13. use Predis\ResponseErrorInterface;
  14. use Predis\Command\CommandInterface;
  15. use Predis\Command\Hash\RedisClusterHashStrategy;
  16. use Predis\Distribution\CRC16HashGenerator;
  17. /**
  18. * Abstraction for Redis cluster (Redis v3.0).
  19. *
  20. * @author Daniele Alessandri <suppakilla@gmail.com>
  21. */
  22. class RedisCluster implements ClusterConnectionInterface, \IteratorAggregate, \Countable
  23. {
  24. private $pool;
  25. private $slots;
  26. private $slotsMap;
  27. private $connections;
  28. private $distributor;
  29. private $cmdHasher;
  30. /**
  31. * @param ConnectionFactoryInterface $connections Connection factory object.
  32. */
  33. public function __construct(ConnectionFactoryInterface $connections = null)
  34. {
  35. $this->pool = array();
  36. $this->slots = array();
  37. $this->connections = $connections ?: new ConnectionFactory();
  38. $this->distributor = new CRC16HashGenerator();
  39. $this->cmdHasher = new RedisClusterHashStrategy();
  40. }
  41. /**
  42. * {@inheritdoc}
  43. */
  44. public function isConnected()
  45. {
  46. foreach ($this->pool as $connection) {
  47. if ($connection->isConnected()) {
  48. return true;
  49. }
  50. }
  51. return false;
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function connect()
  57. {
  58. foreach ($this->pool as $connection) {
  59. $connection->connect();
  60. }
  61. }
  62. /**
  63. * {@inheritdoc}
  64. */
  65. public function disconnect()
  66. {
  67. foreach ($this->pool as $connection) {
  68. $connection->disconnect();
  69. }
  70. }
  71. /**
  72. * {@inheritdoc}
  73. */
  74. public function add(SingleConnectionInterface $connection)
  75. {
  76. $this->pool[(string) $connection] = $connection;
  77. unset($this->slotsMap);
  78. }
  79. /**
  80. * {@inheritdoc}
  81. */
  82. public function remove(SingleConnectionInterface $connection)
  83. {
  84. if (($id = array_search($connection, $this->pool, true)) !== false) {
  85. unset($this->pool[$id]);
  86. unset($this->slotsMap);
  87. return true;
  88. }
  89. return false;
  90. }
  91. /**
  92. * Removes a connection instance using its alias or index.
  93. *
  94. * @param string $connectionId Alias or index of a connection.
  95. * @return Boolean Returns true if the connection was in the pool.
  96. */
  97. public function removeById($connectionId)
  98. {
  99. if (isset($this->pool[$connectionId])) {
  100. unset($this->pool[$connectionId]);
  101. return true;
  102. }
  103. return false;
  104. }
  105. /**
  106. * Builds the slots map for the cluster.
  107. */
  108. public function buildSlotsMap()
  109. {
  110. $this->slotsMap = array();
  111. foreach ($this->pool as $connectionID => $connection) {
  112. $parameters = $connection->getParameters();
  113. if (!isset($parameters->slots)) {
  114. continue;
  115. }
  116. list($first, $last) = explode('-', $parameters->slots, 2);
  117. $this->setSlots($first, $last, $connectionID);
  118. }
  119. return $this->slotsMap;
  120. }
  121. /**
  122. * Preassociate a connection to a set of slots to avoid runtime guessing.
  123. *
  124. * @todo Check type or existence of the specified connection.
  125. *
  126. * @param int $first Initial slot.
  127. * @param int $last Last slot.
  128. * @param SingleConnectionInterface|string $connection ID or connection instance.
  129. */
  130. public function setSlots($first, $last, $connection)
  131. {
  132. if ($first < 0 || $first > 4095 || $last < 0 || $last > 4095 || $last < $first) {
  133. throw new \OutOfBoundsException("Invalid slot values for $connection: [$first-$last]");
  134. }
  135. $this->slotsMap = $this->slotsMap + array_fill($first, $last - $first + 1, (string) $connection);
  136. }
  137. /**
  138. * {@inheritdoc}
  139. */
  140. public function getConnection(CommandInterface $command)
  141. {
  142. $hash = $command->getHash();
  143. if (!isset($hash)) {
  144. $hash = $this->cmdHasher->getHash($this->distributor, $command);
  145. if (!isset($hash)) {
  146. throw new NotSupportedException("Cannot send {$command->getId()} commands to redis-cluster");
  147. }
  148. $command->setHash($hash);
  149. }
  150. $slot = $hash & 4095; // 0x0FFF
  151. if (isset($this->slots[$slot])) {
  152. return $this->slots[$slot];
  153. }
  154. $this->slots[$slot] = $connection = $this->pool[$this->guessNode($slot)];
  155. return $connection;
  156. }
  157. /**
  158. * Tries guessing the correct node associated to the given slot using a precalculated
  159. * slots map or the same logic used by redis-trib to initialize a redis cluster.
  160. *
  161. * @param int $slot Slot ID.
  162. * @return string
  163. */
  164. protected function guessNode($slot)
  165. {
  166. if (!isset($this->slotsMap)) {
  167. $this->buildSlotsMap();
  168. }
  169. if (isset($this->slotsMap[$slot])) {
  170. return $this->slotsMap[$slot];
  171. }
  172. $index = $slot / (int) (4096 / count($this->pool));
  173. $nodes = array_keys($this->pool);
  174. return $nodes[min($index, 4095)];
  175. }
  176. /**
  177. * {@inheritdoc}
  178. */
  179. public function getConnectionById($id = null)
  180. {
  181. if (!isset($id)) {
  182. throw new \InvalidArgumentException("A valid connection ID must be specified");
  183. }
  184. return isset($this->pool[$id]) ? $this->pool[$id] : null;
  185. }
  186. /**
  187. * Handles -MOVED or -ASK replies by re-executing the command on the server
  188. * specified by the Redis reply.
  189. *
  190. * @param CommandInterface $command Command that generated the -MOVE or -ASK reply.
  191. * @param string $request Type of request (either 'MOVED' or 'ASK').
  192. * @param string $details Parameters of the MOVED/ASK request.
  193. * @return mixed
  194. */
  195. protected function onMoveRequest(CommandInterface $command, $request, $details)
  196. {
  197. list($slot, $host) = explode(' ', $details, 2);
  198. $connection = $this->getConnectionById($host);
  199. if (!isset($connection)) {
  200. $parameters = array('host' => null, 'port' => null);
  201. list($parameters['host'], $parameters['port']) = explode(':', $host, 2);
  202. $connection = $this->connections->create($parameters);
  203. }
  204. switch ($request) {
  205. case 'MOVED':
  206. $this->move($connection, $slot);
  207. return $this->executeCommand($command);
  208. case 'ASK':
  209. return $connection->executeCommand($command);
  210. default:
  211. throw new ClientException("Unexpected request type for a move request: $request");
  212. }
  213. }
  214. /**
  215. * Assign the connection instance to a new slot and adds it to the
  216. * pool if the connection was not already part of the pool.
  217. *
  218. * @param SingleConnectionInterface $connection Connection instance
  219. * @param int $slot Target slot.
  220. */
  221. protected function move(SingleConnectionInterface $connection, $slot)
  222. {
  223. $this->pool[(string) $connection] = $connection;
  224. $this->slots[(int) $slot] = $connection;
  225. }
  226. /**
  227. * Returns the underlying command hash strategy used to hash
  228. * commands by their keys.
  229. *
  230. * @return CommandHashStrategy
  231. */
  232. public function getCommandHashStrategy()
  233. {
  234. return $this->cmdHasher;
  235. }
  236. /**
  237. * {@inheritdoc}
  238. */
  239. public function count()
  240. {
  241. return count($this->pool);
  242. }
  243. /**
  244. * {@inheritdoc}
  245. */
  246. public function getIterator()
  247. {
  248. return new \ArrayIterator($this->pool);
  249. }
  250. /**
  251. * Handles -ERR replies from Redis.
  252. *
  253. * @param CommandInterface $command Command that generated the -ERR reply.
  254. * @param ResponseErrorInterface $error Redis error reply object.
  255. * @return mixed
  256. */
  257. protected function handleServerError(CommandInterface $command, ResponseErrorInterface $error)
  258. {
  259. list($type, $details) = explode(' ', $error->getMessage(), 2);
  260. switch ($type) {
  261. case 'MOVED':
  262. case 'ASK':
  263. return $this->onMoveRequest($command, $type, $details);
  264. default:
  265. return $error;
  266. }
  267. }
  268. /**
  269. * {@inheritdoc}
  270. */
  271. public function writeCommand(CommandInterface $command)
  272. {
  273. $this->getConnection($command)->writeCommand($command);
  274. }
  275. /**
  276. * {@inheritdoc}
  277. */
  278. public function readResponse(CommandInterface $command)
  279. {
  280. return $this->getConnection($command)->readResponse($command);
  281. }
  282. /**
  283. * {@inheritdoc}
  284. */
  285. public function executeCommand(CommandInterface $command)
  286. {
  287. $connection = $this->getConnection($command);
  288. $reply = $connection->executeCommand($command);
  289. if ($reply instanceof ResponseErrorInterface) {
  290. return $this->handleServerError($command, $reply);
  291. }
  292. return $reply;
  293. }
  294. }