StreamConnection.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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 '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. $initializer = "{$this->parameters->scheme}StreamInitializer";
  50. $resource = $this->$initializer($this->parameters);
  51. return $resource;
  52. }
  53. /**
  54. * Initializes a TCP stream resource.
  55. *
  56. * @param ParametersInterface $parameters Initialization parameters for the connection.
  57. *
  58. * @return resource
  59. */
  60. protected function tcpStreamInitializer(ParametersInterface $parameters)
  61. {
  62. $uri = "tcp://{$parameters->host}:{$parameters->port}";
  63. $flags = STREAM_CLIENT_CONNECT;
  64. if (isset($parameters->async_connect) && (bool) $parameters->async_connect) {
  65. $flags |= STREAM_CLIENT_ASYNC_CONNECT;
  66. }
  67. if (isset($parameters->persistent) && (bool) $parameters->persistent) {
  68. $flags |= STREAM_CLIENT_PERSISTENT;
  69. $uri .= strpos($path = $parameters->path, '/') === 0 ? $path : "/$path";
  70. }
  71. $resource = @stream_socket_client($uri, $errno, $errstr, (float) $parameters->timeout, $flags);
  72. if (!$resource) {
  73. $this->onConnectionError(trim($errstr), $errno);
  74. }
  75. if (isset($parameters->read_write_timeout)) {
  76. $rwtimeout = (float) $parameters->read_write_timeout;
  77. $rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
  78. $timeoutSeconds = floor($rwtimeout);
  79. $timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000;
  80. stream_set_timeout($resource, $timeoutSeconds, $timeoutUSeconds);
  81. }
  82. if (isset($parameters->tcp_nodelay) && function_exists('socket_import_stream')) {
  83. $socket = socket_import_stream($resource);
  84. socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) $parameters->tcp_nodelay);
  85. }
  86. return $resource;
  87. }
  88. /**
  89. * Initializes a UNIX stream resource.
  90. *
  91. * @param ParametersInterface $parameters Initialization parameters for the connection.
  92. *
  93. * @return resource
  94. */
  95. protected function unixStreamInitializer(ParametersInterface $parameters)
  96. {
  97. $uri = "unix://{$parameters->path}";
  98. $flags = STREAM_CLIENT_CONNECT;
  99. if ((bool) $parameters->persistent) {
  100. $flags |= STREAM_CLIENT_PERSISTENT;
  101. }
  102. $resource = @stream_socket_client($uri, $errno, $errstr, (float) $parameters->timeout, $flags);
  103. if (!$resource) {
  104. $this->onConnectionError(trim($errstr), $errno);
  105. }
  106. return $resource;
  107. }
  108. /**
  109. * {@inheritdoc}
  110. */
  111. public function connect()
  112. {
  113. if (parent::connect() && $this->initCommands) {
  114. foreach ($this->initCommands as $command) {
  115. $this->executeCommand($command);
  116. }
  117. }
  118. }
  119. /**
  120. * {@inheritdoc}
  121. */
  122. public function disconnect()
  123. {
  124. if ($this->isConnected()) {
  125. fclose($this->getResource());
  126. parent::disconnect();
  127. }
  128. }
  129. /**
  130. * Performs a write operation over the stream of the buffer containing a
  131. * command serialized with the Redis wire protocol.
  132. *
  133. * @param string $buffer Representation of a command in the Redis wire protocol.
  134. */
  135. protected function write($buffer)
  136. {
  137. $socket = $this->getResource();
  138. while (($length = strlen($buffer)) > 0) {
  139. $written = @fwrite($socket, $buffer);
  140. if ($length === $written) {
  141. return;
  142. }
  143. if ($written === false || $written === 0) {
  144. $this->onConnectionError('Error while writing bytes to the server.');
  145. }
  146. $buffer = substr($buffer, $written);
  147. }
  148. }
  149. /**
  150. * {@inheritdoc}
  151. */
  152. public function read()
  153. {
  154. $socket = $this->getResource();
  155. $chunk = fgets($socket);
  156. if ($chunk === false || $chunk === '') {
  157. $this->onConnectionError('Error while reading line from the server.');
  158. }
  159. $prefix = $chunk[0];
  160. $payload = substr($chunk, 1, -2);
  161. switch ($prefix) {
  162. case '+':
  163. return StatusResponse::get($payload);
  164. case '$':
  165. $size = (int) $payload;
  166. if ($size === -1) {
  167. return null;
  168. }
  169. $bulkData = '';
  170. $bytesLeft = ($size += 2);
  171. do {
  172. $chunk = fread($socket, min($bytesLeft, 4096));
  173. if ($chunk === false || $chunk === '') {
  174. $this->onConnectionError('Error while reading bytes from the server.');
  175. }
  176. $bulkData .= $chunk;
  177. $bytesLeft = $size - strlen($bulkData);
  178. } while ($bytesLeft > 0);
  179. return substr($bulkData, 0, -2);
  180. case '*':
  181. $count = (int) $payload;
  182. if ($count === -1) {
  183. return null;
  184. }
  185. $multibulk = array();
  186. for ($i = 0; $i < $count; $i++) {
  187. $multibulk[$i] = $this->read();
  188. }
  189. return $multibulk;
  190. case ':':
  191. return (int) $payload;
  192. case '-':
  193. return new ErrorResponse($payload);
  194. default:
  195. $this->onProtocolError("Unknown response prefix: '$prefix'.");
  196. return;
  197. }
  198. }
  199. /**
  200. * {@inheritdoc}
  201. */
  202. public function writeRequest(CommandInterface $command)
  203. {
  204. $commandID = $command->getId();
  205. $arguments = $command->getArguments();
  206. $cmdlen = strlen($commandID);
  207. $reqlen = count($arguments) + 1;
  208. $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$commandID}\r\n";
  209. for ($i = 0, $reqlen--; $i < $reqlen; $i++) {
  210. $argument = $arguments[$i];
  211. $arglen = strlen($argument);
  212. $buffer .= "\${$arglen}\r\n{$argument}\r\n";
  213. }
  214. $this->write($buffer);
  215. }
  216. }