StreamConnection.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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\NotSupportedException;
  12. use Predis\ResponseError;
  13. use Predis\ResponseQueued;
  14. use Predis\Command\CommandInterface;
  15. use Predis\Iterator\MultiBulkResponseSimple;
  16. /**
  17. * Standard connection to Redis servers implemented on top of PHP's streams.
  18. * The connection parameters supported by this class are:
  19. *
  20. * - scheme: it can be either 'tcp' or 'unix'.
  21. * - host: hostname or IP address of the server.
  22. * - port: TCP port of the server.
  23. * - timeout: timeout to perform the connection.
  24. * - read_write_timeout: timeout of read / write operations.
  25. * - async_connect: performs the connection asynchronously.
  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 (!$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 === true) {
  73. $flags |= STREAM_CLIENT_ASYNC_CONNECT;
  74. }
  75. if (isset($parameters->persistent) && $parameters->persistent === true) {
  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. return $resource;
  90. }
  91. /**
  92. * Initializes a UNIX stream resource.
  93. *
  94. * @param ConnectionParametersInterface $parameters Parameters used to initialize the connection.
  95. * @return resource
  96. */
  97. private function unixStreamInitializer(ConnectionParametersInterface $parameters)
  98. {
  99. $uri = "unix://{$parameters->path}";
  100. $flags = STREAM_CLIENT_CONNECT;
  101. if ($parameters->persistent === true) {
  102. $flags |= STREAM_CLIENT_PERSISTENT;
  103. }
  104. $resource = @stream_socket_client($uri, $errno, $errstr, $parameters->timeout, $flags);
  105. if (!$resource) {
  106. $this->onConnectionError(trim($errstr), $errno);
  107. }
  108. return $resource;
  109. }
  110. /**
  111. * {@inheritdoc}
  112. */
  113. public function connect()
  114. {
  115. parent::connect();
  116. if (count($this->initCmds) > 0){
  117. $this->sendInitializationCommands();
  118. }
  119. }
  120. /**
  121. * {@inheritdoc}
  122. */
  123. public function disconnect()
  124. {
  125. if ($this->isConnected()) {
  126. fclose($this->getResource());
  127. parent::disconnect();
  128. }
  129. }
  130. /**
  131. * Sends the initialization commands to Redis when the connection is opened.
  132. */
  133. private function sendInitializationCommands()
  134. {
  135. foreach ($this->initCmds as $command) {
  136. $this->writeCommand($command);
  137. }
  138. foreach ($this->initCmds as $command) {
  139. $this->readResponse($command);
  140. }
  141. }
  142. /**
  143. * Performs a write operation on the stream of the buffer containing a
  144. * command serialized with the Redis wire protocol.
  145. *
  146. * @param string $buffer Redis wire protocol representation of a command.
  147. */
  148. protected function writeBytes($buffer)
  149. {
  150. $socket = $this->getResource();
  151. while (($length = strlen($buffer)) > 0) {
  152. $written = fwrite($socket, $buffer);
  153. if ($length === $written) {
  154. return;
  155. }
  156. if ($written === false || $written === 0) {
  157. $this->onConnectionError('Error while writing bytes to the server');
  158. }
  159. $buffer = substr($buffer, $written);
  160. }
  161. }
  162. /**
  163. * {@inheritdoc}
  164. */
  165. public function read() {
  166. $socket = $this->getResource();
  167. $chunk = fgets($socket);
  168. if ($chunk === false || $chunk === '') {
  169. $this->onConnectionError('Error while reading line from the server');
  170. }
  171. $prefix = $chunk[0];
  172. $payload = substr($chunk, 1, -2);
  173. switch ($prefix) {
  174. case '+': // inline
  175. switch ($payload) {
  176. case 'OK':
  177. return true;
  178. case 'QUEUED':
  179. return new ResponseQueued();
  180. default:
  181. return $payload;
  182. }
  183. case '$': // bulk
  184. $size = (int) $payload;
  185. if ($size === -1) {
  186. return null;
  187. }
  188. $bulkData = '';
  189. $bytesLeft = ($size += 2);
  190. do {
  191. $chunk = fread($socket, min($bytesLeft, 4096));
  192. if ($chunk === false || $chunk === '') {
  193. $this->onConnectionError('Error while reading bytes from the server');
  194. }
  195. $bulkData .= $chunk;
  196. $bytesLeft = $size - strlen($bulkData);
  197. } while ($bytesLeft > 0);
  198. return substr($bulkData, 0, -2);
  199. case '*': // multi bulk
  200. $count = (int) $payload;
  201. if ($count === -1) {
  202. return null;
  203. }
  204. if ($this->mbiterable === true) {
  205. return new MultiBulkResponseSimple($this, $count);
  206. }
  207. $multibulk = array();
  208. for ($i = 0; $i < $count; $i++) {
  209. $multibulk[$i] = $this->read();
  210. }
  211. return $multibulk;
  212. case ':': // integer
  213. return (int) $payload;
  214. case '-': // error
  215. return new ResponseError($payload);
  216. default:
  217. $this->onProtocolError("Unknown prefix: '$prefix'");
  218. }
  219. }
  220. /**
  221. * {@inheritdoc}
  222. */
  223. public function writeCommand(CommandInterface $command)
  224. {
  225. $commandId = $command->getId();
  226. $arguments = $command->getArguments();
  227. $cmdlen = strlen($commandId);
  228. $reqlen = count($arguments) + 1;
  229. $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$commandId}\r\n";
  230. for ($i = 0; $i < $reqlen - 1; $i++) {
  231. $argument = $arguments[$i];
  232. $arglen = strlen($argument);
  233. $buffer .= "\${$arglen}\r\n{$argument}\r\n";
  234. }
  235. $this->writeBytes($buffer);
  236. }
  237. /**
  238. * {@inheritdoc}
  239. */
  240. public function __sleep()
  241. {
  242. return array_merge(parent::__sleep(), array('mbiterable'));
  243. }
  244. }