PhpiredisSocketConnection.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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\Response\Error as ErrorResponse;
  14. use Predis\Response\ErrorInterface as ErrorResponseInterface;
  15. use Predis\Response\Status as StatusResponse;
  16. /**
  17. * This class provides the implementation of a Predis connection that uses the
  18. * PHP socket extension for network communication and wraps the phpiredis C
  19. * extension (PHP bindings for hiredis) to parse the Redis protocol.
  20. *
  21. * This class is intended to provide an optional low-overhead alternative for
  22. * processing responses from Redis compared to the standard pure-PHP classes.
  23. * Differences in speed when dealing with short inline responses are practically
  24. * nonexistent, the actual speed boost is for big multibulk responses when this
  25. * protocol processor can parse and return responses very fast.
  26. *
  27. * For instructions on how to build and install the phpiredis extension, please
  28. * consult the repository of the project.
  29. *
  30. * The connection parameters supported by this class are:
  31. *
  32. * - scheme: it can be either 'redis', 'tcp' or 'unix'.
  33. * - host: hostname or IP address of the server.
  34. * - port: TCP port of the server.
  35. * - path: path of a UNIX domain socket when scheme is 'unix'.
  36. * - timeout: timeout to perform the connection (default is 5 seconds).
  37. * - read_write_timeout: timeout of read / write operations.
  38. *
  39. * @link http://github.com/nrk/phpiredis
  40. *
  41. * @author Daniele Alessandri <suppakilla@gmail.com>
  42. */
  43. class PhpiredisSocketConnection extends AbstractConnection
  44. {
  45. private $reader;
  46. /**
  47. * {@inheritdoc}
  48. */
  49. public function __construct(ParametersInterface $parameters)
  50. {
  51. $this->assertExtensions();
  52. parent::__construct($parameters);
  53. $this->reader = $this->createReader();
  54. }
  55. /**
  56. * Disconnects from the server and destroys the underlying resource and the
  57. * protocol reader resource when PHP's garbage collector kicks in.
  58. */
  59. public function __destruct()
  60. {
  61. phpiredis_reader_destroy($this->reader);
  62. parent::__destruct();
  63. }
  64. /**
  65. * Checks if the socket and phpiredis extensions are loaded in PHP.
  66. */
  67. protected function assertExtensions()
  68. {
  69. if (!extension_loaded('sockets')) {
  70. throw new NotSupportedException(
  71. 'The "sockets" extension is required by this connection backend.'
  72. );
  73. }
  74. if (!extension_loaded('phpiredis')) {
  75. throw new NotSupportedException(
  76. 'The "phpiredis" extension is required by this connection backend.'
  77. );
  78. }
  79. }
  80. /**
  81. * {@inheritdoc}
  82. */
  83. protected function assertParameters(ParametersInterface $parameters)
  84. {
  85. switch ($parameters->scheme) {
  86. case 'tcp':
  87. case 'redis':
  88. case 'unix':
  89. break;
  90. default:
  91. throw new \InvalidArgumentException("Invalid scheme: '$parameters->scheme'.");
  92. }
  93. if (isset($parameters->persistent)) {
  94. throw new NotSupportedException(
  95. 'Persistent connections are not supported by this connection backend.'
  96. );
  97. }
  98. return $parameters;
  99. }
  100. /**
  101. * Creates a new instance of the protocol reader resource.
  102. *
  103. * @return resource
  104. */
  105. private function createReader()
  106. {
  107. $reader = phpiredis_reader_create();
  108. phpiredis_reader_set_status_handler($reader, $this->getStatusHandler());
  109. phpiredis_reader_set_error_handler($reader, $this->getErrorHandler());
  110. return $reader;
  111. }
  112. /**
  113. * Returns the underlying protocol reader resource.
  114. *
  115. * @return resource
  116. */
  117. protected function getReader()
  118. {
  119. return $this->reader;
  120. }
  121. /**
  122. * Returns the handler used by the protocol reader for inline responses.
  123. *
  124. * @return \Closure
  125. */
  126. protected function getStatusHandler()
  127. {
  128. static $statusHandler;
  129. if (!$statusHandler) {
  130. $statusHandler = function ($payload) {
  131. return StatusResponse::get($payload);
  132. };
  133. }
  134. return $statusHandler;
  135. }
  136. /**
  137. * Returns the handler used by the protocol reader for error responses.
  138. *
  139. * @return \Closure
  140. */
  141. protected function getErrorHandler()
  142. {
  143. static $errorHandler;
  144. if (!$errorHandler) {
  145. $errorHandler = function ($errorMessage) {
  146. return new ErrorResponse($errorMessage);
  147. };
  148. }
  149. return $errorHandler;
  150. }
  151. /**
  152. * Helper method used to throw exceptions on socket errors.
  153. */
  154. private function emitSocketError()
  155. {
  156. $errno = socket_last_error();
  157. $errstr = socket_strerror($errno);
  158. $this->disconnect();
  159. $this->onConnectionError(trim($errstr), $errno);
  160. }
  161. /**
  162. * Gets the address of an host from connection parameters.
  163. *
  164. * @param ParametersInterface $parameters Parameters used to initialize the connection.
  165. *
  166. * @return string
  167. */
  168. protected static function getAddress(ParametersInterface $parameters)
  169. {
  170. if (filter_var($host = $parameters->host, FILTER_VALIDATE_IP)) {
  171. return $host;
  172. }
  173. if ($host === $address = gethostbyname($host)) {
  174. return false;
  175. }
  176. return $address;
  177. }
  178. /**
  179. * {@inheritdoc}
  180. */
  181. protected function createResource()
  182. {
  183. $parameters = $this->parameters;
  184. if ($parameters->scheme === 'unix') {
  185. $address = $parameters->path;
  186. $domain = AF_UNIX;
  187. $protocol = 0;
  188. } else {
  189. if (false === $address = self::getAddress($parameters)) {
  190. $this->onConnectionError("Cannot resolve the address of '$parameters->host'.");
  191. }
  192. $domain = filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ? AF_INET6 : AF_INET;
  193. $protocol = SOL_TCP;
  194. }
  195. $socket = @socket_create($domain, SOCK_STREAM, $protocol);
  196. if (!is_resource($socket)) {
  197. $this->emitSocketError();
  198. }
  199. $this->setSocketOptions($socket, $parameters);
  200. $this->connectWithTimeout($socket, $address, $parameters);
  201. return $socket;
  202. }
  203. /**
  204. * Sets options on the socket resource from the connection parameters.
  205. *
  206. * @param resource $socket Socket resource.
  207. * @param ParametersInterface $parameters Parameters used to initialize the connection.
  208. */
  209. private function setSocketOptions($socket, ParametersInterface $parameters)
  210. {
  211. if ($parameters->scheme !== 'unix') {
  212. if (!socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1)) {
  213. $this->emitSocketError();
  214. }
  215. if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
  216. $this->emitSocketError();
  217. }
  218. }
  219. if (isset($parameters->read_write_timeout)) {
  220. $rwtimeout = (float) $parameters->read_write_timeout;
  221. $timeoutSec = floor($rwtimeout);
  222. $timeoutUsec = ($rwtimeout - $timeoutSec) * 1000000;
  223. $timeout = array(
  224. 'sec' => $timeoutSec,
  225. 'usec' => $timeoutUsec,
  226. );
  227. if (!socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $timeout)) {
  228. $this->emitSocketError();
  229. }
  230. if (!socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout)) {
  231. $this->emitSocketError();
  232. }
  233. }
  234. }
  235. /**
  236. * Opens the actual connection to the server with a timeout.
  237. *
  238. * @param resource $socket Socket resource.
  239. * @param string $address IP address (DNS-resolved from hostname)
  240. * @param ParametersInterface $parameters Parameters used to initialize the connection.
  241. *
  242. * @return string
  243. */
  244. private function connectWithTimeout($socket, $address, ParametersInterface $parameters)
  245. {
  246. socket_set_nonblock($socket);
  247. if (@socket_connect($socket, $address, (int) $parameters->port) === false) {
  248. $error = socket_last_error();
  249. if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) {
  250. $this->emitSocketError();
  251. }
  252. }
  253. socket_set_block($socket);
  254. $null = null;
  255. $selectable = array($socket);
  256. $timeout = (isset($parameters->timeout) ? (float) $parameters->timeout : 5.0);
  257. $timeoutSecs = floor($timeout);
  258. $timeoutUSecs = ($timeout - $timeoutSecs) * 1000000;
  259. $selected = socket_select($selectable, $selectable, $null, $timeoutSecs, $timeoutUSecs);
  260. if ($selected === 2) {
  261. $this->onConnectionError('Connection refused.', SOCKET_ECONNREFUSED);
  262. }
  263. if ($selected === 0) {
  264. $this->onConnectionError('Connection timed out.', SOCKET_ETIMEDOUT);
  265. }
  266. if ($selected === false) {
  267. $this->emitSocketError();
  268. }
  269. }
  270. /**
  271. * {@inheritdoc}
  272. */
  273. public function connect()
  274. {
  275. if (parent::connect() && $this->initCommands) {
  276. foreach ($this->initCommands as $command) {
  277. $response = $this->executeCommand($command);
  278. if ($response instanceof ErrorResponseInterface) {
  279. $this->onConnectionError("`{$command->getId()}` failed: $response", 0);
  280. }
  281. }
  282. }
  283. }
  284. /**
  285. * {@inheritdoc}
  286. */
  287. public function disconnect()
  288. {
  289. if ($this->isConnected()) {
  290. socket_close($this->getResource());
  291. parent::disconnect();
  292. }
  293. }
  294. /**
  295. * {@inheritdoc}
  296. */
  297. protected function write($buffer)
  298. {
  299. $socket = $this->getResource();
  300. while (($length = strlen($buffer)) > 0) {
  301. $written = socket_write($socket, $buffer, $length);
  302. if ($length === $written) {
  303. return;
  304. }
  305. if ($written === false) {
  306. $this->onConnectionError('Error while writing bytes to the server.');
  307. }
  308. $buffer = substr($buffer, $written);
  309. }
  310. }
  311. /**
  312. * {@inheritdoc}
  313. */
  314. public function read()
  315. {
  316. $socket = $this->getResource();
  317. $reader = $this->reader;
  318. while (PHPIREDIS_READER_STATE_INCOMPLETE === $state = phpiredis_reader_get_state($reader)) {
  319. if (@socket_recv($socket, $buffer, 4096, 0) === false || $buffer === '' || $buffer === null) {
  320. $this->emitSocketError();
  321. }
  322. phpiredis_reader_feed($reader, $buffer);
  323. }
  324. if ($state === PHPIREDIS_READER_STATE_COMPLETE) {
  325. return phpiredis_reader_get_reply($reader);
  326. } else {
  327. $this->onProtocolError(phpiredis_reader_get_error($reader));
  328. return;
  329. }
  330. }
  331. /**
  332. * {@inheritdoc}
  333. */
  334. public function writeRequest(CommandInterface $command)
  335. {
  336. $arguments = $command->getArguments();
  337. array_unshift($arguments, $command->getId());
  338. $this->write(phpiredis_format_command($arguments));
  339. }
  340. /**
  341. * {@inheritdoc}
  342. */
  343. public function __wakeup()
  344. {
  345. $this->assertExtensions();
  346. $this->reader = $this->createReader();
  347. }
  348. }