MasterSlaveReplication.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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\NotSupportedException;
  12. use Predis\Command\CommandInterface;
  13. /**
  14. * Defines the standard virtual connection class that is used
  15. * by Predis to handle replication with a group of servers in
  16. * a master/slave configuration.
  17. *
  18. * @author Daniele Alessandri <suppakilla@gmail.com>
  19. */
  20. class MasterSlaveReplication implements ReplicationConnectionInterface
  21. {
  22. private $disallowed = array();
  23. private $readonly = array();
  24. private $readonlySHA1 = array();
  25. private $current = null;
  26. private $master = null;
  27. private $slaves = array();
  28. /**
  29. *
  30. */
  31. public function __construct()
  32. {
  33. $this->disallowed = $this->getDisallowedOperations();
  34. $this->readonly = $this->getReadOnlyOperations();
  35. }
  36. /**
  37. * Checks if one master and at least one slave have been defined.
  38. */
  39. protected function check()
  40. {
  41. if (!isset($this->master) || !$this->slaves) {
  42. throw new \RuntimeException('Replication needs a master and at least one slave.');
  43. }
  44. }
  45. /**
  46. * Resets the connection state.
  47. */
  48. protected function reset()
  49. {
  50. $this->current = null;
  51. }
  52. /**
  53. * {@inheritdoc}
  54. */
  55. public function add(SingleConnectionInterface $connection)
  56. {
  57. $alias = $connection->getParameters()->alias;
  58. if ($alias === 'master') {
  59. $this->master = $connection;
  60. } else {
  61. $this->slaves[$alias ?: count($this->slaves)] = $connection;
  62. }
  63. $this->reset();
  64. }
  65. /**
  66. * {@inheritdoc}
  67. */
  68. public function remove(SingleConnectionInterface $connection)
  69. {
  70. if ($connection->getParameters()->alias === 'master') {
  71. $this->master = null;
  72. $this->reset();
  73. return true;
  74. } else {
  75. if (($id = array_search($connection, $this->slaves, true)) !== false) {
  76. unset($this->slaves[$id]);
  77. $this->reset();
  78. return true;
  79. }
  80. }
  81. return false;
  82. }
  83. /**
  84. * {@inheritdoc}
  85. */
  86. public function getConnection(CommandInterface $command)
  87. {
  88. if ($this->current === null) {
  89. $this->check();
  90. $this->current = $this->isReadOperation($command) ? $this->pickSlave() : $this->master;
  91. return $this->current;
  92. }
  93. if ($this->current === $this->master) {
  94. return $this->current;
  95. }
  96. if (!$this->isReadOperation($command)) {
  97. $this->current = $this->master;
  98. }
  99. return $this->current;
  100. }
  101. /**
  102. * {@inheritdoc}
  103. */
  104. public function getConnectionById($connectionId)
  105. {
  106. if ($connectionId === 'master') {
  107. return $this->master;
  108. }
  109. if (isset($this->slaves[$connectionId])) {
  110. return $this->slaves[$connectionId];
  111. }
  112. return null;
  113. }
  114. /**
  115. * {@inheritdoc}
  116. */
  117. public function switchTo($connection)
  118. {
  119. $this->check();
  120. if (!$connection instanceof SingleConnectionInterface) {
  121. $connection = $this->getConnectionById($connection);
  122. }
  123. if ($connection !== $this->master && !in_array($connection, $this->slaves, true)) {
  124. throw new \InvalidArgumentException('The specified connection is not valid.');
  125. }
  126. $this->current = $connection;
  127. }
  128. /**
  129. * {@inheritdoc}
  130. */
  131. public function getCurrent()
  132. {
  133. return $this->current;
  134. }
  135. /**
  136. * {@inheritdoc}
  137. */
  138. public function getMaster()
  139. {
  140. return $this->master;
  141. }
  142. /**
  143. * {@inheritdoc}
  144. */
  145. public function getSlaves()
  146. {
  147. return array_values($this->slaves);
  148. }
  149. /**
  150. * Returns a random slave.
  151. *
  152. * @return SingleConnectionInterface
  153. */
  154. protected function pickSlave()
  155. {
  156. return $this->slaves[array_rand($this->slaves)];
  157. }
  158. /**
  159. * {@inheritdoc}
  160. */
  161. public function isConnected()
  162. {
  163. return $this->current ? $this->current->isConnected() : false;
  164. }
  165. /**
  166. * {@inheritdoc}
  167. */
  168. public function connect()
  169. {
  170. if ($this->current === null) {
  171. $this->check();
  172. $this->current = $this->pickSlave();
  173. }
  174. $this->current->connect();
  175. }
  176. /**
  177. * {@inheritdoc}
  178. */
  179. public function disconnect()
  180. {
  181. if ($this->master) {
  182. $this->master->disconnect();
  183. }
  184. foreach ($this->slaves as $connection) {
  185. $connection->disconnect();
  186. }
  187. }
  188. /**
  189. * {@inheritdoc}
  190. */
  191. public function writeCommand(CommandInterface $command)
  192. {
  193. $this->getConnection($command)->writeCommand($command);
  194. }
  195. /**
  196. * {@inheritdoc}
  197. */
  198. public function readResponse(CommandInterface $command)
  199. {
  200. return $this->getConnection($command)->readResponse($command);
  201. }
  202. /**
  203. * {@inheritdoc}
  204. */
  205. public function executeCommand(CommandInterface $command)
  206. {
  207. return $this->getConnection($command)->executeCommand($command);
  208. }
  209. /**
  210. * Returns if the specified command performs a read-only operation
  211. * against a key stored on Redis.
  212. *
  213. * @param CommandInterface $command Instance of Redis command.
  214. * @return Boolean
  215. */
  216. protected function isReadOperation(CommandInterface $command)
  217. {
  218. if (isset($this->disallowed[$id = $command->getId()])) {
  219. throw new NotSupportedException("The command $id is not allowed in replication mode");
  220. }
  221. if (isset($this->readonly[$id])) {
  222. if (true === $readonly = $this->readonly[$id]) {
  223. return true;
  224. }
  225. return call_user_func($readonly, $command);
  226. }
  227. if (($eval = $id === 'EVAL') || $id === 'EVALSHA') {
  228. $sha1 = $eval ? sha1($command->getArgument(0)) : $command->getArgument(0);
  229. if (isset($this->readonlySHA1[$sha1])) {
  230. if (true === $readonly = $this->readonlySHA1[$sha1]) {
  231. return true;
  232. }
  233. return call_user_func($readonly, $command);
  234. }
  235. }
  236. return false;
  237. }
  238. /**
  239. * Checks if a SORT command is a readable operation by parsing the arguments
  240. * array of the specified commad instance.
  241. *
  242. * @param CommandInterface $command Instance of Redis command.
  243. * @return Boolean
  244. */
  245. private function isSortReadOnly(CommandInterface $command)
  246. {
  247. $arguments = $command->getArguments();
  248. return ($c = count($arguments)) === 1 ? true : $arguments[$c - 2] !== 'STORE';
  249. }
  250. /**
  251. * Marks a command as a read-only operation. When the behaviour of a
  252. * command can be decided only at runtime depending on its arguments,
  253. * a callable object can be provided to dinamically check if the passed
  254. * instance of a command performs write operations or not.
  255. *
  256. * @param string $commandID ID of the command.
  257. * @param mixed $readonly A boolean or a callable object.
  258. */
  259. public function setCommandReadOnly($commandID, $readonly = true)
  260. {
  261. $commandID = strtoupper($commandID);
  262. if ($readonly) {
  263. $this->readonly[$commandID] = $readonly;
  264. } else {
  265. unset($this->readonly[$commandID]);
  266. }
  267. }
  268. /**
  269. * Marks a Lua script for EVAL and EVALSHA as a read-only operation. When
  270. * the behaviour of a script can be decided only at runtime depending on
  271. * its arguments, a callable object can be provided to dinamically check
  272. * if the passed instance of EVAL or EVALSHA performs write operations or
  273. * not.
  274. *
  275. * @param string $script Body of the Lua script.
  276. * @param mixed $readonly A boolean or a callable object.
  277. */
  278. public function setScriptReadOnly($script, $readonly = true)
  279. {
  280. $sha1 = sha1($script);
  281. if ($readonly) {
  282. $this->readonlySHA1[$sha1] = $readonly;
  283. } else {
  284. unset($this->readonlySHA1[$sha1]);
  285. }
  286. }
  287. /**
  288. * Returns the default list of disallowed commands.
  289. *
  290. * @return array
  291. */
  292. protected function getDisallowedOperations()
  293. {
  294. return array(
  295. 'SHUTDOWN' => true,
  296. 'INFO' => true,
  297. 'DBSIZE' => true,
  298. 'LASTSAVE' => true,
  299. 'CONFIG' => true,
  300. 'MONITOR' => true,
  301. 'SLAVEOF' => true,
  302. 'SAVE' => true,
  303. 'BGSAVE' => true,
  304. 'BGREWRITEAOF' => true,
  305. 'SLOWLOG' => true,
  306. );
  307. }
  308. /**
  309. * Returns the default list of commands performing read-only operations.
  310. *
  311. * @return array
  312. */
  313. protected function getReadOnlyOperations()
  314. {
  315. return array(
  316. 'EXISTS' => true,
  317. 'TYPE' => true,
  318. 'KEYS' => true,
  319. 'RANDOMKEY' => true,
  320. 'TTL' => true,
  321. 'GET' => true,
  322. 'MGET' => true,
  323. 'SUBSTR' => true,
  324. 'STRLEN' => true,
  325. 'GETRANGE' => true,
  326. 'GETBIT' => true,
  327. 'LLEN' => true,
  328. 'LRANGE' => true,
  329. 'LINDEX' => true,
  330. 'SCARD' => true,
  331. 'SISMEMBER' => true,
  332. 'SINTER' => true,
  333. 'SUNION' => true,
  334. 'SDIFF' => true,
  335. 'SMEMBERS' => true,
  336. 'SRANDMEMBER' => true,
  337. 'ZRANGE' => true,
  338. 'ZREVRANGE' => true,
  339. 'ZRANGEBYSCORE' => true,
  340. 'ZREVRANGEBYSCORE' => true,
  341. 'ZCARD' => true,
  342. 'ZSCORE' => true,
  343. 'ZCOUNT' => true,
  344. 'ZRANK' => true,
  345. 'ZREVRANK' => true,
  346. 'HGET' => true,
  347. 'HMGET' => true,
  348. 'HEXISTS' => true,
  349. 'HLEN' => true,
  350. 'HKEYS' => true,
  351. 'HVELS' => true,
  352. 'HGETALL' => true,
  353. 'PING' => true,
  354. 'AUTH' => true,
  355. 'SELECT' => true,
  356. 'ECHO' => true,
  357. 'QUIT' => true,
  358. 'OBJECT' => true,
  359. 'BITCOUNT' => true,
  360. 'TIME' => true,
  361. 'SORT' => array($this, 'isSortReadOnly'),
  362. );
  363. }
  364. /**
  365. * {@inheritdoc}
  366. */
  367. public function __sleep()
  368. {
  369. return array('master', 'slaves', 'disallowed', 'readonly', 'readonlySHA1');
  370. }
  371. }