RedisCluster.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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\Cluster\CommandHashStrategyInterface;
  13. use Predis\NotSupportedException;
  14. use Predis\Cluster\RedisClusterHashStrategy;
  15. use Predis\Command\CommandInterface;
  16. use Predis\Response\ResponseErrorInterface;
  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 $slotsPerNode;
  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(
  77. $this->slotsMap,
  78. $this->slotsPerNode
  79. );
  80. }
  81. /**
  82. * {@inheritdoc}
  83. */
  84. public function remove(SingleConnectionInterface $connection)
  85. {
  86. if (($id = array_search($connection, $this->pool, true)) !== false) {
  87. unset(
  88. $this->pool[$id],
  89. $this->slotsMap,
  90. $this->slotsPerNode
  91. );
  92. return true;
  93. }
  94. return false;
  95. }
  96. /**
  97. * Removes a connection instance using its alias or index.
  98. *
  99. * @param string $connectionId Alias or index of a connection.
  100. * @return Boolean Returns true if the connection was in the pool.
  101. */
  102. public function removeById($connectionId)
  103. {
  104. if (isset($this->pool[$connectionId])) {
  105. unset(
  106. $this->pool[$connectionId],
  107. $this->slotsMap,
  108. $this->slotsPerNode
  109. );
  110. return true;
  111. }
  112. return false;
  113. }
  114. /**
  115. * Builds the slots map for the cluster.
  116. *
  117. * @return array
  118. */
  119. public function buildSlotsMap()
  120. {
  121. $this->slotsMap = array();
  122. $this->slotsPerNode = (int) (16384 / count($this->pool));
  123. foreach ($this->pool as $connectionID => $connection) {
  124. $parameters = $connection->getParameters();
  125. if (!isset($parameters->slots)) {
  126. continue;
  127. }
  128. list($first, $last) = explode('-', $parameters->slots, 2);
  129. $this->setSlots($first, $last, $connectionID);
  130. }
  131. return $this->slotsMap;
  132. }
  133. /**
  134. * Returns the current slots map for the cluster.
  135. *
  136. * @return array
  137. */
  138. public function getSlotsMap()
  139. {
  140. if (!isset($this->slotsMap)) {
  141. $this->slotsMap = array();
  142. }
  143. return $this->slotsMap;
  144. }
  145. /**
  146. * Preassociate a connection to a set of slots to avoid runtime guessing.
  147. *
  148. * @todo Check type or existence of the specified connection.
  149. * @todo Cluster loses the slots assigned with this methods when adding / removing connections.
  150. *
  151. * @param int $first Initial slot.
  152. * @param int $last Last slot.
  153. * @param SingleConnectionInterface|string $connection ID or connection instance.
  154. */
  155. public function setSlots($first, $last, $connection)
  156. {
  157. if ($first < 0x0000 || $first > 0x3FFF || $last < 0x0000 || $last > 0x3FFF || $last < $first) {
  158. throw new \OutOfBoundsException("Invalid slot values for $connection: [$first-$last]");
  159. }
  160. $this->slotsMap = $this->getSlotsMap() + array_fill($first, $last - $first + 1, (string) $connection);
  161. }
  162. /**
  163. * {@inheritdoc}
  164. */
  165. public function getConnection(CommandInterface $command)
  166. {
  167. $hash = $this->strategy->getHash($command);
  168. if (!isset($hash)) {
  169. throw new NotSupportedException("Cannot use {$command->getId()} with redis-cluster");
  170. }
  171. $slot = $hash & 0x3FFF;
  172. if (isset($this->slots[$slot])) {
  173. return $this->slots[$slot];
  174. }
  175. $this->slots[$slot] = $connection = $this->pool[$this->guessNode($slot)];
  176. return $connection;
  177. }
  178. /**
  179. * Returns the connection associated to the specified slot.
  180. *
  181. * @param int $slot Slot ID.
  182. * @return SingleConnectionInterface
  183. */
  184. public function getConnectionBySlot($slot)
  185. {
  186. if ($slot < 0x0000 || $slot > 0x3FFF) {
  187. throw new \OutOfBoundsException("Invalid slot value [$slot]");
  188. }
  189. if (isset($this->slots[$slot])) {
  190. return $this->slots[$slot];
  191. }
  192. return $this->pool[$this->guessNode($slot)];
  193. }
  194. /**
  195. * {@inheritdoc}
  196. */
  197. public function getConnectionById($connectionId)
  198. {
  199. return isset($this->pool[$connectionId]) ? $this->pool[$connectionId] : null;
  200. }
  201. /**
  202. * Tries guessing the correct node associated to the given slot using a precalculated
  203. * slots map or the same logic used by redis-trib to initialize a redis cluster.
  204. *
  205. * @param int $slot Slot ID.
  206. * @return string
  207. */
  208. protected function guessNode($slot)
  209. {
  210. if (!isset($this->slotsMap)) {
  211. $this->buildSlotsMap();
  212. }
  213. if (isset($this->slotsMap[$slot])) {
  214. return $this->slotsMap[$slot];
  215. }
  216. $index = min((int) ($slot / $this->slotsPerNode), count($this->pool) - 1);
  217. $nodes = array_keys($this->pool);
  218. return $nodes[$index];
  219. }
  220. /**
  221. * Handles -MOVED or -ASK replies by re-executing the command on the server
  222. * specified by the Redis reply.
  223. *
  224. * @param CommandInterface $command Command that generated the -MOVE or -ASK reply.
  225. * @param string $request Type of request (either 'MOVED' or 'ASK').
  226. * @param string $details Parameters of the MOVED/ASK request.
  227. * @return mixed
  228. */
  229. protected function onMoveRequest(CommandInterface $command, $request, $details)
  230. {
  231. list($slot, $host) = explode(' ', $details, 2);
  232. $connection = $this->getConnectionById($host);
  233. if (!isset($connection)) {
  234. $parameters = array('host' => null, 'port' => null);
  235. list($parameters['host'], $parameters['port']) = explode(':', $host, 2);
  236. $connection = $this->connections->create($parameters);
  237. }
  238. switch ($request) {
  239. case 'MOVED':
  240. $this->move($connection, $slot);
  241. return $this->executeCommand($command);
  242. case 'ASK':
  243. return $connection->executeCommand($command);
  244. default:
  245. throw new ClientException("Unexpected request type for a move request: $request");
  246. }
  247. }
  248. /**
  249. * Assign the connection instance to a new slot and adds it to the
  250. * pool if the connection was not already part of the pool.
  251. *
  252. * @param SingleConnectionInterface $connection Connection instance
  253. * @param int $slot Target slot.
  254. */
  255. protected function move(SingleConnectionInterface $connection, $slot)
  256. {
  257. $this->pool[(string) $connection] = $connection;
  258. $this->slots[(int) $slot] = $connection;
  259. }
  260. /**
  261. * Returns the underlying command hash strategy used to hash
  262. * commands by their keys.
  263. *
  264. * @return CommandHashStrategyInterface
  265. */
  266. public function getCommandHashStrategy()
  267. {
  268. return $this->strategy;
  269. }
  270. /**
  271. * {@inheritdoc}
  272. */
  273. public function count()
  274. {
  275. return count($this->pool);
  276. }
  277. /**
  278. * {@inheritdoc}
  279. */
  280. public function getIterator()
  281. {
  282. return new \ArrayIterator(array_values($this->pool));
  283. }
  284. /**
  285. * Handles -ERR replies from Redis.
  286. *
  287. * @param CommandInterface $command Command that generated the -ERR reply.
  288. * @param ResponseErrorInterface $error Redis error reply object.
  289. * @return mixed
  290. */
  291. protected function handleServerError(CommandInterface $command, ResponseErrorInterface $error)
  292. {
  293. list($type, $details) = explode(' ', $error->getMessage(), 2);
  294. switch ($type) {
  295. case 'MOVED':
  296. case 'ASK':
  297. return $this->onMoveRequest($command, $type, $details);
  298. default:
  299. return $error;
  300. }
  301. }
  302. /**
  303. * {@inheritdoc}
  304. */
  305. public function writeCommand(CommandInterface $command)
  306. {
  307. $this->getConnection($command)->writeCommand($command);
  308. }
  309. /**
  310. * {@inheritdoc}
  311. */
  312. public function readResponse(CommandInterface $command)
  313. {
  314. return $this->getConnection($command)->readResponse($command);
  315. }
  316. /**
  317. * {@inheritdoc}
  318. */
  319. public function executeCommand(CommandInterface $command)
  320. {
  321. $connection = $this->getConnection($command);
  322. $reply = $connection->executeCommand($command);
  323. if ($reply instanceof ResponseErrorInterface) {
  324. return $this->handleServerError($command, $reply);
  325. }
  326. return $reply;
  327. }
  328. }