PhpiredisSocketConnection.php 11 KB

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