RedisCluster.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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\Connection\ConnectionFactory;
  17. use Predis\Connection\ConnectionFactoryInterface;
  18. use Predis\Distribution\CRC16HashGenerator;
  19. /**
  20. * Abstraction for Redis cluster (Redis v3.0).
  21. *
  22. * @author Daniele Alessandri <suppakilla@gmail.com>
  23. */
  24. class RedisCluster implements ClusterConnectionInterface, \IteratorAggregate, \Countable
  25. {
  26. private $pool;
  27. private $slots;
  28. private $slotsMap;
  29. private $connections;
  30. private $distributor;
  31. private $cmdHasher;
  32. /**
  33. * @param ConnectionFactoryInterface $connections Connection factory object.
  34. */
  35. public function __construct(ConnectionFactoryInterface $connections = null)
  36. {
  37. $this->pool = array();
  38. $this->slots = array();
  39. $this->connections = $connections ?: new ConnectionFactory();
  40. $this->distributor = new CRC16HashGenerator();
  41. $this->cmdHasher = new RedisClusterHashStrategy();
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function isConnected()
  47. {
  48. foreach ($this->pool as $connection) {
  49. if ($connection->isConnected()) {
  50. return true;
  51. }
  52. }
  53. return false;
  54. }
  55. /**
  56. * {@inheritdoc}
  57. */
  58. public function connect()
  59. {
  60. foreach ($this->pool as $connection) {
  61. $connection->connect();
  62. }
  63. }
  64. /**
  65. * {@inheritdoc}
  66. */
  67. public function disconnect()
  68. {
  69. foreach ($this->pool as $connection) {
  70. $connection->disconnect();
  71. }
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. public function add(SingleConnectionInterface $connection)
  77. {
  78. $this->pool[(string) $connection] = $connection;
  79. }
  80. /**
  81. * {@inheritdoc}
  82. */
  83. public function remove(SingleConnectionInterface $connection)
  84. {
  85. if (($id = array_search($connection, $this->pool, true)) !== false) {
  86. unset($this->pool[$id]);
  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. * Recreates the slots map for the cluster.
  107. */
  108. public function resetSlotsMap()
  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. if (!isset($this->slotsMap)) {
  143. $this->resetSlotsMap();
  144. }
  145. $hash = $command->getHash();
  146. if (!isset($hash)) {
  147. $hash = $this->cmdHasher->getHash($this->distributor, $command);
  148. if (!isset($hash)) {
  149. throw new NotSupportedException("Cannot send {$command->getId()} commands to redis-cluster");
  150. }
  151. $command->setHash($hash);
  152. }
  153. $slot = $hash & 4095; // 0x0FFF
  154. if (isset($this->slots[$slot])) {
  155. return $this->slots[$slot];
  156. }
  157. $connectionID = isset($this->slotsMap[$slot]) ? $this->slotsMap[$slot] : array_rand($this->pool);
  158. $this->slots[$slot] = $connection = $this->pool[$connectionID];
  159. return $connection;
  160. }
  161. /**
  162. * {@inheritdoc}
  163. */
  164. public function getConnectionById($id = null)
  165. {
  166. if (!isset($id)) {
  167. throw new \InvalidArgumentException("A valid connection ID must be specified");
  168. }
  169. return isset($this->pool[$id]) ? $this->pool[$id] : null;
  170. }
  171. /**
  172. * Handles -MOVED or -ASK replies by re-executing the command on the server
  173. * specified by the Redis reply.
  174. *
  175. * @param CommandInterface $command Command that generated the -MOVE or -ASK reply.
  176. * @param string $request Type of request (either 'MOVED' or 'ASK').
  177. * @param string $details Parameters of the MOVED/ASK request.
  178. * @return mixed
  179. */
  180. protected function onMoveRequest(CommandInterface $command, $request, $details)
  181. {
  182. list($slot, $host) = explode(' ', $details, 2);
  183. $connection = $this->getConnectionById($host);
  184. if (!isset($connection)) {
  185. $parameters = array('host' => null, 'port' => null);
  186. list($parameters['host'], $parameters['port']) = explode(':', $host, 2);
  187. $connection = $this->connections->create($parameters);
  188. }
  189. switch ($request) {
  190. case 'MOVED':
  191. $this->move($connection, $slot);
  192. return $this->executeCommand($command);
  193. case 'ASK':
  194. return $connection->executeCommand($command);
  195. default:
  196. throw new ClientException("Unexpected request type for a move request: $request");
  197. }
  198. }
  199. /**
  200. * Assign the connection instance to a new slot and adds it to the
  201. * pool if the connection was not already part of the pool.
  202. *
  203. * @param SingleConnectionInterface $connection Connection instance
  204. * @param int $slot Target slot.
  205. */
  206. protected function move(SingleConnectionInterface $connection, $slot)
  207. {
  208. $this->pool[(string) $connection] = $connection;
  209. $this->slots[(int) $slot] = $connection;
  210. }
  211. /**
  212. * Returns the underlying command hash strategy used to hash
  213. * commands by their keys.
  214. *
  215. * @return CommandHashStrategy
  216. */
  217. public function getCommandHashStrategy()
  218. {
  219. return $this->cmdHasher;
  220. }
  221. /**
  222. * {@inheritdoc}
  223. */
  224. public function count()
  225. {
  226. return count($this->pool);
  227. }
  228. /**
  229. * {@inheritdoc}
  230. */
  231. public function getIterator()
  232. {
  233. return new \ArrayIterator($this->pool);
  234. }
  235. /**
  236. * Handles -ERR replies from Redis.
  237. *
  238. * @param CommandInterface $command Command that generated the -ERR reply.
  239. * @param ResponseErrorInterface $error Redis error reply object.
  240. * @return mixed
  241. */
  242. protected function handleServerError(CommandInterface $command, ResponseErrorInterface $error)
  243. {
  244. list($type, $details) = explode(' ', $error->getMessage(), 2);
  245. switch ($type) {
  246. case 'MOVED':
  247. case 'ASK':
  248. return $this->onMoveRequest($command, $type, $details);
  249. default:
  250. return $error;
  251. }
  252. }
  253. /**
  254. * {@inheritdoc}
  255. */
  256. public function writeCommand(CommandInterface $command)
  257. {
  258. $this->getConnection($command)->writeCommand($command);
  259. }
  260. /**
  261. * {@inheritdoc}
  262. */
  263. public function readResponse(CommandInterface $command)
  264. {
  265. return $this->getConnection($command)->readResponse($command);
  266. }
  267. /**
  268. * {@inheritdoc}
  269. */
  270. public function executeCommand(CommandInterface $command)
  271. {
  272. $connection = $this->getConnection($command);
  273. $reply = $connection->executeCommand($command);
  274. if ($reply instanceof ResponseErrorInterface) {
  275. return $this->handleServerError($command, $reply);
  276. }
  277. return $reply;
  278. }
  279. }