RedisCluster.php 8.8 KB

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