StreamConnection.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. {
  164. $socket = $this->getResource();
  165. $chunk = fgets($socket);
  166. if ($chunk === false || $chunk === '') {
  167. $this->onConnectionError('Error while reading line from the server');
  168. }
  169. $prefix = $chunk[0];
  170. $payload = substr($chunk, 1, -2);
  171. switch ($prefix) {
  172. case '+': // inline
  173. switch ($payload) {
  174. case 'OK':
  175. return true;
  176. case 'QUEUED':
  177. return new ResponseQueued();
  178. default:
  179. return $payload;
  180. }
  181. case '$': // bulk
  182. $size = (int) $payload;
  183. if ($size === -1) {
  184. return null;
  185. }
  186. $bulkData = '';
  187. $bytesLeft = ($size += 2);
  188. do {
  189. $chunk = fread($socket, min($bytesLeft, 4096));
  190. if ($chunk === false || $chunk === '') {
  191. $this->onConnectionError(
  192. 'Error while reading bytes from the server'
  193. );
  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. if ($this->throwErrors) {
  216. throw new ServerException($payload);
  217. }
  218. return new ResponseError($payload);
  219. default:
  220. $this->onProtocolError("Unknown prefix: '$prefix'");
  221. }
  222. }
  223. /**
  224. * {@inheritdoc}
  225. */
  226. public function writeCommand(ICommand $command)
  227. {
  228. $commandId = $command->getId();
  229. $arguments = $command->getArguments();
  230. $cmdlen = strlen($commandId);
  231. $reqlen = count($arguments) + 1;
  232. $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$commandId}\r\n";
  233. for ($i = 0; $i < $reqlen - 1; $i++) {
  234. $argument = $arguments[$i];
  235. $arglen = strlen($argument);
  236. $buffer .= "\${$arglen}\r\n{$argument}\r\n";
  237. }
  238. $this->writeBytes($buffer);
  239. }
  240. /**
  241. * {@inheritdoc}
  242. */
  243. public function __sleep()
  244. {
  245. return array_merge(parent::__sleep(), array('mbiterable', 'throwErrors'));
  246. }
  247. }