StreamConnection.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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\ResponseError;
  12. use Predis\ResponseQueued;
  13. use Predis\Command\CommandInterface;
  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. * - 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
  33. * PHP's garbage collector kicks in only if the connection has not been
  34. * marked as persistent.
  35. */
  36. public function __destruct()
  37. {
  38. if (isset($this->parameters) && !$this->parameters->persistent) {
  39. $this->disconnect();
  40. }
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. protected function createResource()
  46. {
  47. $parameters = $this->parameters;
  48. $initializer = "{$parameters->scheme}StreamInitializer";
  49. return $this->$initializer($parameters);
  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. $this->sendInitializationCommands();
  111. }
  112. }
  113. /**
  114. * {@inheritdoc}
  115. */
  116. public function disconnect()
  117. {
  118. if ($this->isConnected()) {
  119. fclose($this->getResource());
  120. parent::disconnect();
  121. }
  122. }
  123. /**
  124. * Sends the initialization commands to Redis when the connection is opened.
  125. */
  126. private function sendInitializationCommands()
  127. {
  128. foreach ($this->initCmds as $command) {
  129. $this->writeCommand($command);
  130. }
  131. foreach ($this->initCmds as $command) {
  132. $this->readResponse($command);
  133. }
  134. }
  135. /**
  136. * Performs a write operation on the stream of the buffer containing a
  137. * command serialized with the Redis wire protocol.
  138. *
  139. * @param string $buffer Redis wire protocol representation of a command.
  140. */
  141. protected function writeBytes($buffer)
  142. {
  143. $socket = $this->getResource();
  144. while (($length = strlen($buffer)) > 0) {
  145. $written = fwrite($socket, $buffer);
  146. if ($length === $written) {
  147. return;
  148. }
  149. if ($written === false || $written === 0) {
  150. $this->onConnectionError('Error while writing bytes to the server');
  151. }
  152. $buffer = substr($buffer, $written);
  153. }
  154. }
  155. /**
  156. * {@inheritdoc}
  157. */
  158. public function read()
  159. {
  160. $socket = $this->getResource();
  161. $chunk = fgets($socket);
  162. if ($chunk === false || $chunk === '') {
  163. $this->onConnectionError('Error while reading line from the server');
  164. }
  165. $prefix = $chunk[0];
  166. $payload = substr($chunk, 1, -2);
  167. switch ($prefix) {
  168. case '+': // inline
  169. switch ($payload) {
  170. case 'OK':
  171. return true;
  172. case 'QUEUED':
  173. return new ResponseQueued();
  174. default:
  175. return $payload;
  176. }
  177. case '$': // bulk
  178. $size = (int) $payload;
  179. if ($size === -1) {
  180. return null;
  181. }
  182. $bulkData = '';
  183. $bytesLeft = ($size += 2);
  184. do {
  185. $chunk = fread($socket, min($bytesLeft, 4096));
  186. if ($chunk === false || $chunk === '') {
  187. $this->onConnectionError('Error while reading bytes from the server');
  188. }
  189. $bulkData .= $chunk;
  190. $bytesLeft = $size - strlen($bulkData);
  191. } while ($bytesLeft > 0);
  192. return substr($bulkData, 0, -2);
  193. case '*': // multi bulk
  194. $count = (int) $payload;
  195. if ($count === -1) {
  196. return null;
  197. }
  198. $multibulk = array();
  199. for ($i = 0; $i < $count; $i++) {
  200. $multibulk[$i] = $this->read();
  201. }
  202. return $multibulk;
  203. case ':': // integer
  204. return (int) $payload;
  205. case '-': // error
  206. return new ResponseError($payload);
  207. default:
  208. $this->onProtocolError("Unknown prefix: '$prefix'");
  209. }
  210. }
  211. /**
  212. * {@inheritdoc}
  213. */
  214. public function writeCommand(CommandInterface $command)
  215. {
  216. $commandId = $command->getId();
  217. $arguments = $command->getArguments();
  218. $cmdlen = strlen($commandId);
  219. $reqlen = count($arguments) + 1;
  220. $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$commandId}\r\n";
  221. for ($i = 0; $i < $reqlen - 1; $i++) {
  222. $argument = $arguments[$i];
  223. $arglen = strlen($argument);
  224. $buffer .= "\${$arglen}\r\n{$argument}\r\n";
  225. }
  226. $this->writeBytes($buffer);
  227. }
  228. }