PhpiredisConnection.php 10 KB

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