RedisCluster.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. }
  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. return true;
  86. }
  87. return false;
  88. }
  89. /**
  90. * Removes a connection instance using its alias or index.
  91. *
  92. * @param string $connectionId Alias or index of a connection.
  93. * @return Boolean Returns true if the connection was in the pool.
  94. */
  95. public function removeById($connectionId)
  96. {
  97. if (isset($this->pool[$connectionId])) {
  98. unset($this->pool[$connectionId]);
  99. return true;
  100. }
  101. return false;
  102. }
  103. /**
  104. * Recreates the slots map for the cluster.
  105. */
  106. public function resetSlotsMap()
  107. {
  108. $this->slotsMap = array();
  109. foreach ($this->pool as $connectionID => $connection) {
  110. $parameters = $connection->getParameters();
  111. if (!isset($parameters->slots)) {
  112. continue;
  113. }
  114. list($first, $last) = explode('-', $parameters->slots, 2);
  115. $this->setSlots($first, $last, $connectionID);
  116. }
  117. return $this->slotsMap;
  118. }
  119. /**
  120. * Preassociate a connection to a set of slots to avoid runtime guessing.
  121. *
  122. * @todo Check type or existence of the specified connection.
  123. *
  124. * @param int $first Initial slot.
  125. * @param int $last Last slot.
  126. * @param SingleConnectionInterface|string $connection ID or connection instance.
  127. */
  128. public function setSlots($first, $last, $connection)
  129. {
  130. if ($first < 0 || $first > 4095 || $last < 0 || $last > 4095 || $last < $first) {
  131. throw new \OutOfBoundsException("Invalid slot values for $connection: [$first-$last]");
  132. }
  133. $this->slotsMap = $this->slotsMap + array_fill($first, $last - $first + 1, (string) $connection);
  134. }
  135. /**
  136. * {@inheritdoc}
  137. */
  138. public function getConnection(CommandInterface $command)
  139. {
  140. if (!isset($this->slotsMap)) {
  141. $this->resetSlotsMap();
  142. }
  143. $hash = $command->getHash();
  144. if (!isset($hash)) {
  145. $hash = $this->cmdHasher->getHash($this->distributor, $command);
  146. if (!isset($hash)) {
  147. throw new NotSupportedException("Cannot send {$command->getId()} commands to redis-cluster");
  148. }
  149. $command->setHash($hash);
  150. }
  151. $slot = $hash & 4095; // 0x0FFF
  152. if (isset($this->slots[$slot])) {
  153. return $this->slots[$slot];
  154. }
  155. $connectionID = isset($this->slotsMap[$slot]) ? $this->slotsMap[$slot] : array_rand($this->pool);
  156. $this->slots[$slot] = $connection = $this->pool[$connectionID];
  157. return $connection;
  158. }
  159. /**
  160. * {@inheritdoc}
  161. */
  162. public function getConnectionById($id = null)
  163. {
  164. if (!isset($id)) {
  165. throw new \InvalidArgumentException("A valid connection ID must be specified");
  166. }
  167. return isset($this->pool[$id]) ? $this->pool[$id] : null;
  168. }
  169. /**
  170. * Handles -MOVED or -ASK replies by re-executing the command on the server
  171. * specified by the Redis reply.
  172. *
  173. * @param CommandInterface $command Command that generated the -MOVE or -ASK reply.
  174. * @param string $request Type of request (either 'MOVED' or 'ASK').
  175. * @param string $details Parameters of the MOVED/ASK request.
  176. * @return mixed
  177. */
  178. protected function onMoveRequest(CommandInterface $command, $request, $details)
  179. {
  180. list($slot, $host) = explode(' ', $details, 2);
  181. $connection = $this->getConnectionById($host);
  182. if (!isset($connection)) {
  183. $parameters = array('host' => null, 'port' => null);
  184. list($parameters['host'], $parameters['port']) = explode(':', $host, 2);
  185. $connection = $this->connections->create($parameters);
  186. }
  187. switch ($request) {
  188. case 'MOVED':
  189. $this->move($connection, $slot);
  190. return $this->executeCommand($command);
  191. case 'ASK':
  192. return $connection->executeCommand($command);
  193. default:
  194. throw new ClientException("Unexpected request type for a move request: $request");
  195. }
  196. }
  197. /**
  198. * Assign the connection instance to a new slot and adds it to the
  199. * pool if the connection was not already part of the pool.
  200. *
  201. * @param SingleConnectionInterface $connection Connection instance
  202. * @param int $slot Target slot.
  203. */
  204. protected function move(SingleConnectionInterface $connection, $slot)
  205. {
  206. $this->pool[(string) $connection] = $connection;
  207. $this->slots[(int) $slot] = $connection;
  208. }
  209. /**
  210. * Returns the underlying command hash strategy used to hash
  211. * commands by their keys.
  212. *
  213. * @return CommandHashStrategy
  214. */
  215. public function getCommandHashStrategy()
  216. {
  217. return $this->cmdHasher;
  218. }
  219. /**
  220. * {@inheritdoc}
  221. */
  222. public function count()
  223. {
  224. return count($this->pool);
  225. }
  226. /**
  227. * {@inheritdoc}
  228. */
  229. public function getIterator()
  230. {
  231. return new \ArrayIterator($this->pool);
  232. }
  233. /**
  234. * Handles -ERR replies from Redis.
  235. *
  236. * @param CommandInterface $command Command that generated the -ERR reply.
  237. * @param ResponseErrorInterface $error Redis error reply object.
  238. * @return mixed
  239. */
  240. protected function handleServerError(CommandInterface $command, ResponseErrorInterface $error)
  241. {
  242. list($type, $details) = explode(' ', $error->getMessage(), 2);
  243. switch ($type) {
  244. case 'MOVED':
  245. case 'ASK':
  246. return $this->onMoveRequest($command, $type, $details);
  247. default:
  248. return $error;
  249. }
  250. }
  251. /**
  252. * {@inheritdoc}
  253. */
  254. public function writeCommand(CommandInterface $command)
  255. {
  256. $this->getConnection($command)->writeCommand($command);
  257. }
  258. /**
  259. * {@inheritdoc}
  260. */
  261. public function readResponse(CommandInterface $command)
  262. {
  263. return $this->getConnection($command)->readResponse($command);
  264. }
  265. /**
  266. * {@inheritdoc}
  267. */
  268. public function executeCommand(CommandInterface $command)
  269. {
  270. $connection = $this->getConnection($command);
  271. $reply = $connection->executeCommand($command);
  272. if ($reply instanceof ResponseErrorInterface) {
  273. return $this->handleServerError($command, $reply);
  274. }
  275. return $reply;
  276. }
  277. }