Predis.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  1. <?php
  2. namespace Predis;
  3. class PredisException extends \Exception { }
  4. class ClientException extends PredisException { }
  5. class ServerException extends PredisException { }
  6. class PipelineException extends ClientException { }
  7. class MalformedServerResponse extends ServerException { }
  8. /* ------------------------------------------------------------------------- */
  9. class Client {
  10. // TODO: command arguments should be sanitized or checked for bad arguments
  11. // (e.g. CRLF in keys for inline commands)
  12. private $_connection, $_registeredCommands, $_pipelining;
  13. public function __construct($host = Connection::DEFAULT_HOST, $port = Connection::DEFAULT_PORT) {
  14. $this->_pipelining = false;
  15. $this->_connection = new Connection($host, $port);
  16. $this->_registeredCommands = self::initializeDefaultCommands();
  17. }
  18. public function __destruct() {
  19. $this->_connection->disconnect();
  20. }
  21. public static function createCluster(/* arguments */) {
  22. $cluster = new ConnectionCluster();
  23. foreach (func_get_args() as $parameters) {
  24. $cluster->add(new Connection($parameters['host'], $parameters['port']));
  25. }
  26. $client = new Client();
  27. $client->setConnection($cluster);
  28. return $client;
  29. }
  30. private function setConnection(IConnection $connection) {
  31. $this->_connection = $connection;
  32. }
  33. public function connect() {
  34. $this->_connection->connect();
  35. }
  36. public function disconnect() {
  37. $this->_connection->disconnect();
  38. }
  39. public function isConnected() {
  40. return $this->_connection->isConnected();
  41. }
  42. public function getConnection() {
  43. return $this->_connection;
  44. }
  45. public function __call($method, $arguments) {
  46. $command = $this->createCommandInstance($method, $arguments);
  47. return $this->executeCommand($command);
  48. }
  49. public function createCommandInstance($method, $arguments) {
  50. $commandClass = $this->_registeredCommands[$method];
  51. if ($commandClass === null) {
  52. throw new ClientException("'$method' is not a registered Redis command");
  53. }
  54. $command = new $commandClass();
  55. $command->setArgumentsArray($arguments);
  56. return $command;
  57. }
  58. public function executeCommand(Command $command) {
  59. if ($this->_pipelining === false) {
  60. $this->_connection->writeCommand($command);
  61. if ($command->closesConnection()) {
  62. return $this->_connection->disconnect();
  63. }
  64. return $this->_connection->readResponse($command);
  65. }
  66. else {
  67. $this->_pipelineBuffer[] = $command;
  68. }
  69. }
  70. public function rawCommand($rawCommandData, $closesConnection = false) {
  71. // TODO: rather than check the type of a connection instance, we should
  72. // check if it does respond to the rawCommand method.
  73. if (is_a($this->_connection, '\Predis\ConnectionCluster')) {
  74. throw new ClientException('Cannot send raw commands when connected to a cluster of Redis servers');
  75. }
  76. return $this->_connection->rawCommand($rawCommandData, $closesConnection);
  77. }
  78. public function pipeline(\Closure $pipelineBlock) {
  79. $pipelineBlockException = null;
  80. $returnValues = array();
  81. try {
  82. $pipeline = new CommandPipeline($this);
  83. $this->_pipelining = true;
  84. $pipelineBlock($pipeline);
  85. // TODO: this should be moved entirely into the
  86. // self-contained CommandPipeline instance.
  87. $recordedCommands = $pipeline->getRecordedCommands();
  88. foreach ($recordedCommands as $command) {
  89. $this->_connection->writeCommand($command);
  90. }
  91. foreach ($recordedCommands as $command) {
  92. $returnValues[] = $this->_connection->readResponse($command);
  93. }
  94. }
  95. catch (\Exception $exception) {
  96. $pipelineBlockException = $exception;
  97. }
  98. $this->_pipelining = false;
  99. if ($pipelineBlockException !== null) {
  100. throw new PipelineException('An exception has occurred inside of a pipeline block',
  101. null, $pipelineBlockException);
  102. }
  103. return $returnValues;
  104. }
  105. public function registerCommands(Array $commands) {
  106. foreach ($commands as $command => $aliases) {
  107. $this->registerCommand($command, $aliases);
  108. }
  109. }
  110. public function registerCommand($command, $aliases) {
  111. $commandReflection = new \ReflectionClass($command);
  112. if (!$commandReflection->isSubclassOf('\Predis\Command')) {
  113. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  114. }
  115. if (is_array($aliases)) {
  116. foreach ($aliases as $alias) {
  117. $this->_registeredCommands[$alias] = $command;
  118. }
  119. }
  120. else {
  121. $this->_registeredCommands[$aliases] = $command;
  122. }
  123. }
  124. private static function initializeDefaultCommands() {
  125. // NOTE: we don't use \Predis\Client::registerCommands for performance reasons.
  126. return array(
  127. /* miscellaneous commands */
  128. 'ping' => '\Predis\Commands\Ping',
  129. 'echo' => '\Predis\Commands\DoEcho',
  130. 'auth' => '\Predis\Commands\Auth',
  131. /* connection handling */
  132. 'quit' => '\Predis\Commands\Quit',
  133. /* commands operating on string values */
  134. 'set' => '\Predis\Commands\Set',
  135. 'setnx' => '\Predis\Commands\SetPreserve',
  136. 'setPreserve' => '\Predis\Commands\SetPreserve',
  137. 'mset' => '\Predis\Commands\SetMultiple',
  138. 'setMultiple' => '\Predis\Commands\SetMultiple',
  139. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  140. 'setMultiplePreserve' => '\Predis\Commands\SetMultiplePreserve',
  141. 'get' => '\Predis\Commands\Get',
  142. 'mget' => '\Predis\Commands\GetMultiple',
  143. 'getMultiple' => '\Predis\Commands\GetMultiple',
  144. 'getset' => '\Predis\Commands\GetSet',
  145. 'getSet' => '\Predis\Commands\GetSet',
  146. 'incr' => '\Predis\Commands\Increment',
  147. 'increment' => '\Predis\Commands\Increment',
  148. 'incrby' => '\Predis\Commands\IncrementBy',
  149. 'incrementBy' => '\Predis\Commands\IncrementBy',
  150. 'incr' => '\Predis\Commands\Decrement',
  151. 'decrement' => '\Predis\Commands\Decrement',
  152. 'decrby' => '\Predis\Commands\DecrementBy',
  153. 'decrementBy' => '\Predis\Commands\DecrementBy',
  154. 'exists' => '\Predis\Commands\Exists',
  155. 'del' => '\Predis\Commands\Delete',
  156. 'delete' => '\Predis\Commands\Delete',
  157. 'type' => '\Predis\Commands\Type',
  158. /* commands operating on the key space */
  159. 'keys' => '\Predis\Commands\Keys',
  160. 'randomkey' => '\Predis\Commands\RandomKey',
  161. 'randomKey' => '\Predis\Commands\RandomKey',
  162. 'rename' => '\Predis\Commands\Rename',
  163. 'renamenx' => '\Predis\Commands\RenamePreserve',
  164. 'renamePreserve' => '\Predis\Commands\RenamePreserve',
  165. 'expire' => '\Predis\Commands\Expire',
  166. 'expireat' => '\Predis\Commands\ExpireAt',
  167. 'expireAt' => '\Predis\Commands\ExpireAt',
  168. 'dbsize' => '\Predis\Commands\DatabaseSize',
  169. 'databaseSize' => '\Predis\Commands\DatabaseSize',
  170. 'ttl' => '\Predis\Commands\TimeToLive',
  171. 'timeToLive' => '\Predis\Commands\TimeToLive',
  172. /* commands operating on lists */
  173. 'rpush' => '\Predis\Commands\ListPushTail',
  174. 'pushTail' => '\Predis\Commands\ListPushTail',
  175. 'lpush' => '\Predis\Commands\ListPushHead',
  176. 'pushHead' => '\Predis\Commands\ListPushHead',
  177. 'llen' => '\Predis\Commands\ListLength',
  178. 'listLength' => '\Predis\Commands\ListLength',
  179. 'lrange' => '\Predis\Commands\ListRange',
  180. 'listRange' => '\Predis\Commands\ListRange',
  181. 'ltrim' => '\Predis\Commands\ListTrim',
  182. 'listTrim' => '\Predis\Commands\ListTrim',
  183. 'lindex' => '\Predis\Commands\ListIndex',
  184. 'listIndex' => '\Predis\Commands\ListIndex',
  185. 'lset' => '\Predis\Commands\ListSet',
  186. 'listSet' => '\Predis\Commands\ListSet',
  187. 'lrem' => '\Predis\Commands\ListRemove',
  188. 'listRemove' => '\Predis\Commands\ListRemove',
  189. 'lpop' => '\Predis\Commands\ListPopFirst',
  190. 'popFirst' => '\Predis\Commands\ListPopFirst',
  191. 'rpop' => '\Predis\Commands\ListPopLast',
  192. 'popLast' => '\Predis\Commands\ListPopLast',
  193. /* commands operating on sets */
  194. 'sadd' => '\Predis\Commands\SetAdd',
  195. 'setAdd' => '\Predis\Commands\SetAdd',
  196. 'srem' => '\Predis\Commands\SetRemove',
  197. 'setRemove' => '\Predis\Commands\SetRemove',
  198. 'spop' => '\Predis\Commands\SetPop',
  199. 'setPop' => '\Predis\Commands\SetPop',
  200. 'smove' => '\Predis\Commands\SetMove',
  201. 'setMove' => '\Predis\Commands\SetMove',
  202. 'scard' => '\Predis\Commands\SetCardinality',
  203. 'setCardinality' => '\Predis\Commands\SetCardinality',
  204. 'sismember' => '\Predis\Commands\SetIsMember',
  205. 'setIsMember' => '\Predis\Commands\SetIsMember',
  206. 'sinter' => '\Predis\Commands\SetIntersection',
  207. 'setIntersection' => '\Predis\Commands\SetIntersection',
  208. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  209. 'setIntersectionStore' => '\Predis\Commands\SetIntersectionStore',
  210. 'sunion' => '\Predis\Commands\SetUnion',
  211. 'setUnion' => '\Predis\Commands\SetUnion',
  212. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  213. 'setUnionStore' => '\Predis\Commands\SetUnionStore',
  214. 'sdiff' => '\Predis\Commands\SetDifference',
  215. 'setDifference' => '\Predis\Commands\SetDifference',
  216. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  217. 'setDifferenceStore' => '\Predis\Commands\SetDifferenceStore',
  218. 'smembers' => '\Predis\Commands\SetMembers',
  219. 'setMembers' => '\Predis\Commands\SetMembers',
  220. 'srandmember' => '\Predis\Commands\SetRandomMember',
  221. 'setRandomMember' => '\Predis\Commands\SetRandomMember',
  222. /* commands operating on sorted sets */
  223. 'zadd' => '\Predis\Commands\ZSetAdd',
  224. 'zsetAdd' => '\Predis\Commands\ZSetAdd',
  225. 'zrem' => '\Predis\Commands\ZSetRemove',
  226. 'zsetRemove' => '\Predis\Commands\ZSetRemove',
  227. 'zrange' => '\Predis\Commands\ZSetRange',
  228. 'zsetRange' => '\Predis\Commands\ZSetRange',
  229. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  230. 'zsetReverseRange' => '\Predis\Commands\ZSetReverseRange',
  231. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  232. 'zsetRangeByScore' => '\Predis\Commands\ZSetRangeByScore',
  233. 'zcard' => '\Predis\Commands\ZSetCardinality',
  234. 'zsetCardinality' => '\Predis\Commands\ZSetCardinality',
  235. 'zscore' => '\Predis\Commands\ZSetScore',
  236. 'zsetScore' => '\Predis\Commands\ZSetScore',
  237. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  238. 'zsetRemoveRangeByScore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  239. /* multiple databases handling commands */
  240. 'select' => '\Predis\Commands\SelectDatabase',
  241. 'selectDatabase' => '\Predis\Commands\SelectDatabase',
  242. 'move' => '\Predis\Commands\MoveKey',
  243. 'moveKey' => '\Predis\Commands\MoveKey',
  244. 'flushdb' => '\Predis\Commands\FlushDatabase',
  245. 'flushDatabase' => '\Predis\Commands\FlushDatabase',
  246. 'flushall' => '\Predis\Commands\FlushAll',
  247. 'flushDatabases' => '\Predis\Commands\FlushAll',
  248. /* sorting */
  249. 'sort' => '\Predis\Commands\Sort',
  250. /* remote server control commands */
  251. 'info' => '\Predis\Commands\Info',
  252. 'slaveof' => '\Predis\Commands\SlaveOf',
  253. 'slaveOf' => '\Predis\Commands\SlaveOf',
  254. /* persistence control commands */
  255. 'save' => '\Predis\Commands\Save',
  256. 'bgsave' => '\Predis\Commands\BackgroundSave',
  257. 'backgroundSave' => '\Predis\Commands\BackgroundSave',
  258. 'lastsave' => '\Predis\Commands\LastSave',
  259. 'lastSave' => '\Predis\Commands\LastSave',
  260. 'shutdown' => '\Predis\Commands\Shutdown'
  261. );
  262. }
  263. }
  264. /* ------------------------------------------------------------------------- */
  265. abstract class Command {
  266. private $_arguments;
  267. public abstract function getCommandId();
  268. public abstract function serializeRequest($command, $arguments);
  269. public function canBeHashed() {
  270. return true;
  271. }
  272. public function closesConnection() {
  273. return false;
  274. }
  275. protected function filterArguments(Array $arguments) {
  276. return $arguments;
  277. }
  278. public function setArguments(/* arguments */) {
  279. $this->_arguments = $this->filterArguments(func_get_args());
  280. }
  281. public function setArgumentsArray(Array $arguments) {
  282. $this->_arguments = $this->filterArguments($arguments);
  283. }
  284. protected function getArguments() {
  285. return $this->_arguments !== null ? $this->_arguments : array();
  286. }
  287. public function getArgument($index = 0) {
  288. return $this->_arguments !== null ? $this->_arguments[$index] : null;
  289. }
  290. public function parseResponse($data) {
  291. return $data;
  292. }
  293. public final function __invoke() {
  294. return $this->serializeRequest($this->getCommandId(), $this->getArguments());
  295. }
  296. }
  297. abstract class InlineCommand extends Command {
  298. public function serializeRequest($command, $arguments) {
  299. if (isset($arguments[0]) && is_array($arguments[0])) {
  300. $arguments[0] = implode($arguments[0], ' ');
  301. }
  302. return $command . ' ' . implode($arguments, ' ') . Response::NEWLINE;
  303. }
  304. }
  305. abstract class BulkCommand extends Command {
  306. public function serializeRequest($command, $arguments) {
  307. $data = array_pop($arguments);
  308. if (is_array($data)) {
  309. $data = implode($data, ' ');
  310. }
  311. return $command . ' ' . implode($arguments, ' ') . ' ' . strlen($data) .
  312. Response::NEWLINE . $data . Response::NEWLINE;
  313. }
  314. }
  315. abstract class MultiBulkCommand extends Command {
  316. public function serializeRequest($command, $arguments) {
  317. $buffer = array();
  318. $cmd_args = null;
  319. if (count($arguments) === 1 && is_array($arguments[0])) {
  320. $cmd_args = array();
  321. foreach ($arguments[0] as $k => $v) {
  322. $cmd_args[] = $k;
  323. $cmd_args[] = $v;
  324. }
  325. }
  326. else {
  327. $cmd_args = $arguments;
  328. }
  329. $buffer[] = '*' . ((string) count($cmd_args) + 1) . Response::NEWLINE;
  330. $buffer[] = '$' . strlen($command) . Response::NEWLINE . $command . Response::NEWLINE;
  331. foreach ($cmd_args as $argument) {
  332. $buffer[] = '$' . strlen($argument) . Response::NEWLINE . $argument . Response::NEWLINE;
  333. }
  334. return implode('', $buffer);
  335. }
  336. }
  337. /* ------------------------------------------------------------------------- */
  338. class Response {
  339. const NEWLINE = "\r\n";
  340. const OK = 'OK';
  341. const ERROR = 'ERR';
  342. const NULL = 'nil';
  343. private static $_prefixHandlers;
  344. private static function initializePrefixHandlers() {
  345. return array(
  346. // status
  347. '+' => function($socket) {
  348. $status = rtrim(fgets($socket), Response::NEWLINE);
  349. return $status === Response::OK ? true : $status;
  350. },
  351. // error
  352. '-' => function($socket) {
  353. $errorMessage = rtrim(fgets($socket), Response::NEWLINE);
  354. throw new ServerException(substr($errorMessage, 4));
  355. },
  356. // bulk
  357. '$' => function($socket) {
  358. $dataLength = rtrim(fgets($socket), Response::NEWLINE);
  359. if (!is_numeric($dataLength)) {
  360. throw new ClientException("Cannot parse '$dataLength' as data length");
  361. }
  362. if ($dataLength > 0) {
  363. $value = fread($socket, $dataLength);
  364. fread($socket, 2);
  365. return $value;
  366. }
  367. else if ($dataLength == 0) {
  368. // TODO: I just have a doubt here...
  369. fread($socket, 2);
  370. }
  371. return null;
  372. },
  373. // multibulk
  374. '*' => function($socket) {
  375. $rawLength = rtrim(fgets($socket), Response::NEWLINE);
  376. if (!is_numeric($rawLength)) {
  377. throw new ClientException("Cannot parse '$rawLength' as data length");
  378. }
  379. $listLength = (int) $rawLength;
  380. if ($listLength === -1) {
  381. return null;
  382. }
  383. $list = array();
  384. if ($listLength > 0) {
  385. for ($i = 0; $i < $listLength; $i++) {
  386. $handler = Response::getPrefixHandler(fgetc($socket));
  387. $list[] = $handler($socket);
  388. }
  389. }
  390. return $list;
  391. },
  392. // integer
  393. ':' => function($socket) {
  394. $number = rtrim(fgets($socket), Response::NEWLINE);
  395. if (is_numeric($number)) {
  396. return (int) $number;
  397. }
  398. else {
  399. if ($number !== Response::NULL) {
  400. throw new ClientException("Cannot parse '$number' as numeric response");
  401. }
  402. return null;
  403. }
  404. }
  405. );
  406. }
  407. public static function getPrefixHandler($prefix) {
  408. if (self::$_prefixHandlers == null) {
  409. self::$_prefixHandlers = self::initializePrefixHandlers();
  410. }
  411. $handler = self::$_prefixHandlers[$prefix];
  412. if ($handler === null) {
  413. throw new MalformedServerResponse("Unknown prefix '$prefix'");
  414. }
  415. return $handler;
  416. }
  417. }
  418. class CommandPipeline {
  419. private $_redisClient, $_pipelineBuffer;
  420. public function __construct(Client $redisClient) {
  421. $this->_redisClient = $redisClient;
  422. $this->_pipelineBuffer = array();
  423. }
  424. public function __call($method, $arguments) {
  425. $command = $this->_redisClient->createCommandInstance($method, $arguments);
  426. $this->registerCommand($command);
  427. }
  428. private function registerCommand(Command $command) {
  429. $this->_pipelineBuffer[] = $command;
  430. }
  431. public function getRecordedCommands() {
  432. return $this->_pipelineBuffer;
  433. }
  434. }
  435. /* ------------------------------------------------------------------------- */
  436. interface IConnection {
  437. public function connect();
  438. public function disconnect();
  439. public function isConnected();
  440. public function writeCommand(Command $command);
  441. public function readResponse(Command $command);
  442. }
  443. class Connection implements IConnection {
  444. const DEFAULT_HOST = '127.0.0.1';
  445. const DEFAULT_PORT = 6379;
  446. const CONNECTION_TIMEOUT = 2;
  447. const READ_WRITE_TIMEOUT = 5;
  448. private $_host, $_port, $_socket;
  449. public function __construct($host = self::DEFAULT_HOST, $port = self::DEFAULT_PORT) {
  450. $this->_host = $host;
  451. $this->_port = $port;
  452. }
  453. public function __destruct() {
  454. $this->disconnect();
  455. }
  456. public function isConnected() {
  457. return is_resource($this->_socket);
  458. }
  459. public function connect() {
  460. if ($this->isConnected()) {
  461. throw new ClientException('Connection already estabilished');
  462. }
  463. $uri = sprintf('tcp://%s:%d/', $this->_host, $this->_port);
  464. $this->_socket = @stream_socket_client($uri, $errno, $errstr, self::CONNECTION_TIMEOUT);
  465. if (!$this->_socket) {
  466. throw new ClientException(trim($errstr), $errno);
  467. }
  468. stream_set_timeout($this->_socket, self::READ_WRITE_TIMEOUT);
  469. }
  470. public function disconnect() {
  471. if ($this->isConnected()) {
  472. fclose($this->_socket);
  473. }
  474. }
  475. public function writeCommand(Command $command) {
  476. fwrite($this->getSocket(), $command());
  477. }
  478. public function readResponse(Command $command) {
  479. $socket = $this->getSocket();
  480. $handler = Response::getPrefixHandler(fgetc($socket));
  481. $response = $command->parseResponse($handler($socket));
  482. return $response;
  483. }
  484. public function rawCommand($rawCommandData, $closesConnection = false) {
  485. $socket = $this->getSocket();
  486. fwrite($socket, $rawCommandData);
  487. if ($closesConnection) {
  488. return;
  489. }
  490. $handler = Response::getPrefixHandler(fgetc($socket));
  491. return $handler($socket);
  492. }
  493. public function getSocket() {
  494. if (!$this->isConnected()) {
  495. $this->connect();
  496. }
  497. return $this->_socket;
  498. }
  499. public function __toString() {
  500. return sprintf('tcp://%s:%d/', $this->_host, $this->_port);
  501. }
  502. }
  503. class ConnectionCluster implements IConnection {
  504. // TODO: storing a temporary map of commands hashes to hashring items (that
  505. // is, connections) could offer a notable speedup, but I am wondering
  506. // about the increased memory footprint.
  507. // TODO: find a clean way to handle connection failures of single nodes.
  508. private $_pool, $_ring;
  509. public function __construct() {
  510. $this->_pool = array();
  511. $this->_ring = new Utilities\HashRing();
  512. }
  513. public function __destruct() {
  514. $this->disconnect();
  515. }
  516. public function isConnected() {
  517. foreach ($this->_pool as $connection) {
  518. if ($connection->isConnected()) {
  519. return true;
  520. }
  521. }
  522. return false;
  523. }
  524. public function connect() {
  525. foreach ($this->_pool as $connection) {
  526. $connection->connect();
  527. }
  528. }
  529. public function disconnect() {
  530. foreach ($this->_pool as $connection) {
  531. $connection->disconnect();
  532. }
  533. }
  534. public function add(Connection $connection) {
  535. $this->_pool[] = $connection;
  536. $this->_ring->add($connection);
  537. }
  538. private function getConnectionFromRing(Command $command) {
  539. return $this->_ring->get($this->computeHash($command));
  540. }
  541. private function computeHash(Command $command) {
  542. return crc32($command->getArgument(0));
  543. }
  544. private function getConnection(Command $command) {
  545. return $command->canBeHashed()
  546. ? $this->getConnectionFromRing($command)
  547. : $this->getConnectionById(0);
  548. }
  549. public function getConnectionById($id = null) {
  550. return $this->_pool[$id === null ? 0 : $id];
  551. }
  552. public function writeCommand(Command $command) {
  553. $this->getConnection($command)->writeCommand($command);
  554. }
  555. public function readResponse(Command $command) {
  556. return $this->getConnection($command)->readResponse($command);
  557. }
  558. }
  559. /* ------------------------------------------------------------------------- */
  560. namespace Predis\Utilities;
  561. class HashRing {
  562. const NUMBER_OF_REPLICAS = 64;
  563. private $_ring, $_ringKeys;
  564. public function __construct() {
  565. $this->_ring = array();
  566. $this->_ringKeys = array();
  567. }
  568. public function add($node) {
  569. for ($i = 0; $i < self::NUMBER_OF_REPLICAS; $i++) {
  570. $key = crc32((string)$node . ':' . $i);
  571. $this->_ring[$key] = $node;
  572. }
  573. ksort($this->_ring, SORT_NUMERIC);
  574. $this->_ringKeys = array_keys($this->_ring);
  575. }
  576. public function remove($node) {
  577. for ($i = 0; $i < self::NUMBER_OF_REPLICAS; $i++) {
  578. $key = crc32((string)$node . '_' . $i);
  579. unset($this->_ring[$key]);
  580. $this->_ringKeys = array_filter($this->_ringKeys, function($rk) use($key) {
  581. return $rk !== $key;
  582. });
  583. }
  584. }
  585. public function get($key) {
  586. return $this->_ring[$this->getNodeKey($key)];
  587. }
  588. private function getNodeKey($key) {
  589. $upper = count($this->_ringKeys) - 1;
  590. $lower = 0;
  591. $index = 0;
  592. while ($lower <= $upper) {
  593. $index = ($lower + $upper) / 2;
  594. $item = $this->_ringKeys[$index];
  595. if ($item === $key) {
  596. return $index;
  597. }
  598. else if ($item > $key) {
  599. $upper = $index - 1;
  600. }
  601. else {
  602. $lower = $index + 1;
  603. }
  604. }
  605. return $this->_ringKeys[$upper];
  606. }
  607. }
  608. /* ------------------------------------------------------------------------- */
  609. namespace Predis\Commands;
  610. /* miscellaneous commands */
  611. class Ping extends \Predis\InlineCommand {
  612. public function canBeHashed() { return false; }
  613. public function getCommandId() { return 'PING'; }
  614. public function parseResponse($data) {
  615. return $data === 'PONG' ? true : false;
  616. }
  617. }
  618. class DoEcho extends \Predis\BulkCommand {
  619. public function canBeHashed() { return false; }
  620. public function getCommandId() { return 'ECHO'; }
  621. }
  622. class Auth extends \Predis\InlineCommand {
  623. public function canBeHashed() { return false; }
  624. public function getCommandId() { return 'AUTH'; }
  625. }
  626. /* connection handling */
  627. class Quit extends \Predis\InlineCommand {
  628. public function canBeHashed() { return false; }
  629. public function getCommandId() { return 'QUIT'; }
  630. public function closesConnection() { return true; }
  631. }
  632. /* commands operating on string values */
  633. class Set extends \Predis\MultiBulkCommand {
  634. public function getCommandId() { return 'SET'; }
  635. }
  636. class SetPreserve extends \Predis\BulkCommand {
  637. public function getCommandId() { return 'SETNX'; }
  638. public function parseResponse($data) { return (bool) $data; }
  639. }
  640. class SetMultiple extends \Predis\MultiBulkCommand {
  641. public function canBeHashed() { return false; }
  642. public function getCommandId() { return 'MSET'; }
  643. }
  644. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  645. public function canBeHashed() { return false; }
  646. public function getCommandId() { return 'MSETNX'; }
  647. public function parseResponse($data) { return (bool) $data; }
  648. }
  649. class Get extends \Predis\MultiBulkCommand {
  650. public function getCommandId() { return 'GET'; }
  651. }
  652. class GetMultiple extends \Predis\InlineCommand {
  653. public function canBeHashed() { return false; }
  654. public function getCommandId() { return 'MGET'; }
  655. }
  656. class GetSet extends \Predis\BulkCommand {
  657. public function getCommandId() { return 'GETSET'; }
  658. }
  659. class Increment extends \Predis\InlineCommand {
  660. public function getCommandId() { return 'INCR'; }
  661. }
  662. class IncrementBy extends \Predis\InlineCommand {
  663. public function getCommandId() { return 'INCRBY'; }
  664. }
  665. class Decrement extends \Predis\InlineCommand {
  666. public function getCommandId() { return 'DECR'; }
  667. }
  668. class DecrementBy extends \Predis\InlineCommand {
  669. public function getCommandId() { return 'DECRBY'; }
  670. }
  671. class Exists extends \Predis\InlineCommand {
  672. public function getCommandId() { return 'EXISTS'; }
  673. public function parseResponse($data) { return (bool) $data; }
  674. }
  675. class Delete extends \Predis\InlineCommand {
  676. public function getCommandId() { return 'DEL'; }
  677. public function parseResponse($data) { return (bool) $data; }
  678. }
  679. class Type extends \Predis\InlineCommand {
  680. public function getCommandId() { return 'TYPE'; }
  681. }
  682. /* commands operating on the key space */
  683. class Keys extends \Predis\InlineCommand {
  684. public function canBeHashed() { return false; }
  685. public function getCommandId() { return 'KEYS'; }
  686. public function parseResponse($data) {
  687. // TODO: is this behaviour correct?
  688. return strlen($data) > 0 ? explode(' ', $data) : array();
  689. }
  690. }
  691. class RandomKey extends \Predis\InlineCommand {
  692. public function canBeHashed() { return false; }
  693. public function getCommandId() { return 'RANDOMKEY'; }
  694. public function parseResponse($data) { return $data !== '' ? $data : null; }
  695. }
  696. class Rename extends \Predis\InlineCommand {
  697. // TODO: doesn't RENAME break the hash-based client-side sharding?
  698. public function canBeHashed() { return false; }
  699. public function getCommandId() { return 'RENAME'; }
  700. }
  701. class RenamePreserve extends \Predis\InlineCommand {
  702. public function canBeHashed() { return false; }
  703. public function getCommandId() { return 'RENAMENX'; }
  704. public function parseResponse($data) { return (bool) $data; }
  705. }
  706. class Expire extends \Predis\InlineCommand {
  707. public function getCommandId() { return 'EXPIRE'; }
  708. public function parseResponse($data) { return (bool) $data; }
  709. }
  710. class ExpireAt extends \Predis\InlineCommand {
  711. public function getCommandId() { return 'EXPIREAT'; }
  712. public function parseResponse($data) { return (bool) $data; }
  713. }
  714. class DatabaseSize extends \Predis\InlineCommand {
  715. public function canBeHashed() { return false; }
  716. public function getCommandId() { return 'DBSIZE'; }
  717. }
  718. class TimeToLive extends \Predis\InlineCommand {
  719. public function getCommandId() { return 'TTL'; }
  720. }
  721. /* commands operating on lists */
  722. class ListPushTail extends \Predis\BulkCommand {
  723. public function getCommandId() { return 'RPUSH'; }
  724. }
  725. class ListPushHead extends \Predis\BulkCommand {
  726. public function getCommandId() { return 'LPUSH'; }
  727. }
  728. class ListLength extends \Predis\InlineCommand {
  729. public function getCommandId() { return 'LLEN'; }
  730. }
  731. class ListRange extends \Predis\InlineCommand {
  732. public function getCommandId() { return 'LRANGE'; }
  733. }
  734. class ListTrim extends \Predis\InlineCommand {
  735. public function getCommandId() { return 'LTRIM'; }
  736. }
  737. class ListIndex extends \Predis\InlineCommand {
  738. public function getCommandId() { return 'LINDEX'; }
  739. }
  740. class ListSet extends \Predis\BulkCommand {
  741. public function getCommandId() { return 'LSET'; }
  742. }
  743. class ListRemove extends \Predis\BulkCommand {
  744. public function getCommandId() { return 'LREM'; }
  745. }
  746. class ListPopFirst extends \Predis\InlineCommand {
  747. public function getCommandId() { return 'LPOP'; }
  748. }
  749. class ListPopLast extends \Predis\InlineCommand {
  750. public function getCommandId() { return 'RPOP'; }
  751. }
  752. /* commands operating on sets */
  753. class SetAdd extends \Predis\BulkCommand {
  754. public function getCommandId() { return 'SADD'; }
  755. public function parseResponse($data) { return (bool) $data; }
  756. }
  757. class SetRemove extends \Predis\BulkCommand {
  758. public function getCommandId() { return 'SREM'; }
  759. public function parseResponse($data) { return (bool) $data; }
  760. }
  761. class SetPop extends \Predis\InlineCommand {
  762. public function getCommandId() { return 'SPOP'; }
  763. }
  764. class SetMove extends \Predis\BulkCommand {
  765. public function canBeHashed() { return false; }
  766. public function getCommandId() { return 'SMOVE'; }
  767. public function parseResponse($data) { return (bool) $data; }
  768. }
  769. class SetCardinality extends \Predis\InlineCommand {
  770. public function getCommandId() { return 'SCARD'; }
  771. }
  772. class SetIsMember extends \Predis\BulkCommand {
  773. public function getCommandId() { return 'SISMEMBER'; }
  774. public function parseResponse($data) { return (bool) $data; }
  775. }
  776. class SetIntersection extends \Predis\InlineCommand {
  777. public function getCommandId() { return 'SINTER'; }
  778. }
  779. class SetIntersectionStore extends \Predis\InlineCommand {
  780. public function getCommandId() { return 'SINTERSTORE'; }
  781. }
  782. class SetUnion extends \Predis\InlineCommand {
  783. public function getCommandId() { return 'SUNION'; }
  784. }
  785. class SetUnionStore extends \Predis\InlineCommand {
  786. public function getCommandId() { return 'SUNIONSTORE'; }
  787. }
  788. class SetDifference extends \Predis\InlineCommand {
  789. public function getCommandId() { return 'SDIFF'; }
  790. }
  791. class SetDifferenceStore extends \Predis\InlineCommand {
  792. public function getCommandId() { return 'SDIFFSTORE'; }
  793. }
  794. class SetMembers extends \Predis\InlineCommand {
  795. public function getCommandId() { return 'SMEMBERS'; }
  796. }
  797. class SetRandomMember extends \Predis\InlineCommand {
  798. public function getCommandId() { return 'SRANDMEMBER'; }
  799. }
  800. /* commands operating on sorted sets */
  801. class ZSetAdd extends \Predis\BulkCommand {
  802. public function getCommandId() { return 'ZADD'; }
  803. public function parseResponse($data) { return (bool) $data; }
  804. }
  805. class ZSetRemove extends \Predis\BulkCommand {
  806. public function getCommandId() { return 'ZREM'; }
  807. public function parseResponse($data) { return (bool) $data; }
  808. }
  809. class ZSetRange extends \Predis\InlineCommand {
  810. public function getCommandId() { return 'ZRANGE'; }
  811. }
  812. class ZSetReverseRange extends \Predis\InlineCommand {
  813. public function getCommandId() { return 'ZREVRANGE'; }
  814. }
  815. class ZSetRangeByScore extends \Predis\InlineCommand {
  816. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  817. }
  818. class ZSetCardinality extends \Predis\InlineCommand {
  819. public function getCommandId() { return 'ZCARD'; }
  820. }
  821. class ZSetScore extends \Predis\BulkCommand {
  822. public function getCommandId() { return 'ZSCORE'; }
  823. }
  824. class ZSetRemoveRangeByScore extends \Predis\InlineCommand {
  825. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  826. }
  827. /* multiple databases handling commands */
  828. class SelectDatabase extends \Predis\InlineCommand {
  829. public function canBeHashed() { return false; }
  830. public function getCommandId() { return 'SELECT'; }
  831. }
  832. class MoveKey extends \Predis\InlineCommand {
  833. public function canBeHashed() { return false; }
  834. public function getCommandId() { return 'MOVE'; }
  835. public function parseResponse($data) { return (bool) $data; }
  836. }
  837. class FlushDatabase extends \Predis\InlineCommand {
  838. public function canBeHashed() { return false; }
  839. public function getCommandId() { return 'FLUSHDB'; }
  840. }
  841. class FlushAll extends \Predis\InlineCommand {
  842. public function canBeHashed() { return false; }
  843. public function getCommandId() { return 'FLUSHALL'; }
  844. }
  845. /* sorting */
  846. class Sort extends \Predis\InlineCommand {
  847. public function getCommandId() { return 'SORT'; }
  848. public function filterArguments($arguments) {
  849. if (count($arguments) === 1) {
  850. return $arguments;
  851. }
  852. // TODO: add more parameters checks
  853. $query = array($arguments[0]);
  854. $sortParams = $arguments[1];
  855. if (isset($sortParams['by'])) {
  856. $query[] = 'BY ' . $sortParams['by'];
  857. }
  858. if (isset($sortParams['get'])) {
  859. $query[] = 'GET ' . $sortParams['get'];
  860. }
  861. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  862. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  863. }
  864. if (isset($sortParams['sort'])) {
  865. $query[] = strtoupper($sortParams['sort']);
  866. }
  867. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  868. $query[] = 'ALPHA';
  869. }
  870. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  871. $query[] = 'STORE ' . $sortParams['store'];
  872. }
  873. return $query;
  874. }
  875. }
  876. /* persistence control commands */
  877. class Save extends \Predis\InlineCommand {
  878. public function canBeHashed() { return false; }
  879. public function getCommandId() { return 'SAVE'; }
  880. }
  881. class BackgroundSave extends \Predis\InlineCommand {
  882. public function canBeHashed() { return false; }
  883. public function getCommandId() { return 'BGSAVE'; }
  884. }
  885. class LastSave extends \Predis\InlineCommand {
  886. public function canBeHashed() { return false; }
  887. public function getCommandId() { return 'LASTSAVE'; }
  888. }
  889. class Shutdown extends \Predis\InlineCommand {
  890. public function canBeHashed() { return false; }
  891. public function getCommandId() { return 'SHUTDOWN'; }
  892. public function closesConnection() { return true; }
  893. }
  894. /* remote server control commands */
  895. class Info extends \Predis\InlineCommand {
  896. public function canBeHashed() { return false; }
  897. public function getCommandId() { return 'INFO'; }
  898. public function parseResponse($data) {
  899. $info = array();
  900. $infoLines = explode("\r\n", $data, -1);
  901. foreach ($infoLines as $row) {
  902. list($k, $v) = explode(':', $row);
  903. $info[$k] = $v;
  904. }
  905. return $info;
  906. }
  907. }
  908. class SlaveOf extends \Predis\InlineCommand {
  909. public function canBeHashed() { return false; }
  910. public function getCommandId() { return 'SLAVEOF'; }
  911. public function filterArguments($arguments) {
  912. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  913. }
  914. }
  915. ?>