PhpiredisConnection.php 10 KB

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