WebdisConnection.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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\Command\CommandInterface;
  12. use Predis\NotSupportedException;
  13. use Predis\Protocol\ProtocolException;
  14. use Predis\Response\Error as ErrorResponse;
  15. use Predis\Response\Status as StatusResponse;
  16. /**
  17. * This class implements a Predis connection that actually talks with Webdis
  18. * instead of connecting directly to Redis. It relies on the cURL extension to
  19. * communicate with the web server and the phpiredis extension to parse the
  20. * protocol for responses returned in the http response bodies.
  21. *
  22. * Some features are not yet available or they simply cannot be implemented:
  23. * - Pipelining commands.
  24. * - Publish / Subscribe.
  25. * - MULTI / EXEC transactions (not yet supported by Webdis).
  26. *
  27. * The connection parameters supported by this class are:
  28. *
  29. * - scheme: must be 'http'.
  30. * - host: hostname or IP address of the server.
  31. * - port: TCP port of the server.
  32. * - timeout: timeout to perform the connection.
  33. * - user: username for authentication.
  34. * - pass: password for authentication.
  35. *
  36. * @link http://webd.is
  37. * @link http://github.com/nicolasff/webdis
  38. * @link http://github.com/seppo0010/phpiredis
  39. *
  40. * @author Daniele Alessandri <suppakilla@gmail.com>
  41. */
  42. class WebdisConnection implements NodeConnectionInterface
  43. {
  44. private $parameters;
  45. private $resource;
  46. private $reader;
  47. /**
  48. * @param ParametersInterface $parameters Initialization parameters for the connection.
  49. *
  50. * @throws \InvalidArgumentException
  51. */
  52. public function __construct(ParametersInterface $parameters)
  53. {
  54. $this->assertExtensions();
  55. if ($parameters->scheme !== 'http') {
  56. throw new \InvalidArgumentException("Invalid scheme: '{$parameters->scheme}'.");
  57. }
  58. $this->parameters = $parameters;
  59. $this->resource = $this->createCurl();
  60. $this->reader = $this->createReader();
  61. }
  62. /**
  63. * Frees the underlying cURL and protocol reader resources when the garbage
  64. * collector kicks in.
  65. */
  66. public function __destruct()
  67. {
  68. curl_close($this->resource);
  69. phpiredis_reader_destroy($this->reader);
  70. }
  71. /**
  72. * Helper method used to throw on unsupported methods.
  73. *
  74. * @param string $method Name of the unsupported method.
  75. *
  76. * @throws NotSupportedException
  77. */
  78. private function throwNotSupportedException($method)
  79. {
  80. $class = __CLASS__;
  81. throw new NotSupportedException("The method $class::$method() is not supported.");
  82. }
  83. /**
  84. * Checks if the cURL and phpiredis extensions are loaded in PHP.
  85. */
  86. private function assertExtensions()
  87. {
  88. if (!extension_loaded('curl')) {
  89. throw new NotSupportedException(
  90. 'The "curl" extension is required by this connection backend.'
  91. );
  92. }
  93. if (!extension_loaded('phpiredis')) {
  94. throw new NotSupportedException(
  95. 'The "phpiredis" extension is required by this connection backend.'
  96. );
  97. }
  98. }
  99. /**
  100. * Initializes cURL.
  101. *
  102. * @return resource
  103. */
  104. private function createCurl()
  105. {
  106. $parameters = $this->getParameters();
  107. if (filter_var($host = $parameters->host, FILTER_VALIDATE_IP)) {
  108. $host = "[$host]";
  109. }
  110. $options = array(
  111. CURLOPT_FAILONERROR => true,
  112. CURLOPT_CONNECTTIMEOUT_MS => $parameters->timeout * 1000,
  113. CURLOPT_URL => "$parameters->scheme://$host:$parameters->port",
  114. CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  115. CURLOPT_POST => true,
  116. CURLOPT_WRITEFUNCTION => array($this, 'feedReader'),
  117. );
  118. if (isset($parameters->user, $parameters->pass)) {
  119. $options[CURLOPT_USERPWD] = "{$parameters->user}:{$parameters->pass}";
  120. }
  121. curl_setopt_array($resource = curl_init(), $options);
  122. return $resource;
  123. }
  124. /**
  125. * Initializes the phpiredis protocol reader.
  126. *
  127. * @return resource
  128. */
  129. private function createReader()
  130. {
  131. $reader = phpiredis_reader_create();
  132. phpiredis_reader_set_status_handler($reader, $this->getStatusHandler());
  133. phpiredis_reader_set_error_handler($reader, $this->getErrorHandler());
  134. return $reader;
  135. }
  136. /**
  137. * Returns the handler used by the protocol reader for inline responses.
  138. *
  139. * @return \Closure
  140. */
  141. protected function getStatusHandler()
  142. {
  143. return function ($payload) {
  144. return StatusResponse::get($payload);
  145. };
  146. }
  147. /**
  148. * Returns the handler used by the protocol reader for error responses.
  149. *
  150. * @return \Closure
  151. */
  152. protected function getErrorHandler()
  153. {
  154. return function ($payload) {
  155. return new ErrorResponse($payload);
  156. };
  157. }
  158. /**
  159. * Feeds the phpredis reader resource with the data read from the network.
  160. *
  161. * @param resource $resource Reader resource.
  162. * @param string $buffer Buffer of data read from a connection.
  163. *
  164. * @return int
  165. */
  166. protected function feedReader($resource, $buffer)
  167. {
  168. phpiredis_reader_feed($this->reader, $buffer);
  169. return strlen($buffer);
  170. }
  171. /**
  172. * {@inheritdoc}
  173. */
  174. public function connect()
  175. {
  176. // NOOP
  177. }
  178. /**
  179. * {@inheritdoc}
  180. */
  181. public function disconnect()
  182. {
  183. // NOOP
  184. }
  185. /**
  186. * {@inheritdoc}
  187. */
  188. public function isConnected()
  189. {
  190. return true;
  191. }
  192. /**
  193. * Checks if the specified command is supported by this connection class.
  194. *
  195. * @param CommandInterface $command Command instance.
  196. *
  197. * @throws NotSupportedException
  198. *
  199. * @return string
  200. */
  201. protected function getCommandId(CommandInterface $command)
  202. {
  203. switch ($commandID = $command->getId()) {
  204. case 'AUTH':
  205. case 'SELECT':
  206. case 'MULTI':
  207. case 'EXEC':
  208. case 'WATCH':
  209. case 'UNWATCH':
  210. case 'DISCARD':
  211. case 'MONITOR':
  212. throw new NotSupportedException("Command '$commandID' is not allowed by Webdis.");
  213. default:
  214. return $commandID;
  215. }
  216. }
  217. /**
  218. * {@inheritdoc}
  219. */
  220. public function writeRequest(CommandInterface $command)
  221. {
  222. $this->throwNotSupportedException(__FUNCTION__);
  223. }
  224. /**
  225. * {@inheritdoc}
  226. */
  227. public function readResponse(CommandInterface $command)
  228. {
  229. $this->throwNotSupportedException(__FUNCTION__);
  230. }
  231. /**
  232. * {@inheritdoc}
  233. */
  234. public function executeCommand(CommandInterface $command)
  235. {
  236. $resource = $this->resource;
  237. $commandId = $this->getCommandId($command);
  238. if ($arguments = $command->getArguments()) {
  239. $arguments = implode('/', array_map('urlencode', $arguments));
  240. $serializedCommand = "$commandId/$arguments.raw";
  241. } else {
  242. $serializedCommand = "$commandId.raw";
  243. }
  244. curl_setopt($resource, CURLOPT_POSTFIELDS, $serializedCommand);
  245. if (curl_exec($resource) === false) {
  246. $error = curl_error($resource);
  247. $errno = curl_errno($resource);
  248. throw new ConnectionException($this, trim($error), $errno);
  249. }
  250. if (phpiredis_reader_get_state($this->reader) !== PHPIREDIS_READER_STATE_COMPLETE) {
  251. throw new ProtocolException($this, phpiredis_reader_get_error($this->reader));
  252. }
  253. return phpiredis_reader_get_reply($this->reader);
  254. }
  255. /**
  256. * {@inheritdoc}
  257. */
  258. public function getResource()
  259. {
  260. return $this->resource;
  261. }
  262. /**
  263. * {@inheritdoc}
  264. */
  265. public function getParameters()
  266. {
  267. return $this->parameters;
  268. }
  269. /**
  270. * {@inheritdoc}
  271. */
  272. public function addConnectCommand(CommandInterface $command)
  273. {
  274. $this->throwNotSupportedException(__FUNCTION__);
  275. }
  276. /**
  277. * {@inheritdoc}
  278. */
  279. public function read()
  280. {
  281. $this->throwNotSupportedException(__FUNCTION__);
  282. }
  283. /**
  284. * {@inheritdoc}
  285. */
  286. public function __toString()
  287. {
  288. return "{$this->parameters->host}:{$this->parameters->port}";
  289. }
  290. /**
  291. * {@inheritdoc}
  292. */
  293. public function __sleep()
  294. {
  295. return array('parameters');
  296. }
  297. /**
  298. * {@inheritdoc}
  299. */
  300. public function __wakeup()
  301. {
  302. $this->assertExtensions();
  303. $this->resource = $this->createCurl();
  304. $this->reader = $this->createReader();
  305. }
  306. }