PredisReplication.php 10 KB

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