PhpiredisConnection.php 11 KB

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