RedisCluster.php 9.9 KB

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