RedisCluster.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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\ResponseErrorInterface;
  17. use Predis\Cluster\CommandHashStrategyInterface;
  18. use Predis\Cluster\RedisClusterHashStrategy;
  19. use Predis\Command\CommandInterface;
  20. use Predis\Command\RawCommand;
  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 -MOVED 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 SLOTS 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 = true;
  46. private $defaultParameters = array();
  47. private $pool = array();
  48. private $slots = array();
  49. private $slotsMap;
  50. private $strategy;
  51. private $connections;
  52. /**
  53. * @param ConnectionFactoryInterface $connections Connection factory object.
  54. */
  55. public function __construct(ConnectionFactoryInterface $connections = null)
  56. {
  57. $this->strategy = new RedisClusterHashStrategy();
  58. $this->connections = $connections ?: new ConnectionFactory();
  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 an updated slots map fetching the cluster configuration using
  152. * the CLUSTER SLOTS command against the specified node or a random one from
  153. * the pool.
  154. *
  155. * @param SingleConnectionInterface $connection Optional connection instance.
  156. * @return array
  157. */
  158. public function askClusterNodes(SingleConnectionInterface $connection = null)
  159. {
  160. if (!$connection && !$connection = $this->getRandomConnection()) {
  161. return array();
  162. }
  163. $command = RawCommand::create('CLUSTER', 'SLOTS');
  164. $response = $connection->executeCommand($command);
  165. foreach ($response as $slots) {
  166. // We only support master servers for now, so we ignore subsequent
  167. // elements in the $slots array identifying slaves.
  168. list($start, $end, $master) = $slots;
  169. if ($master[0] === '') {
  170. $this->setSlots($start, $end, (string) $connection);
  171. } else {
  172. $this->setSlots($start, $end, "{$master[0]}:{$master[1]}");
  173. }
  174. }
  175. return $this->slotsMap;
  176. }
  177. /**
  178. * Returns the current slots map for the cluster.
  179. *
  180. * @return array
  181. */
  182. public function getSlotsMap()
  183. {
  184. if (!isset($this->slotsMap)) {
  185. $this->slotsMap = array();
  186. }
  187. return $this->slotsMap;
  188. }
  189. /**
  190. * Pre-associates a connection to a slots range to avoid runtime guessing.
  191. *
  192. * @param int $first Initial slot of the range.
  193. * @param int $last Last slot of the range.
  194. * @param SingleConnectionInterface|string $connection ID or connection instance.
  195. */
  196. public function setSlots($first, $last, $connection)
  197. {
  198. if ($first < 0x0000 || $first > 0x3FFF ||
  199. $last < 0x0000 || $last > 0x3FFF ||
  200. $last < $first
  201. ) {
  202. throw new OutOfBoundsException(
  203. "Invalid slot range for $connection: [$first-$last]"
  204. );
  205. }
  206. $slots = array_fill($first, $last - $first + 1, (string) $connection);
  207. $this->slotsMap = $this->getSlotsMap() + $slots;
  208. }
  209. /**
  210. * Guesses the correct node associated to a given slot using a precalculated
  211. * slots map, falling back to the same logic used by Redis to initialize a
  212. * cluster (best-effort).
  213. *
  214. * @param int $slot Slot index.
  215. * @return string Connection ID.
  216. */
  217. protected function guessNode($slot)
  218. {
  219. if (!isset($this->slotsMap)) {
  220. $this->buildSlotsMap();
  221. }
  222. if (isset($this->slotsMap[$slot])) {
  223. return $this->slotsMap[$slot];
  224. }
  225. $count = count($this->pool);
  226. $index = min((int) ($slot / (int) (16384 / $count)), $count - 1);
  227. $nodes = array_keys($this->pool);
  228. return $nodes[$index];
  229. }
  230. /**
  231. * Creates a new connection instance from the given connection ID.
  232. *
  233. * @param string $connectionID Identifier for the connection.
  234. * @return SingleConnectionInterface
  235. */
  236. protected function createConnection($connectionID)
  237. {
  238. $host = explode(':', $connectionID, 2);
  239. $parameters = array_merge($this->defaultParameters, array(
  240. 'host' => $host[0],
  241. 'port' => $host[1],
  242. ));
  243. $connection = $this->connections->create($parameters);
  244. return $connection;
  245. }
  246. /**
  247. * {@inheritdoc}
  248. */
  249. public function getConnection(CommandInterface $command)
  250. {
  251. $hash = $this->strategy->getHash($command);
  252. if (!isset($hash)) {
  253. throw new NotSupportedException(
  254. "Cannot use {$command->getId()} with redis-cluster"
  255. );
  256. }
  257. $slot = $hash & 0x3FFF;
  258. if (isset($this->slots[$slot])) {
  259. return $this->slots[$slot];
  260. } else {
  261. return $this->getConnectionBySlot($slot);
  262. }
  263. }
  264. /**
  265. * Returns the connection currently associated to a given slot.
  266. *
  267. * @param int $slot Slot index.
  268. * @return SingleConnectionInterface
  269. */
  270. public function getConnectionBySlot($slot)
  271. {
  272. if ($slot < 0x0000 || $slot > 0x3FFF) {
  273. throw new OutOfBoundsException("Invalid slot [$slot]");
  274. }
  275. if (isset($this->slots[$slot])) {
  276. return $this->slots[$slot];
  277. }
  278. $connectionID = $this->guessNode($slot);
  279. if (!$connection = $this->getConnectionById($connectionID)) {
  280. $connection = $this->createConnection($connectionID);
  281. $this->pool[$connectionID] = $connection;
  282. }
  283. return $this->slots[$slot] = $connection;
  284. }
  285. /**
  286. * {@inheritdoc}
  287. */
  288. public function getConnectionById($connectionID)
  289. {
  290. if (isset($this->pool[$connectionID])) {
  291. return $this->pool[$connectionID];
  292. }
  293. }
  294. /**
  295. * Returns a random connection from the pool.
  296. *
  297. * @return SingleConnectionInterface
  298. */
  299. protected function getRandomConnection()
  300. {
  301. if ($this->pool) {
  302. return $this->pool[array_rand($this->pool)];
  303. }
  304. }
  305. /**
  306. * Permanently associates the connection instance to a new slot.
  307. * The connection is added to the connections pool if not yet included.
  308. *
  309. * @param SingleConnectionInterface $connection Connection instance.
  310. * @param int $slot Target slot index.
  311. */
  312. protected function move(SingleConnectionInterface $connection, $slot)
  313. {
  314. $this->pool[(string) $connection] = $connection;
  315. $this->slots[(int) $slot] = $connection;
  316. }
  317. /**
  318. * Handles -ERR responses returned by Redis.
  319. *
  320. * @param CommandInterface $command Command that generated the -ERR response.
  321. * @param ResponseErrorInterface $error Redis error response object.
  322. * @return mixed
  323. */
  324. protected function onErrorResponse(CommandInterface $command, ResponseErrorInterface $error)
  325. {
  326. $details = explode(' ', $error->getMessage(), 2);
  327. switch ($details[0]) {
  328. case 'MOVED':
  329. return $this->onMovedResponse($command, $details[1]);
  330. case 'ASK':
  331. return $this->onAskResponse($command, $details[1]);
  332. default:
  333. return $error;
  334. }
  335. }
  336. /**
  337. * Handles -MOVED responses by executing again the command against the node
  338. * indicated by the Redis response.
  339. *
  340. * @param CommandInterface $command Command that generated the -MOVED response.
  341. * @param string $details Parameters of the -MOVED response.
  342. * @return mixed
  343. */
  344. protected function onMovedResponse(CommandInterface $command, $details)
  345. {
  346. list($slot, $connectionID) = explode(' ', $details, 2);
  347. if (!$connection = $this->getConnectionById($connectionID)) {
  348. $connection = $this->createConnection($connectionID);
  349. }
  350. if ($this->askClusterNodes) {
  351. $this->askClusterNodes($connection);
  352. }
  353. $this->move($connection, $slot);
  354. $response = $this->executeCommand($command);
  355. return $response;
  356. }
  357. /**
  358. * Handles -ASK responses by executing again the command against the node
  359. * indicated by the Redis response.
  360. *
  361. * @param CommandInterface $command Command that generated the -ASK response.
  362. * @param string $details Parameters of the -ASK response.
  363. * @return mixed
  364. */
  365. protected function onAskResponse(CommandInterface $command, $details)
  366. {
  367. list($slot, $connectionID) = explode(' ', $details, 2);
  368. if (!$connection = $this->getConnectionById($connectionID)) {
  369. $connection = $this->createConnection($connectionID);
  370. }
  371. $connection->executeCommand(RawCommand::create('ASKING'));
  372. $response = $connection->executeCommand($command);
  373. return $response;
  374. }
  375. /**
  376. * {@inheritdoc}
  377. */
  378. public function writeCommand(CommandInterface $command)
  379. {
  380. $this->getConnection($command)->writeCommand($command);
  381. }
  382. /**
  383. * {@inheritdoc}
  384. */
  385. public function readResponse(CommandInterface $command)
  386. {
  387. return $this->getConnection($command)->readResponse($command);
  388. }
  389. /**
  390. * {@inheritdoc}
  391. */
  392. public function executeCommand(CommandInterface $command)
  393. {
  394. $connection = $this->getConnection($command);
  395. $response = $connection->executeCommand($command);
  396. if ($response instanceof ResponseErrorInterface) {
  397. return $this->onErrorResponse($command, $response);
  398. }
  399. return $response;
  400. }
  401. /**
  402. * {@inheritdoc}
  403. */
  404. public function count()
  405. {
  406. return count($this->pool);
  407. }
  408. /**
  409. * {@inheritdoc}
  410. */
  411. public function getIterator()
  412. {
  413. return new ArrayIterator(array_values($this->pool));
  414. }
  415. /**
  416. * Returns the underlying hash strategy used to hash commands by their keys.
  417. *
  418. * @return CommandHashStrategyInterface
  419. */
  420. public function getCommandHashStrategy()
  421. {
  422. return $this->strategy;
  423. }
  424. /**
  425. * Enables automatic fetching of the current slots map from one of the nodes
  426. * using the CLUSTER SLOTS command. This option is disabled by default but
  427. * asking the current slots map to Redis upon -MOVED responses may reduce
  428. * overhead by eliminating the trial-and-error nature of the node guessing
  429. * procedure, mostly when targeting many keys that would end up in a lot of
  430. * redirections.
  431. *
  432. * The slots map can still be manually fetched using the askClusterNodes()
  433. * method whether or not this option is enabled.
  434. *
  435. * @param bool $value Enable or disable the use of CLUSTER SLOTS.
  436. */
  437. public function enableClusterNodes($value)
  438. {
  439. $this->askClusterNodes = (bool) $value;
  440. }
  441. /**
  442. * Sets a default array of connection parameters to be applied when creating
  443. * new connection instances on the fly when they are not part of the initial
  444. * pool supplied upon cluster initialization.
  445. *
  446. * These parameters are not applied to connections added to the pool using
  447. * the add() method.
  448. *
  449. * @param array $parameters Array of connection parameters.
  450. */
  451. public function setDefaultParameters(array $parameters)
  452. {
  453. $this->defaultParameters = array_merge(
  454. $this->defaultParameters,
  455. $parameters ?: array()
  456. );
  457. }
  458. }