StreamConnection.php 7.4 KB

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