StreamConnection.php 7.7 KB

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