StreamConnection.php 7.3 KB

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