MasterSlaveReplication.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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\Aggregate;
  11. use Predis\ClientException;
  12. use Predis\Command\CommandInterface;
  13. use Predis\Connection\ConnectionException;
  14. use Predis\Connection\NodeConnectionInterface;
  15. use Predis\Replication\ReplicationStrategy;
  16. /**
  17. * Aggregate connection handling replication of Redis nodes configured in a
  18. * single master / multiple slaves setup.
  19. *
  20. * @author Daniele Alessandri <suppakilla@gmail.com>
  21. */
  22. class MasterSlaveReplication implements ReplicationInterface
  23. {
  24. /**
  25. * @var ReplicationStrategy
  26. */
  27. protected $strategy;
  28. /**
  29. * @var NodeConnectionInterface
  30. */
  31. protected $master;
  32. /**
  33. * @var NodeConnectionInterface[]
  34. */
  35. protected $slaves = array();
  36. /**
  37. * @var NodeConnectionInterface
  38. */
  39. protected $current;
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function __construct(ReplicationStrategy $strategy = null)
  44. {
  45. $this->strategy = $strategy ?: new ReplicationStrategy();
  46. }
  47. /**
  48. * Resets the connection state.
  49. */
  50. protected function reset()
  51. {
  52. $this->current = null;
  53. }
  54. /**
  55. * {@inheritdoc}
  56. */
  57. public function add(NodeConnectionInterface $connection)
  58. {
  59. $alias = $connection->getParameters()->alias;
  60. if ($alias === 'master') {
  61. $this->master = $connection;
  62. } else {
  63. $this->slaves[$alias ?: "slave-$connection"] = $connection;
  64. }
  65. $this->reset();
  66. }
  67. /**
  68. * {@inheritdoc}
  69. */
  70. public function remove(NodeConnectionInterface $connection)
  71. {
  72. if ($connection->getParameters()->alias === 'master') {
  73. $this->master = null;
  74. $this->reset();
  75. return true;
  76. } else {
  77. if (($id = array_search($connection, $this->slaves, true)) !== false) {
  78. unset($this->slaves[$id]);
  79. $this->reset();
  80. return true;
  81. }
  82. }
  83. return false;
  84. }
  85. /**
  86. * {@inheritdoc}
  87. */
  88. public function getConnection(CommandInterface $command)
  89. {
  90. if (!$this->current) {
  91. if ($this->strategy->isReadOperation($command) && $slave = $this->pickSlave()) {
  92. $this->current = $slave;
  93. } else {
  94. $this->current = $this->getMasterOrDie();
  95. }
  96. return $this->current;
  97. }
  98. if ($this->current === $master = $this->getMasterOrDie()) {
  99. return $master;
  100. }
  101. if (!$this->strategy->isReadOperation($command) || !$this->slaves) {
  102. $this->current = $master;
  103. }
  104. return $this->current;
  105. }
  106. /**
  107. * {@inheritdoc}
  108. */
  109. public function getConnectionById($connectionId)
  110. {
  111. if ($connectionId === 'master') {
  112. return $this->master;
  113. }
  114. if (isset($this->slaves[$connectionId])) {
  115. return $this->slaves[$connectionId];
  116. }
  117. return;
  118. }
  119. /**
  120. * {@inheritdoc}
  121. */
  122. public function switchTo($connection)
  123. {
  124. if (!$connection instanceof NodeConnectionInterface) {
  125. $connection = $this->getConnectionById($connection);
  126. }
  127. if (!$connection) {
  128. throw new \InvalidArgumentException('Invalid connection or connection not found.');
  129. }
  130. if ($connection !== $this->master && !in_array($connection, $this->slaves, true)) {
  131. throw new \InvalidArgumentException('Invalid connection or connection not found.');
  132. }
  133. $this->current = $connection;
  134. }
  135. /**
  136. * Switches to the master server.
  137. */
  138. public function switchToMaster()
  139. {
  140. $this->switchTo('master');
  141. }
  142. /**
  143. * Switches to a random slave server.
  144. */
  145. public function switchToSlave()
  146. {
  147. $connection = $this->pickSlave();
  148. $this->switchTo($connection);
  149. }
  150. /**
  151. * {@inheritdoc}
  152. */
  153. public function getCurrent()
  154. {
  155. return $this->current;
  156. }
  157. /**
  158. * {@inheritdoc}
  159. */
  160. public function getMaster()
  161. {
  162. return $this->master;
  163. }
  164. /**
  165. * Returns the connection associated to the master server.
  166. *
  167. * @return NodeConnectionInterface
  168. */
  169. private function getMasterOrDie()
  170. {
  171. if (!$connection = $this->getMaster()) {
  172. throw new ClientException('No master server available for replication');
  173. }
  174. return $connection;
  175. }
  176. /**
  177. * {@inheritdoc}
  178. */
  179. public function getSlaves()
  180. {
  181. return array_values($this->slaves);
  182. }
  183. /**
  184. * Returns the underlying replication strategy.
  185. *
  186. * @return ReplicationStrategy
  187. */
  188. public function getReplicationStrategy()
  189. {
  190. return $this->strategy;
  191. }
  192. /**
  193. * Returns a random slave.
  194. *
  195. * @return NodeConnectionInterface
  196. */
  197. protected function pickSlave()
  198. {
  199. if ($this->slaves) {
  200. return $this->slaves[array_rand($this->slaves)];
  201. }
  202. }
  203. /**
  204. * {@inheritdoc}
  205. */
  206. public function isConnected()
  207. {
  208. return $this->current ? $this->current->isConnected() : false;
  209. }
  210. /**
  211. * {@inheritdoc}
  212. */
  213. public function connect()
  214. {
  215. if (!$this->current) {
  216. if (!$this->current = $this->pickSlave()) {
  217. if (!$this->current = $this->getMaster()) {
  218. throw new ClientException("No available connection for replication");
  219. }
  220. }
  221. }
  222. $this->current->connect();
  223. }
  224. /**
  225. * {@inheritdoc}
  226. */
  227. public function disconnect()
  228. {
  229. if ($this->master) {
  230. $this->master->disconnect();
  231. }
  232. foreach ($this->slaves as $connection) {
  233. $connection->disconnect();
  234. }
  235. }
  236. /**
  237. * Retries the execution of a command upon slave failure.
  238. *
  239. * @param CommandInterface $command Command instance.
  240. * @param string $method Actual method.
  241. *
  242. * @return mixed
  243. */
  244. private function retryCommandOnFailure(CommandInterface $command, $method)
  245. {
  246. RETRY_COMMAND: {
  247. try {
  248. $response = $this->getConnection($command)->$method($command);
  249. } catch (ConnectionException $exception) {
  250. $connection = $exception->getConnection();
  251. $connection->disconnect();
  252. if ($connection === $this->master) {
  253. // Throw immediatly if the client was connected to master,
  254. // even when the command represents a read-only operation.
  255. throw $exception;
  256. } else {
  257. // Otherwise remove the failing slave and attempt to execute
  258. // the command again on one of the remaining slaves...
  259. $this->remove($connection);
  260. }
  261. // ... that is, unless we have no more connections to use.
  262. if (!$this->slaves && !$this->master) {
  263. throw $exception;
  264. }
  265. goto RETRY_COMMAND;
  266. }
  267. }
  268. return $response;
  269. }
  270. /**
  271. * {@inheritdoc}
  272. */
  273. public function writeRequest(CommandInterface $command)
  274. {
  275. $this->retryCommandOnFailure($command, __FUNCTION__);
  276. }
  277. /**
  278. * {@inheritdoc}
  279. */
  280. public function readResponse(CommandInterface $command)
  281. {
  282. return $this->retryCommandOnFailure($command, __FUNCTION__);
  283. }
  284. /**
  285. * {@inheritdoc}
  286. */
  287. public function executeCommand(CommandInterface $command)
  288. {
  289. return $this->retryCommandOnFailure($command, __FUNCTION__);
  290. }
  291. /**
  292. * {@inheritdoc}
  293. */
  294. public function __sleep()
  295. {
  296. return array('master', 'slaves', 'strategy');
  297. }
  298. }