WebdisConnection.php 8.7 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;
  11. use Predis\NotSupportedException;
  12. use Predis\Command\CommandInterface;
  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. $options = array(
  108. CURLOPT_FAILONERROR => true,
  109. CURLOPT_CONNECTTIMEOUT_MS => $parameters->timeout * 1000,
  110. CURLOPT_URL => "{$parameters->scheme}://{$parameters->host}:{$parameters->port}",
  111. CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  112. CURLOPT_POST => true,
  113. CURLOPT_WRITEFUNCTION => array($this, 'feedReader'),
  114. );
  115. if (isset($parameters->user, $parameters->pass)) {
  116. $options[CURLOPT_USERPWD] = "{$parameters->user}:{$parameters->pass}";
  117. }
  118. curl_setopt_array($resource = curl_init(), $options);
  119. return $resource;
  120. }
  121. /**
  122. * Initializes the phpiredis protocol reader.
  123. *
  124. * @return resource
  125. */
  126. private function createReader()
  127. {
  128. $reader = phpiredis_reader_create();
  129. phpiredis_reader_set_status_handler($reader, $this->getStatusHandler());
  130. phpiredis_reader_set_error_handler($reader, $this->getErrorHandler());
  131. return $reader;
  132. }
  133. /**
  134. * Returns the handler used by the protocol reader for inline responses.
  135. *
  136. * @return \Closure
  137. */
  138. protected function getStatusHandler()
  139. {
  140. return function ($payload) {
  141. return StatusResponse::get($payload);
  142. };
  143. }
  144. /**
  145. * Returns the handler used by the protocol reader for error responses.
  146. *
  147. * @return \Closure
  148. */
  149. protected function getErrorHandler()
  150. {
  151. return function ($payload) {
  152. return new ErrorResponse($payload);
  153. };
  154. }
  155. /**
  156. * Feeds the phpredis reader resource with the data read from the network.
  157. *
  158. * @param resource $resource Reader resource.
  159. * @param string $buffer Buffer of data read from a connection.
  160. *
  161. * @return int
  162. */
  163. protected function feedReader($resource, $buffer)
  164. {
  165. phpiredis_reader_feed($this->reader, $buffer);
  166. return strlen($buffer);
  167. }
  168. /**
  169. * {@inheritdoc}
  170. */
  171. public function connect()
  172. {
  173. // NOOP
  174. }
  175. /**
  176. * {@inheritdoc}
  177. */
  178. public function disconnect()
  179. {
  180. // NOOP
  181. }
  182. /**
  183. * {@inheritdoc}
  184. */
  185. public function isConnected()
  186. {
  187. return true;
  188. }
  189. /**
  190. * Checks if the specified command is supported by this connection class.
  191. *
  192. * @param CommandInterface $command Command instance.
  193. *
  194. * @return string
  195. *
  196. * @throws NotSupportedException
  197. */
  198. protected function getCommandId(CommandInterface $command)
  199. {
  200. switch ($commandID = $command->getId()) {
  201. case 'AUTH':
  202. case 'SELECT':
  203. case 'MULTI':
  204. case 'EXEC':
  205. case 'WATCH':
  206. case 'UNWATCH':
  207. case 'DISCARD':
  208. case 'MONITOR':
  209. throw new NotSupportedException("Command '$commandID' is not allowed by Webdis.");
  210. default:
  211. return $commandID;
  212. }
  213. }
  214. /**
  215. * {@inheritdoc}
  216. */
  217. public function writeRequest(CommandInterface $command)
  218. {
  219. $this->throwNotSupportedException(__FUNCTION__);
  220. }
  221. /**
  222. * {@inheritdoc}
  223. */
  224. public function readResponse(CommandInterface $command)
  225. {
  226. $this->throwNotSupportedException(__FUNCTION__);
  227. }
  228. /**
  229. * {@inheritdoc}
  230. */
  231. public function executeCommand(CommandInterface $command)
  232. {
  233. $resource = $this->resource;
  234. $commandId = $this->getCommandId($command);
  235. if ($arguments = $command->getArguments()) {
  236. $arguments = implode('/', array_map('urlencode', $arguments));
  237. $serializedCommand = "$commandId/$arguments.raw";
  238. } else {
  239. $serializedCommand = "$commandId.raw";
  240. }
  241. curl_setopt($resource, CURLOPT_POSTFIELDS, $serializedCommand);
  242. if (curl_exec($resource) === false) {
  243. $error = curl_error($resource);
  244. $errno = curl_errno($resource);
  245. throw new ConnectionException($this, trim($error), $errno);
  246. }
  247. if (phpiredis_reader_get_state($this->reader) !== PHPIREDIS_READER_STATE_COMPLETE) {
  248. throw new ProtocolException($this, phpiredis_reader_get_error($this->reader));
  249. }
  250. return phpiredis_reader_get_reply($this->reader);
  251. }
  252. /**
  253. * {@inheritdoc}
  254. */
  255. public function getResource()
  256. {
  257. return $this->resource;
  258. }
  259. /**
  260. * {@inheritdoc}
  261. */
  262. public function getParameters()
  263. {
  264. return $this->parameters;
  265. }
  266. /**
  267. * {@inheritdoc}
  268. */
  269. public function addConnectCommand(CommandInterface $command)
  270. {
  271. $this->throwNotSupportedException(__FUNCTION__);
  272. }
  273. /**
  274. * {@inheritdoc}
  275. */
  276. public function read()
  277. {
  278. $this->throwNotSupportedException(__FUNCTION__);
  279. }
  280. /**
  281. * {@inheritdoc}
  282. */
  283. public function __toString()
  284. {
  285. return "{$this->parameters->host}:{$this->parameters->port}";
  286. }
  287. /**
  288. * {@inheritdoc}
  289. */
  290. public function __sleep()
  291. {
  292. return array('parameters');
  293. }
  294. /**
  295. * {@inheritdoc}
  296. */
  297. public function __wakeup()
  298. {
  299. $this->assertExtensions();
  300. $this->resource = $this->createCurl();
  301. $this->reader = $this->createReader();
  302. }
  303. }