StreamConnection.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 (default is 5 seconds).
  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 assertParameters(ParametersInterface $parameters)
  48. {
  49. switch ($parameters->scheme) {
  50. case 'tcp':
  51. case 'redis':
  52. case 'unix':
  53. break;
  54. default:
  55. throw new \InvalidArgumentException("Invalid scheme: '$parameters->scheme'.");
  56. }
  57. return $parameters;
  58. }
  59. /**
  60. * {@inheritdoc}
  61. */
  62. protected function createResource()
  63. {
  64. switch ($this->parameters->scheme) {
  65. case 'tcp':
  66. case 'redis':
  67. return $this->tcpStreamInitializer($this->parameters);
  68. case 'unix':
  69. return $this->unixStreamInitializer($this->parameters);
  70. default:
  71. throw new \InvalidArgumentException("Invalid scheme: '{$this->parameters->scheme}'.");
  72. }
  73. }
  74. /**
  75. * Creates a connected stream socket resource.
  76. *
  77. * @param ParametersInterface $parameters Connection parameters.
  78. * @param string $address Address for stream_socket_client().
  79. * @param int $flags Flags for stream_socket_client().
  80. *
  81. * @return resource
  82. */
  83. protected function createStreamSocket(ParametersInterface $parameters, $address, $flags)
  84. {
  85. $timeout = (isset($parameters->timeout) ? (float) $parameters->timeout : 5.0);
  86. if (!$resource = @stream_socket_client($address, $errno, $errstr, $timeout, $flags)) {
  87. $this->onConnectionError(trim($errstr), $errno);
  88. }
  89. if (isset($parameters->read_write_timeout)) {
  90. $rwtimeout = (float) $parameters->read_write_timeout;
  91. $rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
  92. $timeoutSeconds = floor($rwtimeout);
  93. $timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000;
  94. stream_set_timeout($resource, $timeoutSeconds, $timeoutUSeconds);
  95. }
  96. if (isset($parameters->tcp_nodelay) && function_exists('socket_import_stream')) {
  97. $socket = socket_import_stream($resource);
  98. socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) $parameters->tcp_nodelay);
  99. }
  100. return $resource;
  101. }
  102. /**
  103. * Initializes a TCP stream resource.
  104. *
  105. * @param ParametersInterface $parameters Initialization parameters for the connection.
  106. *
  107. * @return resource
  108. */
  109. protected function tcpStreamInitializer(ParametersInterface $parameters)
  110. {
  111. $address = "tcp://{$parameters->host}:{$parameters->port}";
  112. $flags = STREAM_CLIENT_CONNECT;
  113. if (isset($parameters->async_connect) && $parameters->async_connect) {
  114. $flags |= STREAM_CLIENT_ASYNC_CONNECT;
  115. }
  116. if (isset($parameters->persistent)) {
  117. if (false !== $persistent = filter_var($parameters->persistent, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) {
  118. $flags |= STREAM_CLIENT_PERSISTENT;
  119. if ($persistent === null) {
  120. $address = "{$address}/{$parameters->persistent}";
  121. }
  122. }
  123. }
  124. $resource = $this->createStreamSocket($parameters, $address, $flags);
  125. return $resource;
  126. }
  127. /**
  128. * Initializes a UNIX stream resource.
  129. *
  130. * @param ParametersInterface $parameters Initialization parameters for the connection.
  131. *
  132. * @return resource
  133. */
  134. protected function unixStreamInitializer(ParametersInterface $parameters)
  135. {
  136. if (!isset($parameters->path)) {
  137. throw new \InvalidArgumentException('Missing UNIX domain socket path.');
  138. }
  139. $flags = STREAM_CLIENT_CONNECT;
  140. if (isset($parameters->persistent)) {
  141. if (false !== $persistent = filter_var($parameters->persistent, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) {
  142. $flags |= STREAM_CLIENT_PERSISTENT;
  143. if ($persistent === null) {
  144. throw new \InvalidArgumentException(
  145. 'Persistent connection IDs are not supported when using UNIX domain sockets.'
  146. );
  147. }
  148. }
  149. }
  150. $resource = $this->createStreamSocket($parameters, "unix://{$parameters->path}", $flags);
  151. return $resource;
  152. }
  153. /**
  154. * {@inheritdoc}
  155. */
  156. public function connect()
  157. {
  158. if (parent::connect() && $this->initCommands) {
  159. foreach ($this->initCommands as $command) {
  160. $this->executeCommand($command);
  161. }
  162. }
  163. }
  164. /**
  165. * {@inheritdoc}
  166. */
  167. public function disconnect()
  168. {
  169. if ($this->isConnected()) {
  170. fclose($this->getResource());
  171. parent::disconnect();
  172. }
  173. }
  174. /**
  175. * Performs a write operation over the stream of the buffer containing a
  176. * command serialized with the Redis wire protocol.
  177. *
  178. * @param string $buffer Representation of a command in the Redis wire protocol.
  179. */
  180. protected function write($buffer)
  181. {
  182. $socket = $this->getResource();
  183. while (($length = strlen($buffer)) > 0) {
  184. $written = @fwrite($socket, $buffer);
  185. if ($length === $written) {
  186. return;
  187. }
  188. if ($written === false || $written === 0) {
  189. $this->onConnectionError('Error while writing bytes to the server.');
  190. }
  191. $buffer = substr($buffer, $written);
  192. }
  193. }
  194. /**
  195. * {@inheritdoc}
  196. */
  197. public function read()
  198. {
  199. $socket = $this->getResource();
  200. $chunk = fgets($socket);
  201. if ($chunk === false || $chunk === '') {
  202. $this->onConnectionError('Error while reading line from the server.');
  203. }
  204. $prefix = $chunk[0];
  205. $payload = substr($chunk, 1, -2);
  206. switch ($prefix) {
  207. case '+':
  208. return StatusResponse::get($payload);
  209. case '$':
  210. $size = (int) $payload;
  211. if ($size === -1) {
  212. return;
  213. }
  214. $bulkData = '';
  215. $bytesLeft = ($size += 2);
  216. do {
  217. $chunk = fread($socket, min($bytesLeft, 4096));
  218. if ($chunk === false || $chunk === '') {
  219. $this->onConnectionError('Error while reading bytes from the server.');
  220. }
  221. $bulkData .= $chunk;
  222. $bytesLeft = $size - strlen($bulkData);
  223. } while ($bytesLeft > 0);
  224. return substr($bulkData, 0, -2);
  225. case '*':
  226. $count = (int) $payload;
  227. if ($count === -1) {
  228. return;
  229. }
  230. $multibulk = array();
  231. for ($i = 0; $i < $count; ++$i) {
  232. $multibulk[$i] = $this->read();
  233. }
  234. return $multibulk;
  235. case ':':
  236. return (int) $payload;
  237. case '-':
  238. return new ErrorResponse($payload);
  239. default:
  240. $this->onProtocolError("Unknown response prefix: '$prefix'.");
  241. return;
  242. }
  243. }
  244. /**
  245. * {@inheritdoc}
  246. */
  247. public function writeRequest(CommandInterface $command)
  248. {
  249. $commandID = $command->getId();
  250. $arguments = $command->getArguments();
  251. $cmdlen = strlen($commandID);
  252. $reqlen = count($arguments) + 1;
  253. $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$commandID}\r\n";
  254. for ($i = 0, $reqlen--; $i < $reqlen; ++$i) {
  255. $argument = $arguments[$i];
  256. $arglen = strlen($argument);
  257. $buffer .= "\${$arglen}\r\n{$argument}\r\n";
  258. }
  259. $this->write($buffer);
  260. }
  261. }