RedisCluster.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 ArrayIterator;
  12. use Countable;
  13. use IteratorAggregate;
  14. use OutOfBoundsException;
  15. use Predis\NotSupportedException;
  16. use Predis\Cluster\RedisStrategy as RedisClusterStrategy;
  17. use Predis\Command\CommandInterface;
  18. use Predis\Command\RawCommand;
  19. use Predis\Protocol\ProtocolException;
  20. use Predis\Response\ErrorInterface as ErrorResponseInterface;
  21. /**
  22. * Abstraction for a Redis-backed cluster of nodes (Redis >= 3.0.0).
  23. *
  24. * This connection backend offers smart support for redis-cluster by handling
  25. * automatic slots map (re)generation upon -MOVE or -ASK responses returned by
  26. * Redis when redirecting a client to a different node.
  27. *
  28. * The cluster can be pre-initialized using only a subset of the actual nodes in
  29. * the cluster, Predis will do the rest by adjusting the slots map and creating
  30. * the missing underlying connection instances on the fly.
  31. *
  32. * It is possible to pre-associate connections to a slots range with the "slots"
  33. * parameter in the form "$first-$last". This can greatly reduce runtime node
  34. * guessing and redirections.
  35. *
  36. * It is also possible to ask for the full and updated slots map directly to one
  37. * of the nodes and optionally enable such a behaviour upon -MOVED redirections.
  38. * Asking for the cluster configuration to Redis is actually done by issuing a
  39. * CLUSTER NODES command to a random node in the pool.
  40. *
  41. * @author Daniele Alessandri <suppakilla@gmail.com>
  42. */
  43. class RedisCluster implements ClusterConnectionInterface, IteratorAggregate, Countable
  44. {
  45. private $askClusterNodes = false;
  46. private $defaultParameters = array();
  47. private $pool = array();
  48. private $slots = array();
  49. private $slotsMap;
  50. private $strategy;
  51. private $connections;
  52. /**
  53. * @param FactoryInterface $connections Connection factory object.
  54. */
  55. public function __construct(FactoryInterface $connections = null)
  56. {
  57. $this->strategy = new RedisClusterStrategy();
  58. $this->connections = $connections ?: new Factory();
  59. }
  60. /**
  61. * {@inheritdoc}
  62. */
  63. public function isConnected()
  64. {
  65. foreach ($this->pool as $connection) {
  66. if ($connection->isConnected()) {
  67. return true;
  68. }
  69. }
  70. return false;
  71. }
  72. /**
  73. * {@inheritdoc}
  74. */
  75. public function connect()
  76. {
  77. if ($connection = $this->getRandomConnection()) {
  78. $connection->connect();
  79. }
  80. }
  81. /**
  82. * {@inheritdoc}
  83. */
  84. public function disconnect()
  85. {
  86. foreach ($this->pool as $connection) {
  87. $connection->disconnect();
  88. }
  89. }
  90. /**
  91. * {@inheritdoc}
  92. */
  93. public function add(SingleConnectionInterface $connection)
  94. {
  95. $this->pool[(string) $connection] = $connection;
  96. unset($this->slotsMap);
  97. }
  98. /**
  99. * {@inheritdoc}
  100. */
  101. public function remove(SingleConnectionInterface $connection)
  102. {
  103. if (false !== $id = array_search($connection, $this->pool, true)) {
  104. unset(
  105. $this->pool[$id],
  106. $this->slotsMap
  107. );
  108. return true;
  109. }
  110. return false;
  111. }
  112. /**
  113. * Removes a connection instance by using its identifier.
  114. *
  115. * @param string $connectionID Connection identifier.
  116. * @return bool True if the connection was in the pool.
  117. */
  118. public function removeById($connectionID)
  119. {
  120. if (isset($this->pool[$connectionID])) {
  121. unset(
  122. $this->pool[$connectionID],
  123. $this->slotsMap
  124. );
  125. return true;
  126. }
  127. return false;
  128. }
  129. /**
  130. * Generates the current slots map by guessing the cluster configuration out
  131. * of the connection parameters of the connections in the pool.
  132. *
  133. * Generation is based on the same algorithm used by Redis to generate the
  134. * cluster, so it is most effective when all of the connections supplied on
  135. * initialization have the "slots" parameter properly set accordingly to the
  136. * current cluster configuration.
  137. */
  138. public function buildSlotsMap()
  139. {
  140. $this->slotsMap = array();
  141. foreach ($this->pool as $connectionID => $connection) {
  142. $parameters = $connection->getParameters();
  143. if (!isset($parameters->slots)) {
  144. continue;
  145. }
  146. $slots = explode('-', $parameters->slots, 2);
  147. $this->setSlots($slots[0], $slots[1], $connectionID);
  148. }
  149. }
  150. /**
  151. * Generates the current slots map by fetching the cluster configuration to
  152. * one of the nodes by leveraging the CLUSTER NODES command.
  153. */
  154. public function askClusterNodes()
  155. {
  156. if (!$connection = $this->getRandomConnection()) {
  157. return array();
  158. }
  159. $cmdCluster = RawCommand::create('CLUSTER', 'NODES');
  160. $response = $connection->executeCommand($cmdCluster);
  161. $nodes = explode("\n", $response, -1);
  162. $count = count($nodes);
  163. for ($i = 0; $i < $count; $i++) {
  164. $node = explode(' ', $nodes[$i], 9);
  165. $slots = explode('-', $node[8], 2);
  166. if ($node[1] === ':0') {
  167. $this->setSlots($slots[0], $slots[1], (string) $connection);
  168. } else {
  169. $this->setSlots($slots[0], $slots[1], $node[1]);
  170. }
  171. }
  172. }
  173. /**
  174. * Returns the current slots map for the cluster.
  175. *
  176. * @return array
  177. */
  178. public function getSlotsMap()
  179. {
  180. if (!isset($this->slotsMap)) {
  181. $this->slotsMap = array();
  182. }
  183. return $this->slotsMap;
  184. }
  185. /**
  186. * Pre-associates a connection to a slots range to avoid runtime guessing.
  187. *
  188. * @param int $first Initial slot of the range.
  189. * @param int $last Last slot of the range.
  190. * @param SingleConnectionInterface|string $connection ID or connection instance.
  191. */
  192. public function setSlots($first, $last, $connection)
  193. {
  194. if ($first < 0x0000 || $first > 0x3FFF ||
  195. $last < 0x0000 || $last > 0x3FFF ||
  196. $last < $first
  197. ) {
  198. throw new OutOfBoundsException(
  199. "Invalid slot range for $connection: [$first-$last]."
  200. );
  201. }
  202. $slots = array_fill($first, $last - $first + 1, (string) $connection);
  203. $this->slotsMap = $this->getSlotsMap() + $slots;
  204. }
  205. /**
  206. * Guesses the correct node associated to a given slot using a precalculated
  207. * slots map, falling back to the same logic used by Redis to initialize a
  208. * cluster (best-effort).
  209. *
  210. * @param int $slot Slot index.
  211. * @return string Connection ID.
  212. */
  213. protected function guessNode($slot)
  214. {
  215. if (!isset($this->slotsMap)) {
  216. $this->buildSlotsMap();
  217. }
  218. if (isset($this->slotsMap[$slot])) {
  219. return $this->slotsMap[$slot];
  220. }
  221. $count = count($this->pool);
  222. $index = min((int) ($slot / (int) (16384 / $count)), $count - 1);
  223. $nodes = array_keys($this->pool);
  224. return $nodes[$index];
  225. }
  226. /**
  227. * {@inheritdoc}
  228. */
  229. public function getConnection(CommandInterface $command)
  230. {
  231. $hash = $this->strategy->getHash($command);
  232. if (!isset($hash)) {
  233. throw new NotSupportedException(
  234. "Cannot use '{$command->getId()}' with redis-cluster."
  235. );
  236. }
  237. $slot = $hash & 0x3FFF;
  238. if (isset($this->slots[$slot])) {
  239. return $this->slots[$slot];
  240. } else {
  241. return $this->getConnectionBySlot($slot);
  242. }
  243. }
  244. /**
  245. * Returns the connection currently associated to a given slot.
  246. *
  247. * @param int $slot Slot index.
  248. * @return SingleConnectionInterface
  249. */
  250. public function getConnectionBySlot($slot)
  251. {
  252. if ($slot < 0x0000 || $slot > 0x3FFF) {
  253. throw new OutOfBoundsException("Invalid slot [$slot].");
  254. }
  255. if (isset($this->slots[$slot])) {
  256. return $this->slots[$slot];
  257. }
  258. $connectionID = $this->guessNode($slot);
  259. if (!$connection = $this->getConnectionById($connectionID)) {
  260. $host = explode(':', $connectionID, 2);
  261. $parameters = array_merge($this->defaultParameters, array(
  262. 'host' => $host[0],
  263. 'port' => $host[1],
  264. ));
  265. $connection = $this->connections->create($parameters);
  266. $this->pool[$connectionID] = $connection;
  267. }
  268. return $this->slots[$slot] = $connection;
  269. }
  270. /**
  271. * {@inheritdoc}
  272. */
  273. public function getConnectionById($connectionID)
  274. {
  275. if (isset($this->pool[$connectionID])) {
  276. return $this->pool[$connectionID];
  277. }
  278. }
  279. /**
  280. * Returns a random connection from the pool.
  281. *
  282. * @return SingleConnectionInterface
  283. */
  284. protected function getRandomConnection()
  285. {
  286. if ($this->pool) {
  287. return $this->pool[array_rand($this->pool)];
  288. }
  289. }
  290. /**
  291. * Permanently associates the connection instance to a new slot.
  292. * The connection is added to the connections pool if not yet included.
  293. *
  294. * @param SingleConnectionInterface $connection Connection instance.
  295. * @param int $slot Target slot index.
  296. */
  297. protected function move(SingleConnectionInterface $connection, $slot)
  298. {
  299. $this->pool[(string) $connection] = $connection;
  300. $this->slots[(int) $slot] = $connection;
  301. }
  302. /**
  303. * Handles -ERR responses from Redis.
  304. *
  305. * @param CommandInterface $command Command that generated the -ERR response.
  306. * @param ErrorResponseInterface $error Redis error response object.
  307. * @return mixed
  308. */
  309. protected function onErrorResponse(CommandInterface $command, ErrorResponseInterface $error)
  310. {
  311. $details = explode(' ', $error->getMessage(), 2);
  312. switch ($details[0]) {
  313. case 'MOVED':
  314. case 'ASK':
  315. return $this->onMoveRequest($command, $details[0], $details[1]);
  316. default:
  317. return $error;
  318. }
  319. }
  320. /**
  321. * Handles -MOVED and -ASK responses by re-executing the command on the node
  322. * specified by the Redis response.
  323. *
  324. * @param CommandInterface $command Command that generated the -MOVE or -ASK response.
  325. * @param string $request Type of request (either 'MOVED' or 'ASK').
  326. * @param string $details Parameters of the MOVED/ASK request.
  327. * @return mixed
  328. */
  329. protected function onMoveRequest(CommandInterface $command, $request, $details)
  330. {
  331. list($slot, $host) = explode(' ', $details, 2);
  332. $connection = $this->getConnectionById($host);
  333. if (!$connection) {
  334. $host = explode(':', $host, 2);
  335. $parameters = array_merge($this->defaultParameters, array(
  336. 'host' => $host[0],
  337. 'port' => $host[1],
  338. ));
  339. $connection = $this->connections->create($parameters);
  340. }
  341. switch ($request) {
  342. case 'MOVED':
  343. if ($this->askClusterNodes) {
  344. $this->askClusterNodes();
  345. }
  346. $this->move($connection, $slot);
  347. $response = $this->executeCommand($command);
  348. return $response;
  349. case 'ASK':
  350. $connection->executeCommand(RawCommand::create('ASKING'));
  351. $response = $connection->executeCommand($command);
  352. return $response;
  353. default:
  354. throw new ProtocolException(
  355. "Unexpected request type for a move request: $request."
  356. );
  357. }
  358. }
  359. /**
  360. * {@inheritdoc}
  361. */
  362. public function writeRequest(CommandInterface $command)
  363. {
  364. $this->getConnection($command)->writeRequest($command);
  365. }
  366. /**
  367. * {@inheritdoc}
  368. */
  369. public function readResponse(CommandInterface $command)
  370. {
  371. return $this->getConnection($command)->readResponse($command);
  372. }
  373. /**
  374. * {@inheritdoc}
  375. */
  376. public function executeCommand(CommandInterface $command)
  377. {
  378. $connection = $this->getConnection($command);
  379. $response = $connection->executeCommand($command);
  380. if ($response instanceof ErrorResponseInterface) {
  381. return $this->onErrorResponse($command, $response);
  382. }
  383. return $response;
  384. }
  385. /**
  386. * {@inheritdoc}
  387. */
  388. public function count()
  389. {
  390. return count($this->pool);
  391. }
  392. /**
  393. * {@inheritdoc}
  394. */
  395. public function getIterator()
  396. {
  397. return new ArrayIterator(array_values($this->pool));
  398. }
  399. /**
  400. * Returns the underlying command hash strategy used to hash commands by
  401. * using keys found in their arguments.
  402. *
  403. * @return ClusterStrategyInterface
  404. */
  405. public function getClusterStrategy()
  406. {
  407. return $this->strategy;
  408. }
  409. /**
  410. * Enables automatic fetching of the current slots map from one of the nodes
  411. * using the CLUSTER NODES command. This option is disabled by default but
  412. * asking the current slots map to Redis upon -MOVE responses may reduce
  413. * overhead by eliminating the trial-and-error nature of the node guessing
  414. * procedure, mostly when targeting many keys that would end up in a lot of
  415. * redirections.
  416. *
  417. * The slots map can still be manually fetched using the askClusterNodes()
  418. * method whether or not this option is enabled.
  419. *
  420. * @param bool $value Enable or disable the use of CLUSTER NODES.
  421. */
  422. public function enableClusterNodes($value)
  423. {
  424. $this->askClusterNodes = (bool) $value;
  425. }
  426. /**
  427. * Sets a default array of connection parameters to be applied when creating
  428. * new connection instances on the fly when they are not part of the initial
  429. * pool supplied upon cluster initialization.
  430. *
  431. * These parameters are not applied to connections added to the pool using
  432. * the add() method.
  433. *
  434. * @param array $parameters Array of connection parameters.
  435. */
  436. public function setDefaultParameters(array $parameters)
  437. {
  438. $this->defaultParameters = array_merge(
  439. $this->defaultParameters,
  440. $parameters ?: array()
  441. );
  442. }
  443. }