StreamConnection.php 8.5 KB

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