RedisCluster.php 8.9 KB

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