StreamConnection.php 8.5 KB

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