StreamConnection.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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\NotSupportedException;
  14. use Predis\ConnectionParametersInterface;
  15. use Predis\Command\CommandInterface;
  16. use Predis\Iterator\MultiBulkResponseSimple;
  17. /**
  18. * Standard connection to Redis servers implemented on top of PHP's streams.
  19. * The connection parameters supported by this class are:
  20. *
  21. * - scheme: it can be either 'tcp' or 'unix'.
  22. * - host: hostname or IP address of the server.
  23. * - port: TCP port of the server.
  24. * - timeout: timeout to perform the connection.
  25. * - read_write_timeout: timeout of read / write operations.
  26. * - async_connect: performs the connection asynchronously.
  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 (!$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. private 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 === true) {
  74. $flags |= STREAM_CLIENT_ASYNC_CONNECT;
  75. }
  76. if (isset($parameters->persistent) && $parameters->persistent === true) {
  77. $flags |= STREAM_CLIENT_PERSISTENT;
  78. }
  79. $resource = @stream_socket_client(
  80. $uri, $errno, $errstr, $parameters->timeout, $flags
  81. );
  82. if (!$resource) {
  83. $this->onConnectionError(trim($errstr), $errno);
  84. }
  85. if (isset($parameters->read_write_timeout)) {
  86. $rwtimeout = $parameters->read_write_timeout;
  87. $rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
  88. $timeoutSeconds = floor($rwtimeout);
  89. $timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000;
  90. stream_set_timeout($resource, $timeoutSeconds, $timeoutUSeconds);
  91. }
  92. return $resource;
  93. }
  94. /**
  95. * Initializes a UNIX stream resource.
  96. *
  97. * @param ConnectionParametersInterface $parameters Parameters used to initialize the connection.
  98. * @return resource
  99. */
  100. private function unixStreamInitializer(ConnectionParametersInterface $parameters)
  101. {
  102. $uri = "unix://{$parameters->path}";
  103. $flags = STREAM_CLIENT_CONNECT;
  104. if ($parameters->persistent === true) {
  105. $flags |= STREAM_CLIENT_PERSISTENT;
  106. }
  107. $resource = @stream_socket_client(
  108. $uri, $errno, $errstr, $parameters->timeout, $flags
  109. );
  110. if (!$resource) {
  111. $this->onConnectionError(trim($errstr), $errno);
  112. }
  113. return $resource;
  114. }
  115. /**
  116. * {@inheritdoc}
  117. */
  118. public function connect()
  119. {
  120. parent::connect();
  121. if (count($this->initCmds) > 0){
  122. $this->sendInitializationCommands();
  123. }
  124. }
  125. /**
  126. * {@inheritdoc}
  127. */
  128. public function disconnect()
  129. {
  130. if ($this->isConnected()) {
  131. fclose($this->getResource());
  132. parent::disconnect();
  133. }
  134. }
  135. /**
  136. * Sends the initialization commands to Redis when the connection is opened.
  137. */
  138. private function sendInitializationCommands()
  139. {
  140. foreach ($this->initCmds as $command) {
  141. $this->writeCommand($command);
  142. }
  143. foreach ($this->initCmds as $command) {
  144. $this->readResponse($command);
  145. }
  146. }
  147. /**
  148. * Performs a write operation on the stream of the buffer containing a
  149. * command serialized with the Redis wire protocol.
  150. *
  151. * @param string $buffer Redis wire protocol representation of a command.
  152. */
  153. protected function writeBytes($buffer)
  154. {
  155. $socket = $this->getResource();
  156. while (($length = strlen($buffer)) > 0) {
  157. $written = fwrite($socket, $buffer);
  158. if ($length === $written) {
  159. return;
  160. }
  161. if ($written === false || $written === 0) {
  162. $this->onConnectionError('Error while writing bytes to the server');
  163. }
  164. $buffer = substr($buffer, $written);
  165. }
  166. }
  167. /**
  168. * {@inheritdoc}
  169. */
  170. public function read() {
  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(
  199. 'Error while reading bytes from the server'
  200. );
  201. }
  202. $bulkData .= $chunk;
  203. $bytesLeft = $size - strlen($bulkData);
  204. } while ($bytesLeft > 0);
  205. return substr($bulkData, 0, -2);
  206. case '*': // multi bulk
  207. $count = (int) $payload;
  208. if ($count === -1) {
  209. return null;
  210. }
  211. if ($this->mbiterable === true) {
  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 ':': // integer
  220. return (int) $payload;
  221. case '-': // error
  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; $i < $reqlen - 1; $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. }