PhpiredisConnection.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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->params;
  150. $initializer = array($this, "{$parameters->scheme}SocketInitializer");
  151. $socket = call_user_func($initializer, $parameters);
  152. $this->setSocketOptions($socket, $parameters);
  153. return $socket;
  154. }
  155. /**
  156. * Initializes a TCP socket resource.
  157. *
  158. * @param IConnectionParameters $parameters Parameters used to initialize the connection.
  159. * @return resource
  160. */
  161. private function tcpSocketInitializer(IConnectionParameters $parameters)
  162. {
  163. $socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  164. if (!is_resource($socket)) {
  165. $this->emitSocketError();
  166. }
  167. return $socket;
  168. }
  169. /**
  170. * Initializes a UNIX socket resource.
  171. *
  172. * @param IConnectionParameters $parameters Parameters used to initialize the connection.
  173. * @return resource
  174. */
  175. private function unixSocketInitializer(IConnectionParameters $parameters)
  176. {
  177. $socket = @socket_create(AF_UNIX, SOCK_STREAM, 0);
  178. if (!is_resource($socket)) {
  179. $this->emitSocketError();
  180. }
  181. return $socket;
  182. }
  183. /**
  184. * Sets options on the socket resource from the connection parameters.
  185. *
  186. * @param resource $socket Socket resource.
  187. * @param IConnectionParameters $parameters Parameters used to initialize the connection.
  188. */
  189. private function setSocketOptions($socket, IConnectionParameters $parameters)
  190. {
  191. if ($parameters->scheme !== 'tcp') {
  192. return;
  193. }
  194. if (!socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1)) {
  195. $this->emitSocketError();
  196. }
  197. if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
  198. $this->emitSocketError();
  199. }
  200. if (isset($parameters->read_write_timeout)) {
  201. $rwtimeout = $parameters->read_write_timeout;
  202. $timeoutSec = floor($rwtimeout);
  203. $timeoutUsec = ($rwtimeout - $timeoutSec) * 1000000;
  204. $timeout = array(
  205. 'sec' => $timeoutSec,
  206. 'usec' => $timeoutUsec,
  207. );
  208. if (!socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $timeout)) {
  209. $this->emitSocketError();
  210. }
  211. if (!socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout)) {
  212. $this->emitSocketError();
  213. }
  214. }
  215. }
  216. /**
  217. * Gets the address from the connection parameters.
  218. *
  219. * @param IConnectionParameters $parameters Parameters used to initialize the connection.
  220. * @return string
  221. */
  222. private function getAddress(IConnectionParameters $parameters)
  223. {
  224. if ($parameters->scheme === 'unix') {
  225. return $parameters->path;
  226. }
  227. $host = $parameters->host;
  228. if (ip2long($host) === false) {
  229. if (($address = gethostbyname($host)) === $host) {
  230. $this->onConnectionError("Cannot resolve the address of $host");
  231. }
  232. return $address;
  233. }
  234. return $host;
  235. }
  236. /**
  237. * Opens the actual connection to the server with a timeout.
  238. *
  239. * @param IConnectionParameters $parameters Parameters used to initialize the connection.
  240. * @return string
  241. */
  242. private function connectWithTimeout(IConnectionParameters $parameters) {
  243. $host = self::getAddress($parameters);
  244. $socket = $this->getResource();
  245. socket_set_nonblock($socket);
  246. if (@socket_connect($socket, $host, $parameters->port) === false) {
  247. $error = socket_last_error();
  248. if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) {
  249. $this->emitSocketError();
  250. }
  251. }
  252. socket_set_block($socket);
  253. $null = null;
  254. $selectable = array($socket);
  255. $timeout = $parameters->connection_timeout;
  256. $timeoutSecs = floor($timeout);
  257. $timeoutUSecs = ($timeout - $timeoutSecs) * 1000000;
  258. $selected = socket_select($selectable, $selectable, $null, $timeoutSecs, $timeoutUSecs);
  259. if ($selected === 2) {
  260. $this->onConnectionError('Connection refused', SOCKET_ECONNREFUSED);
  261. }
  262. if ($selected === 0) {
  263. $this->onConnectionError('Connection timed out', SOCKET_ETIMEDOUT);
  264. }
  265. if ($selected === false) {
  266. $this->emitSocketError();
  267. }
  268. }
  269. /**
  270. * {@inheritdoc}
  271. */
  272. public function connect()
  273. {
  274. parent::connect();
  275. $this->connectWithTimeout($this->params);
  276. if (count($this->initCmds) > 0) {
  277. $this->sendInitializationCommands();
  278. }
  279. }
  280. /**
  281. * {@inheritdoc}
  282. */
  283. public function disconnect()
  284. {
  285. if ($this->isConnected()) {
  286. socket_close($this->getResource());
  287. parent::disconnect();
  288. }
  289. }
  290. /**
  291. * Sends the initialization commands to Redis when the connection is opened.
  292. */
  293. private function sendInitializationCommands()
  294. {
  295. foreach ($this->initCmds as $command) {
  296. $this->writeCommand($command);
  297. }
  298. foreach ($this->initCmds as $command) {
  299. $this->readResponse($command);
  300. }
  301. }
  302. /**
  303. * {@inheritdoc}
  304. */
  305. private function write($buffer)
  306. {
  307. $socket = $this->getResource();
  308. while (($length = strlen($buffer)) > 0) {
  309. $written = socket_write($socket, $buffer, $length);
  310. if ($length === $written) {
  311. return;
  312. }
  313. if ($written === false) {
  314. $this->onConnectionError('Error while writing bytes to the server');
  315. }
  316. $buffer = substr($buffer, $written);
  317. }
  318. }
  319. /**
  320. * {@inheritdoc}
  321. */
  322. public function read()
  323. {
  324. $socket = $this->getResource();
  325. $reader = $this->reader;
  326. while (($state = phpiredis_reader_get_state($reader)) === PHPIREDIS_READER_STATE_INCOMPLETE) {
  327. if (@socket_recv($socket, $buffer, 4096, 0) === false || $buffer === '') {
  328. $this->emitSocketError();
  329. }
  330. phpiredis_reader_feed($reader, $buffer);
  331. }
  332. if ($state === PHPIREDIS_READER_STATE_COMPLETE) {
  333. return phpiredis_reader_get_reply($reader);
  334. }
  335. else {
  336. $this->onProtocolError(phpiredis_reader_get_error($reader));
  337. }
  338. }
  339. /**
  340. * {@inheritdoc}
  341. */
  342. public function writeCommand(ICommand $command)
  343. {
  344. $cmdargs = $command->getArguments();
  345. array_unshift($cmdargs, $command->getId());
  346. $this->write(phpiredis_format_command($cmdargs));
  347. }
  348. }