PhpiredisSocketConnection.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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\Command\CommandInterface;
  13. use Predis\Response;
  14. /**
  15. * This class provides the implementation of a Predis connection that uses the
  16. * PHP socket extension for network communication and wraps the phpiredis C
  17. * extension (PHP bindings for hiredis) to parse the Redis protocol.
  18. *
  19. * This class is intended to provide an optional low-overhead alternative for
  20. * processing responses from Redis compared to the standard pure-PHP classes.
  21. * Differences in speed when dealing with short inline responses are practically
  22. * nonexistent, the actual speed boost is for big multibulk responses when this
  23. * protocol processor can parse and return responses very fast.
  24. *
  25. * For instructions on how to build and install the phpiredis extension, please
  26. * consult the repository of the project.
  27. *
  28. * The connection parameters supported by this class are:
  29. *
  30. * - scheme: it can be either 'tcp' or 'unix'.
  31. * - host: hostname or IP address of the server.
  32. * - port: TCP port of the server.
  33. * - path: path of a UNIX domain socket when scheme is 'unix'.
  34. * - timeout: timeout to perform the connection.
  35. * - read_write_timeout: timeout of read / write operations.
  36. *
  37. * @link http://github.com/nrk/phpiredis
  38. * @author Daniele Alessandri <suppakilla@gmail.com>
  39. */
  40. class PhpiredisSocketConnection extends AbstractConnection
  41. {
  42. private $reader;
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function __construct(ConnectionParametersInterface $parameters)
  47. {
  48. $this->assertExtensions();
  49. parent::__construct($parameters);
  50. $this->reader = $this->createReader();
  51. }
  52. /**
  53. * Disconnects from the server and destroys the underlying resource and the
  54. * protocol reader resource when PHP's garbage collector kicks in.
  55. */
  56. public function __destruct()
  57. {
  58. phpiredis_reader_destroy($this->reader);
  59. parent::__destruct();
  60. }
  61. /**
  62. * Checks if the socket and phpiredis extensions are loaded in PHP.
  63. */
  64. protected function assertExtensions()
  65. {
  66. if (!extension_loaded('sockets')) {
  67. throw new NotSupportedException(
  68. 'The "sockets" extension is required by this connection backend'
  69. );
  70. }
  71. if (!extension_loaded('phpiredis')) {
  72. throw new NotSupportedException(
  73. 'The "phpiredis" extension is required by this connection backend'
  74. );
  75. }
  76. }
  77. /**
  78. * {@inheritdoc}
  79. */
  80. protected function assertParameters(ConnectionParametersInterface $parameters)
  81. {
  82. if (isset($parameters->persistent)) {
  83. throw new NotSupportedException(
  84. "Persistent connections are not supported by this connection backend"
  85. );
  86. }
  87. return parent::assertParameters($parameters);
  88. }
  89. /**
  90. * Creates a new instance of the protocol reader resource.
  91. *
  92. * @return resource
  93. */
  94. private function createReader()
  95. {
  96. $reader = phpiredis_reader_create();
  97. phpiredis_reader_set_status_handler($reader, $this->getStatusHandler());
  98. phpiredis_reader_set_error_handler($reader, $this->getErrorHandler());
  99. return $reader;
  100. }
  101. /**
  102. * Returns the underlying protocol reader resource.
  103. *
  104. * @return resource
  105. */
  106. protected function getReader()
  107. {
  108. return $this->reader;
  109. }
  110. /**
  111. * Returns the handler used by the protocol reader for inline responses.
  112. *
  113. * @return \Closure
  114. */
  115. private function getStatusHandler()
  116. {
  117. return function ($payload) {
  118. return Response\Status::get($payload);
  119. };
  120. }
  121. /**
  122. * Returns the handler used by the protocol reader for error responses.
  123. *
  124. * @return \Closure
  125. */
  126. protected function getErrorHandler()
  127. {
  128. return function ($payload) {
  129. return new Response\Error($payload);
  130. };
  131. }
  132. /**
  133. * Helper method used to throw exceptions on socket errors.
  134. */
  135. private function emitSocketError()
  136. {
  137. $errno = socket_last_error();
  138. $errstr = socket_strerror($errno);
  139. $this->disconnect();
  140. $this->onConnectionError(trim($errstr), $errno);
  141. }
  142. /**
  143. * {@inheritdoc}
  144. */
  145. protected function createResource()
  146. {
  147. $isUnix = $this->parameters->scheme === 'unix';
  148. $domain = $isUnix ? AF_UNIX : AF_INET;
  149. $protocol = $isUnix ? 0 : SOL_TCP;
  150. $socket = @call_user_func('socket_create', $domain, SOCK_STREAM, $protocol);
  151. if (!is_resource($socket)) {
  152. $this->emitSocketError();
  153. }
  154. $this->setSocketOptions($socket, $this->parameters);
  155. return $socket;
  156. }
  157. /**
  158. * Sets options on the socket resource from the connection parameters.
  159. *
  160. * @param resource $socket Socket resource.
  161. * @param ConnectionParametersInterface $parameters Parameters used to initialize the connection.
  162. */
  163. private function setSocketOptions($socket, ConnectionParametersInterface $parameters)
  164. {
  165. if ($parameters->scheme !== 'tcp') {
  166. return;
  167. }
  168. if (!socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1)) {
  169. $this->emitSocketError();
  170. }
  171. if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
  172. $this->emitSocketError();
  173. }
  174. if (isset($parameters->read_write_timeout)) {
  175. $rwtimeout = $parameters->read_write_timeout;
  176. $timeoutSec = floor($rwtimeout);
  177. $timeoutUsec = ($rwtimeout - $timeoutSec) * 1000000;
  178. $timeout = array(
  179. 'sec' => $timeoutSec,
  180. 'usec' => $timeoutUsec,
  181. );
  182. if (!socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $timeout)) {
  183. $this->emitSocketError();
  184. }
  185. if (!socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout)) {
  186. $this->emitSocketError();
  187. }
  188. }
  189. }
  190. /**
  191. * Gets the address from the connection parameters.
  192. *
  193. * @param ConnectionParametersInterface $parameters Parameters used to initialize the connection.
  194. * @return string
  195. */
  196. private static function getAddress(ConnectionParametersInterface $parameters)
  197. {
  198. if ($parameters->scheme === 'unix') {
  199. return $parameters->path;
  200. }
  201. $host = $parameters->host;
  202. if (ip2long($host) === false) {
  203. if (($addresses = gethostbynamel($host)) === false) {
  204. $this->onConnectionError("Cannot resolve the address of $host");
  205. }
  206. return $addresses[array_rand($addresses)];
  207. }
  208. return $host;
  209. }
  210. /**
  211. * Opens the actual connection to the server with a timeout.
  212. *
  213. * @param ConnectionParametersInterface $parameters Parameters used to initialize the connection.
  214. * @return string
  215. */
  216. private function connectWithTimeout(ConnectionParametersInterface $parameters)
  217. {
  218. $host = self::getAddress($parameters);
  219. $socket = $this->getResource();
  220. socket_set_nonblock($socket);
  221. if (@socket_connect($socket, $host, $parameters->port) === false) {
  222. $error = socket_last_error();
  223. if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) {
  224. $this->emitSocketError();
  225. }
  226. }
  227. socket_set_block($socket);
  228. $null = null;
  229. $selectable = array($socket);
  230. $timeout = $parameters->timeout;
  231. $timeoutSecs = floor($timeout);
  232. $timeoutUSecs = ($timeout - $timeoutSecs) * 1000000;
  233. $selected = socket_select($selectable, $selectable, $null, $timeoutSecs, $timeoutUSecs);
  234. if ($selected === 2) {
  235. $this->onConnectionError('Connection refused', SOCKET_ECONNREFUSED);
  236. }
  237. if ($selected === 0) {
  238. $this->onConnectionError('Connection timed out', SOCKET_ETIMEDOUT);
  239. }
  240. if ($selected === false) {
  241. $this->emitSocketError();
  242. }
  243. }
  244. /**
  245. * {@inheritdoc}
  246. */
  247. public function connect()
  248. {
  249. parent::connect();
  250. $this->connectWithTimeout($this->parameters);
  251. if ($this->initCmds) {
  252. foreach ($this->initCmds as $command) {
  253. $this->executeCommand($command);
  254. }
  255. }
  256. }
  257. /**
  258. * {@inheritdoc}
  259. */
  260. public function disconnect()
  261. {
  262. if ($this->isConnected()) {
  263. socket_close($this->getResource());
  264. parent::disconnect();
  265. }
  266. }
  267. /**
  268. * {@inheritdoc}
  269. */
  270. protected function write($buffer)
  271. {
  272. $socket = $this->getResource();
  273. while (($length = strlen($buffer)) > 0) {
  274. $written = socket_write($socket, $buffer, $length);
  275. if ($length === $written) {
  276. return;
  277. }
  278. if ($written === false) {
  279. $this->onConnectionError('Error while writing bytes to the server');
  280. }
  281. $buffer = substr($buffer, $written);
  282. }
  283. }
  284. /**
  285. * {@inheritdoc}
  286. */
  287. public function read()
  288. {
  289. $socket = $this->getResource();
  290. $reader = $this->reader;
  291. while (PHPIREDIS_READER_STATE_INCOMPLETE === $state = phpiredis_reader_get_state($reader)) {
  292. if (@socket_recv($socket, $buffer, 4096, 0) === false || $buffer === '') {
  293. $this->emitSocketError();
  294. }
  295. phpiredis_reader_feed($reader, $buffer);
  296. }
  297. if ($state === PHPIREDIS_READER_STATE_COMPLETE) {
  298. return phpiredis_reader_get_reply($reader);
  299. } else {
  300. $this->onProtocolError(phpiredis_reader_get_error($reader));
  301. }
  302. }
  303. /**
  304. * {@inheritdoc}
  305. */
  306. public function writeRequest(CommandInterface $command)
  307. {
  308. $arguments = $command->getArguments();
  309. array_unshift($arguments, $command->getId());
  310. $this->write(phpiredis_format_command($arguments));
  311. }
  312. /**
  313. * {@inheritdoc}
  314. */
  315. public function __wakeup()
  316. {
  317. $this->assertExtensions();
  318. $this->reader = $this->createReader();
  319. }
  320. }