StreamConnection.php 7.9 KB

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