PhpiredisConnection.php 10 KB

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