PhpiredisConnection.php 11 KB

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