PhpiredisConnection.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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\Network;
  11. use Predis\Commands\ICommand;
  12. use Predis\IConnectionParameters;
  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. * @link http://github.com/seppo0010/phpiredis
  35. * @author Daniele Alessandri <suppakilla@gmail.com>
  36. */
  37. class PhpiredisConnection extends ConnectionBase
  38. {
  39. private $reader;
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function __construct(IConnectionParameters $parameters)
  44. {
  45. if (!function_exists('socket_create')) {
  46. throw new NotSupportedException(
  47. 'The socket extension must be loaded in order to be able to ' .
  48. 'use this connection class'
  49. );
  50. }
  51. parent::__construct($parameters);
  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. * {@inheritdoc}
  64. */
  65. protected function checkParameters(IConnectionParameters $parameters)
  66. {
  67. if ($parameters->isSetByUser('iterable_multibulk')) {
  68. $this->onInvalidOption('iterable_multibulk', $parameters);
  69. }
  70. if ($parameters->isSetByUser('connection_persistent')) {
  71. $this->onInvalidOption('connection_persistent', $parameters);
  72. }
  73. return parent::checkParameters($parameters);
  74. }
  75. /**
  76. * Initializes the protocol reader resource.
  77. *
  78. * @param Boolean $throw_errors Specify if Redis errors throw exceptions.
  79. */
  80. private function initializeReader($throw_errors = true)
  81. {
  82. if (!function_exists('phpiredis_reader_create')) {
  83. throw new NotSupportedException(
  84. 'The phpiredis extension must be loaded in order to be able to ' .
  85. 'use this connection class'
  86. );
  87. }
  88. $reader = phpiredis_reader_create();
  89. phpiredis_reader_set_status_handler($reader, $this->getStatusHandler());
  90. phpiredis_reader_set_error_handler($reader, $this->getErrorHandler($throw_errors));
  91. $this->reader = $reader;
  92. }
  93. /**
  94. * {@inheritdoc}
  95. */
  96. protected function initializeProtocol(IConnectionParameters $parameters)
  97. {
  98. $this->initializeReader($parameters->throw_errors);
  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. * @param Boolean $throw_errors Specify if Redis errors throw exceptions.
  122. * @return \Closure
  123. */
  124. private function getErrorHandler($throwErrors = true)
  125. {
  126. if ($throwErrors) {
  127. return function($errorMessage) {
  128. throw new ServerException($errorMessage);
  129. };
  130. }
  131. return function($errorMessage) {
  132. return new ResponseError($errorMessage);
  133. };
  134. }
  135. /**
  136. * Helper method used to throw exceptions on socket errors.
  137. */
  138. private function emitSocketError()
  139. {
  140. $errno = socket_last_error();
  141. $errstr = socket_strerror($errno);
  142. $this->disconnect();
  143. $this->onConnectionError(trim($errstr), $errno);
  144. }
  145. /**
  146. * {@inheritdoc}
  147. */
  148. protected function createResource()
  149. {
  150. $parameters = $this->parameters;
  151. $isUnix = $this->parameters->scheme === 'unix';
  152. $domain = $isUnix ? AF_UNIX : AF_INET;
  153. $protocol = $isUnix ? 0 : SOL_TCP;
  154. $socket = @call_user_func('socket_create', $domain, SOCK_STREAM, $protocol);
  155. if (!is_resource($socket)) {
  156. $this->emitSocketError();
  157. }
  158. $this->setSocketOptions($socket, $parameters);
  159. return $socket;
  160. }
  161. /**
  162. * Sets options on the socket resource from the connection parameters.
  163. *
  164. * @param resource $socket Socket resource.
  165. * @param IConnectionParameters $parameters Parameters used to initialize the connection.
  166. */
  167. private function setSocketOptions($socket, IConnectionParameters $parameters)
  168. {
  169. if ($parameters->scheme !== 'tcp') {
  170. return;
  171. }
  172. if (!socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1)) {
  173. $this->emitSocketError();
  174. }
  175. if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
  176. $this->emitSocketError();
  177. }
  178. if (isset($parameters->read_write_timeout)) {
  179. $rwtimeout = $parameters->read_write_timeout;
  180. $timeoutSec = floor($rwtimeout);
  181. $timeoutUsec = ($rwtimeout - $timeoutSec) * 1000000;
  182. $timeout = array(
  183. 'sec' => $timeoutSec,
  184. 'usec' => $timeoutUsec,
  185. );
  186. if (!socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $timeout)) {
  187. $this->emitSocketError();
  188. }
  189. if (!socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout)) {
  190. $this->emitSocketError();
  191. }
  192. }
  193. }
  194. /**
  195. * Gets the address from the connection parameters.
  196. *
  197. * @param IConnectionParameters $parameters Parameters used to initialize the connection.
  198. * @return string
  199. */
  200. private function getAddress(IConnectionParameters $parameters)
  201. {
  202. if ($parameters->scheme === 'unix') {
  203. return $parameters->path;
  204. }
  205. $host = $parameters->host;
  206. if (ip2long($host) === false) {
  207. if (($address = gethostbyname($host)) === $host) {
  208. $this->onConnectionError("Cannot resolve the address of $host");
  209. }
  210. return $address;
  211. }
  212. return $host;
  213. }
  214. /**
  215. * Opens the actual connection to the server with a timeout.
  216. *
  217. * @param IConnectionParameters $parameters Parameters used to initialize the connection.
  218. * @return string
  219. */
  220. private function connectWithTimeout(IConnectionParameters $parameters)
  221. {
  222. $host = self::getAddress($parameters);
  223. $socket = $this->getResource();
  224. socket_set_nonblock($socket);
  225. if (@socket_connect($socket, $host, $parameters->port) === false) {
  226. $error = socket_last_error();
  227. if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) {
  228. $this->emitSocketError();
  229. }
  230. }
  231. socket_set_block($socket);
  232. $null = null;
  233. $selectable = array($socket);
  234. $timeout = $parameters->connection_timeout;
  235. $timeoutSecs = floor($timeout);
  236. $timeoutUSecs = ($timeout - $timeoutSecs) * 1000000;
  237. $selected = socket_select($selectable, $selectable, $null, $timeoutSecs, $timeoutUSecs);
  238. if ($selected === 2) {
  239. $this->onConnectionError('Connection refused', SOCKET_ECONNREFUSED);
  240. }
  241. if ($selected === 0) {
  242. $this->onConnectionError('Connection timed out', SOCKET_ETIMEDOUT);
  243. }
  244. if ($selected === false) {
  245. $this->emitSocketError();
  246. }
  247. }
  248. /**
  249. * {@inheritdoc}
  250. */
  251. public function connect()
  252. {
  253. parent::connect();
  254. $this->connectWithTimeout($this->parameters);
  255. if (count($this->initCmds) > 0) {
  256. $this->sendInitializationCommands();
  257. }
  258. }
  259. /**
  260. * {@inheritdoc}
  261. */
  262. public function disconnect()
  263. {
  264. if ($this->isConnected()) {
  265. socket_close($this->getResource());
  266. parent::disconnect();
  267. }
  268. }
  269. /**
  270. * Sends the initialization commands to Redis when the connection is opened.
  271. */
  272. private function sendInitializationCommands()
  273. {
  274. foreach ($this->initCmds as $command) {
  275. $this->writeCommand($command);
  276. }
  277. foreach ($this->initCmds as $command) {
  278. $this->readResponse($command);
  279. }
  280. }
  281. /**
  282. * {@inheritdoc}
  283. */
  284. private function write($buffer)
  285. {
  286. $socket = $this->getResource();
  287. while (($length = strlen($buffer)) > 0) {
  288. $written = socket_write($socket, $buffer, $length);
  289. if ($length === $written) {
  290. return;
  291. }
  292. if ($written === false) {
  293. $this->onConnectionError('Error while writing bytes to the server');
  294. }
  295. $buffer = substr($buffer, $written);
  296. }
  297. }
  298. /**
  299. * {@inheritdoc}
  300. */
  301. public function read()
  302. {
  303. $socket = $this->getResource();
  304. $reader = $this->reader;
  305. while (($state = phpiredis_reader_get_state($reader)) === PHPIREDIS_READER_STATE_INCOMPLETE) {
  306. if (@socket_recv($socket, $buffer, 4096, 0) === false || $buffer === '') {
  307. $this->emitSocketError();
  308. }
  309. phpiredis_reader_feed($reader, $buffer);
  310. }
  311. if ($state === PHPIREDIS_READER_STATE_COMPLETE) {
  312. return phpiredis_reader_get_reply($reader);
  313. }
  314. else {
  315. $this->onProtocolError(phpiredis_reader_get_error($reader));
  316. }
  317. }
  318. /**
  319. * {@inheritdoc}
  320. */
  321. public function writeCommand(ICommand $command)
  322. {
  323. $cmdargs = $command->getArguments();
  324. array_unshift($cmdargs, $command->getId());
  325. $this->write(phpiredis_format_command($cmdargs));
  326. }
  327. /**
  328. * {@inheritdoc}
  329. */
  330. public function __wakeup()
  331. {
  332. $this->initializeProtocol($this->getParameters());
  333. }
  334. }