StreamConnection.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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\Response\Error as ErrorResponse;
  13. use Predis\Response\Status as StatusResponse;
  14. /**
  15. * Standard connection to Redis servers implemented on top of PHP's streams.
  16. * The connection parameters supported by this class are:.
  17. *
  18. * - scheme: it can be either 'redis', 'tcp' or 'unix'.
  19. * - host: hostname or IP address of the server.
  20. * - port: TCP port of the server.
  21. * - path: path of a UNIX domain socket when scheme is 'unix'.
  22. * - timeout: timeout to perform the connection.
  23. * - read_write_timeout: timeout of read / write operations.
  24. * - async_connect: performs the connection asynchronously.
  25. * - tcp_nodelay: enables or disables Nagle's algorithm for coalescing.
  26. * - persistent: the connection is left intact after a GC collection.
  27. *
  28. * @author Daniele Alessandri <suppakilla@gmail.com>
  29. */
  30. class StreamConnection extends AbstractConnection
  31. {
  32. /**
  33. * Disconnects from the server and destroys the underlying resource when the
  34. * garbage collector kicks in only if the connection has not been marked as
  35. * persistent.
  36. */
  37. public function __destruct()
  38. {
  39. if (isset($this->parameters->persistent) && $this->parameters->persistent) {
  40. return;
  41. }
  42. $this->disconnect();
  43. }
  44. /**
  45. * {@inheritdoc}
  46. */
  47. protected function createResource()
  48. {
  49. switch ($this->parameters->scheme) {
  50. case 'tcp':
  51. case 'redis':
  52. return $this->tcpStreamInitializer($this->parameters);
  53. case 'unix':
  54. return $this->unixStreamInitializer($this->parameters);
  55. default:
  56. throw new \InvalidArgumentException("Invalid scheme: '{$this->parameters->scheme}'.");
  57. }
  58. }
  59. /**
  60. * Initializes a TCP stream resource.
  61. *
  62. * @param ParametersInterface $parameters Initialization parameters for the connection.
  63. *
  64. * @return resource
  65. */
  66. protected function tcpStreamInitializer(ParametersInterface $parameters)
  67. {
  68. if (!filter_var($parameters->host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
  69. $uri = "tcp://$parameters->host:$parameters->port";
  70. } else {
  71. $uri = "tcp://[$parameters->host]:$parameters->port";
  72. }
  73. $flags = STREAM_CLIENT_CONNECT;
  74. if (isset($parameters->async_connect) && (bool) $parameters->async_connect) {
  75. $flags |= STREAM_CLIENT_ASYNC_CONNECT;
  76. }
  77. if (isset($parameters->persistent) && (bool) $parameters->persistent) {
  78. $flags |= STREAM_CLIENT_PERSISTENT;
  79. $uri .= strpos($path = $parameters->path, '/') === 0 ? $path : "/$path";
  80. }
  81. $resource = @stream_socket_client($uri, $errno, $errstr, (float) $parameters->timeout, $flags);
  82. if (!$resource) {
  83. $this->onConnectionError(trim($errstr), $errno);
  84. }
  85. if (isset($parameters->read_write_timeout)) {
  86. $rwtimeout = (float) $parameters->read_write_timeout;
  87. $rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
  88. $timeoutSeconds = floor($rwtimeout);
  89. $timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000;
  90. stream_set_timeout($resource, $timeoutSeconds, $timeoutUSeconds);
  91. }
  92. if (isset($parameters->tcp_nodelay) && function_exists('socket_import_stream')) {
  93. $socket = socket_import_stream($resource);
  94. socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) $parameters->tcp_nodelay);
  95. }
  96. return $resource;
  97. }
  98. /**
  99. * Initializes a UNIX stream resource.
  100. *
  101. * @param ParametersInterface $parameters Initialization parameters for the connection.
  102. *
  103. * @return resource
  104. */
  105. protected function unixStreamInitializer(ParametersInterface $parameters)
  106. {
  107. if (!isset($parameters->path)) {
  108. throw new InvalidArgumentException('Missing UNIX domain socket path.');
  109. }
  110. $uri = "unix://{$parameters->path}";
  111. $flags = STREAM_CLIENT_CONNECT;
  112. if ((bool) $parameters->persistent) {
  113. $flags |= STREAM_CLIENT_PERSISTENT;
  114. }
  115. $resource = @stream_socket_client($uri, $errno, $errstr, (float) $parameters->timeout, $flags);
  116. if (!$resource) {
  117. $this->onConnectionError(trim($errstr), $errno);
  118. }
  119. if (isset($parameters->read_write_timeout)) {
  120. $rwtimeout = (float) $parameters->read_write_timeout;
  121. $rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
  122. $timeoutSeconds = floor($rwtimeout);
  123. $timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000;
  124. stream_set_timeout($resource, $timeoutSeconds, $timeoutUSeconds);
  125. }
  126. return $resource;
  127. }
  128. /**
  129. * {@inheritdoc}
  130. */
  131. public function connect()
  132. {
  133. if (parent::connect() && $this->initCommands) {
  134. foreach ($this->initCommands as $command) {
  135. $this->executeCommand($command);
  136. }
  137. }
  138. }
  139. /**
  140. * {@inheritdoc}
  141. */
  142. public function disconnect()
  143. {
  144. if ($this->isConnected()) {
  145. fclose($this->getResource());
  146. parent::disconnect();
  147. }
  148. }
  149. /**
  150. * Performs a write operation over the stream of the buffer containing a
  151. * command serialized with the Redis wire protocol.
  152. *
  153. * @param string $buffer Representation of a command in the Redis wire protocol.
  154. */
  155. protected function write($buffer)
  156. {
  157. $socket = $this->getResource();
  158. while (($length = strlen($buffer)) > 0) {
  159. $written = @fwrite($socket, $buffer);
  160. if ($length === $written) {
  161. return;
  162. }
  163. if ($written === false || $written === 0) {
  164. $this->onConnectionError('Error while writing bytes to the server.');
  165. }
  166. $buffer = substr($buffer, $written);
  167. }
  168. }
  169. /**
  170. * {@inheritdoc}
  171. */
  172. public function read()
  173. {
  174. $socket = $this->getResource();
  175. $chunk = fgets($socket);
  176. if ($chunk === false || $chunk === '') {
  177. $this->onConnectionError('Error while reading line from the server.');
  178. }
  179. $prefix = $chunk[0];
  180. $payload = substr($chunk, 1, -2);
  181. switch ($prefix) {
  182. case '+':
  183. return StatusResponse::get($payload);
  184. case '$':
  185. $size = (int) $payload;
  186. if ($size === -1) {
  187. return;
  188. }
  189. $bulkData = '';
  190. $bytesLeft = ($size += 2);
  191. do {
  192. $chunk = fread($socket, min($bytesLeft, 4096));
  193. if ($chunk === false || $chunk === '') {
  194. $this->onConnectionError('Error while reading bytes from the server.');
  195. }
  196. $bulkData .= $chunk;
  197. $bytesLeft = $size - strlen($bulkData);
  198. } while ($bytesLeft > 0);
  199. return substr($bulkData, 0, -2);
  200. case '*':
  201. $count = (int) $payload;
  202. if ($count === -1) {
  203. return;
  204. }
  205. $multibulk = array();
  206. for ($i = 0; $i < $count; ++$i) {
  207. $multibulk[$i] = $this->read();
  208. }
  209. return $multibulk;
  210. case ':':
  211. return (int) $payload;
  212. case '-':
  213. return new ErrorResponse($payload);
  214. default:
  215. $this->onProtocolError("Unknown response prefix: '$prefix'.");
  216. return;
  217. }
  218. }
  219. /**
  220. * {@inheritdoc}
  221. */
  222. public function writeRequest(CommandInterface $command)
  223. {
  224. $commandID = $command->getId();
  225. $arguments = $command->getArguments();
  226. $cmdlen = strlen($commandID);
  227. $reqlen = count($arguments) + 1;
  228. $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$commandID}\r\n";
  229. for ($i = 0, $reqlen--; $i < $reqlen; ++$i) {
  230. $argument = $arguments[$i];
  231. $arglen = strlen($argument);
  232. $buffer .= "\${$arglen}\r\n{$argument}\r\n";
  233. }
  234. $this->write($buffer);
  235. }
  236. }