RedisCluster.php 9.1 KB

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