PhpiredisConnection.php 11 KB

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