PhpiredisConnection.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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\ResponseError;
  13. use Predis\ResponseQueued;
  14. use Predis\Command\CommandInterface;
  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. * - path: path of a UNIX domain socket when scheme is 'unix'.
  37. * - timeout: timeout to perform the connection.
  38. * - read_write_timeout: timeout of read / write operations.
  39. *
  40. * @link http://github.com/nrk/phpiredis
  41. * @author Daniele Alessandri <suppakilla@gmail.com>
  42. */
  43. class PhpiredisConnection extends AbstractConnection
  44. {
  45. const ERR_MSG_EXTENSION = 'The %s extension must be loaded in order to be able to use this connection class';
  46. private $reader;
  47. /**
  48. * {@inheritdoc}
  49. */
  50. public function __construct(ConnectionParametersInterface $parameters)
  51. {
  52. $this->checkExtensions();
  53. $this->initializeReader();
  54. parent::__construct($parameters);
  55. }
  56. /**
  57. * Disconnects from the server and destroys the underlying resource and the
  58. * protocol reader resource when PHP's garbage collector kicks in.
  59. */
  60. public function __destruct()
  61. {
  62. phpiredis_reader_destroy($this->reader);
  63. parent::__destruct();
  64. }
  65. /**
  66. * Checks if the socket and phpiredis extensions are loaded in PHP.
  67. */
  68. private function checkExtensions()
  69. {
  70. if (!function_exists('socket_create')) {
  71. throw new NotSupportedException(sprintf(self::ERR_MSG_EXTENSION, 'socket'));
  72. }
  73. if (!function_exists('phpiredis_reader_create')) {
  74. throw new NotSupportedException(sprintf(self::ERR_MSG_EXTENSION, 'phpiredis'));
  75. }
  76. }
  77. /**
  78. * {@inheritdoc}
  79. */
  80. protected function checkParameters(ConnectionParametersInterface $parameters)
  81. {
  82. if (isset($parameters->iterable_multibulk)) {
  83. $this->onInvalidOption('iterable_multibulk', $parameters);
  84. }
  85. if (isset($parameters->persistent)) {
  86. $this->onInvalidOption('persistent', $parameters);
  87. }
  88. return parent::checkParameters($parameters);
  89. }
  90. /**
  91. * Initializes the protocol reader resource.
  92. */
  93. private function initializeReader()
  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. $this->reader = $reader;
  99. }
  100. /**
  101. * Gets the handler used by the protocol reader to handle status replies.
  102. *
  103. * @return \Closure
  104. */
  105. private function getStatusHandler()
  106. {
  107. return function ($payload) {
  108. switch ($payload) {
  109. case 'OK':
  110. return true;
  111. case 'QUEUED':
  112. return new ResponseQueued();
  113. default:
  114. return $payload;
  115. }
  116. };
  117. }
  118. /**
  119. * Gets the handler used by the protocol reader to handle Redis errors.
  120. *
  121. * @return \Closure
  122. */
  123. private function getErrorHandler()
  124. {
  125. return function ($errorMessage) {
  126. return new ResponseError($errorMessage);
  127. };
  128. }
  129. /**
  130. * Helper method used to throw exceptions on socket errors.
  131. */
  132. private function emitSocketError()
  133. {
  134. $errno = socket_last_error();
  135. $errstr = socket_strerror($errno);
  136. $this->disconnect();
  137. $this->onConnectionError(trim($errstr), $errno);
  138. }
  139. /**
  140. * {@inheritdoc}
  141. */
  142. protected function createResource()
  143. {
  144. $parameters = $this->parameters;
  145. $isUnix = $this->parameters->scheme === 'unix';
  146. $domain = $isUnix ? AF_UNIX : AF_INET;
  147. $protocol = $isUnix ? 0 : SOL_TCP;
  148. $socket = @call_user_func('socket_create', $domain, SOCK_STREAM, $protocol);
  149. if (!is_resource($socket)) {
  150. $this->emitSocketError();
  151. }
  152. $this->setSocketOptions($socket, $parameters);
  153. return $socket;
  154. }
  155. /**
  156. * Sets options on the socket resource from the connection parameters.
  157. *
  158. * @param resource $socket Socket resource.
  159. * @param ConnectionParametersInterface $parameters Parameters used to initialize the connection.
  160. */
  161. private function setSocketOptions($socket, ConnectionParametersInterface $parameters)
  162. {
  163. if ($parameters->scheme !== 'tcp') {
  164. return;
  165. }
  166. if (!socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1)) {
  167. $this->emitSocketError();
  168. }
  169. if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
  170. $this->emitSocketError();
  171. }
  172. if (isset($parameters->read_write_timeout)) {
  173. $rwtimeout = $parameters->read_write_timeout;
  174. $timeoutSec = floor($rwtimeout);
  175. $timeoutUsec = ($rwtimeout - $timeoutSec) * 1000000;
  176. $timeout = array(
  177. 'sec' => $timeoutSec,
  178. 'usec' => $timeoutUsec,
  179. );
  180. if (!socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $timeout)) {
  181. $this->emitSocketError();
  182. }
  183. if (!socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout)) {
  184. $this->emitSocketError();
  185. }
  186. }
  187. }
  188. /**
  189. * Gets the address from the connection parameters.
  190. *
  191. * @param ConnectionParametersInterface $parameters Parameters used to initialize the connection.
  192. * @return string
  193. */
  194. protected static function getAddress(ConnectionParametersInterface $parameters)
  195. {
  196. if ($parameters->scheme === 'unix') {
  197. return $parameters->path;
  198. }
  199. $host = $parameters->host;
  200. if (ip2long($host) === false) {
  201. if (false === $addresses = gethostbynamel($host)) {
  202. return false;
  203. }
  204. return $addresses[array_rand($addresses)];
  205. }
  206. return $host;
  207. }
  208. /**
  209. * Opens the actual connection to the server with a timeout.
  210. *
  211. * @param ConnectionParametersInterface $parameters Parameters used to initialize the connection.
  212. * @return string
  213. */
  214. private function connectWithTimeout(ConnectionParametersInterface $parameters)
  215. {
  216. if (false === $host = self::getAddress($parameters)) {
  217. $this->onConnectionError("Cannot resolve the address of '$parameters->host'.");
  218. }
  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. $this->sendInitializationCommands();
  253. }
  254. }
  255. /**
  256. * {@inheritdoc}
  257. */
  258. public function disconnect()
  259. {
  260. if ($this->isConnected()) {
  261. socket_close($this->getResource());
  262. parent::disconnect();
  263. }
  264. }
  265. /**
  266. * Sends the initialization commands to Redis when the connection is opened.
  267. */
  268. private function sendInitializationCommands()
  269. {
  270. foreach ($this->initCmds as $command) {
  271. $this->writeCommand($command);
  272. }
  273. foreach ($this->initCmds as $command) {
  274. $this->readResponse($command);
  275. }
  276. }
  277. /**
  278. * {@inheritdoc}
  279. */
  280. protected function write($buffer)
  281. {
  282. $socket = $this->getResource();
  283. while (($length = strlen($buffer)) > 0) {
  284. $written = socket_write($socket, $buffer, $length);
  285. if ($length === $written) {
  286. return;
  287. }
  288. if ($written === false) {
  289. $this->onConnectionError('Error while writing bytes to the server');
  290. }
  291. $buffer = substr($buffer, $written);
  292. }
  293. }
  294. /**
  295. * {@inheritdoc}
  296. */
  297. public function read()
  298. {
  299. $socket = $this->getResource();
  300. $reader = $this->reader;
  301. while (($state = phpiredis_reader_get_state($reader)) === PHPIREDIS_READER_STATE_INCOMPLETE) {
  302. if (@socket_recv($socket, $buffer, 4096, 0) === false || $buffer === '' || $buffer === null) {
  303. $this->emitSocketError();
  304. }
  305. phpiredis_reader_feed($reader, $buffer);
  306. }
  307. if ($state === PHPIREDIS_READER_STATE_COMPLETE) {
  308. return phpiredis_reader_get_reply($reader);
  309. } else {
  310. $this->onProtocolError(phpiredis_reader_get_error($reader));
  311. }
  312. }
  313. /**
  314. * {@inheritdoc}
  315. */
  316. public function writeCommand(CommandInterface $command)
  317. {
  318. $cmdargs = $command->getArguments();
  319. array_unshift($cmdargs, $command->getId());
  320. $this->write(phpiredis_format_command($cmdargs));
  321. }
  322. /**
  323. * {@inheritdoc}
  324. */
  325. public function __wakeup()
  326. {
  327. $this->checkExtensions();
  328. $this->initializeReader();
  329. }
  330. }