RedisCluster.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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($id = null)
  197. {
  198. if (!isset($id)) {
  199. throw new \InvalidArgumentException("A valid connection ID must be specified");
  200. }
  201. return isset($this->pool[$id]) ? $this->pool[$id] : null;
  202. }
  203. /**
  204. * Tries guessing the correct node associated to the given slot using a precalculated
  205. * slots map or the same logic used by redis-trib to initialize a redis cluster.
  206. *
  207. * @param int $slot Slot ID.
  208. * @return string
  209. */
  210. protected function guessNode($slot)
  211. {
  212. if (!isset($this->slotsMap)) {
  213. $this->buildSlotsMap();
  214. }
  215. if (isset($this->slotsMap[$slot])) {
  216. return $this->slotsMap[$slot];
  217. }
  218. $index = min((int) ($slot / $this->slotsPerNode), count($this->pool) - 1);
  219. $nodes = array_keys($this->pool);
  220. return $nodes[$index];
  221. }
  222. /**
  223. * Handles -MOVED or -ASK replies by re-executing the command on the server
  224. * specified by the Redis reply.
  225. *
  226. * @param CommandInterface $command Command that generated the -MOVE or -ASK reply.
  227. * @param string $request Type of request (either 'MOVED' or 'ASK').
  228. * @param string $details Parameters of the MOVED/ASK request.
  229. * @return mixed
  230. */
  231. protected function onMoveRequest(CommandInterface $command, $request, $details)
  232. {
  233. list($slot, $host) = explode(' ', $details, 2);
  234. $connection = $this->getConnectionById($host);
  235. if (!isset($connection)) {
  236. $parameters = array('host' => null, 'port' => null);
  237. list($parameters['host'], $parameters['port']) = explode(':', $host, 2);
  238. $connection = $this->connections->create($parameters);
  239. }
  240. switch ($request) {
  241. case 'MOVED':
  242. $this->move($connection, $slot);
  243. return $this->executeCommand($command);
  244. case 'ASK':
  245. return $connection->executeCommand($command);
  246. default:
  247. throw new ClientException("Unexpected request type for a move request: $request");
  248. }
  249. }
  250. /**
  251. * Assign the connection instance to a new slot and adds it to the
  252. * pool if the connection was not already part of the pool.
  253. *
  254. * @param SingleConnectionInterface $connection Connection instance
  255. * @param int $slot Target slot.
  256. */
  257. protected function move(SingleConnectionInterface $connection, $slot)
  258. {
  259. $this->pool[(string) $connection] = $connection;
  260. $this->slots[(int) $slot] = $connection;
  261. }
  262. /**
  263. * Returns the underlying command hash strategy used to hash
  264. * commands by their keys.
  265. *
  266. * @return Predis\Cluster\CommandHashStrategyInterface
  267. */
  268. public function getCommandHashStrategy()
  269. {
  270. return $this->strategy;
  271. }
  272. /**
  273. * {@inheritdoc}
  274. */
  275. public function count()
  276. {
  277. return count($this->pool);
  278. }
  279. /**
  280. * {@inheritdoc}
  281. */
  282. public function getIterator()
  283. {
  284. return new \ArrayIterator(array_values($this->pool));
  285. }
  286. /**
  287. * Handles -ERR replies from Redis.
  288. *
  289. * @param CommandInterface $command Command that generated the -ERR reply.
  290. * @param ResponseErrorInterface $error Redis error reply object.
  291. * @return mixed
  292. */
  293. protected function handleServerError(CommandInterface $command, ResponseErrorInterface $error)
  294. {
  295. list($type, $details) = explode(' ', $error->getMessage(), 2);
  296. switch ($type) {
  297. case 'MOVED':
  298. case 'ASK':
  299. return $this->onMoveRequest($command, $type, $details);
  300. default:
  301. return $error;
  302. }
  303. }
  304. /**
  305. * {@inheritdoc}
  306. */
  307. public function writeCommand(CommandInterface $command)
  308. {
  309. $this->getConnection($command)->writeCommand($command);
  310. }
  311. /**
  312. * {@inheritdoc}
  313. */
  314. public function readResponse(CommandInterface $command)
  315. {
  316. return $this->getConnection($command)->readResponse($command);
  317. }
  318. /**
  319. * {@inheritdoc}
  320. */
  321. public function executeCommand(CommandInterface $command)
  322. {
  323. $connection = $this->getConnection($command);
  324. $reply = $connection->executeCommand($command);
  325. if ($reply instanceof ResponseErrorInterface) {
  326. return $this->handleServerError($command, $reply);
  327. }
  328. return $reply;
  329. }
  330. }