Predis.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  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. 'rpoplpush' => '\Predis\Commands\ListPushTailPopFirst',
  194. 'listPushTailPopFist' => '\Predis\Commands\ListPushTailPopFirst',
  195. /* commands operating on sets */
  196. 'sadd' => '\Predis\Commands\SetAdd',
  197. 'setAdd' => '\Predis\Commands\SetAdd',
  198. 'srem' => '\Predis\Commands\SetRemove',
  199. 'setRemove' => '\Predis\Commands\SetRemove',
  200. 'spop' => '\Predis\Commands\SetPop',
  201. 'setPop' => '\Predis\Commands\SetPop',
  202. 'smove' => '\Predis\Commands\SetMove',
  203. 'setMove' => '\Predis\Commands\SetMove',
  204. 'scard' => '\Predis\Commands\SetCardinality',
  205. 'setCardinality' => '\Predis\Commands\SetCardinality',
  206. 'sismember' => '\Predis\Commands\SetIsMember',
  207. 'setIsMember' => '\Predis\Commands\SetIsMember',
  208. 'sinter' => '\Predis\Commands\SetIntersection',
  209. 'setIntersection' => '\Predis\Commands\SetIntersection',
  210. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  211. 'setIntersectionStore' => '\Predis\Commands\SetIntersectionStore',
  212. 'sunion' => '\Predis\Commands\SetUnion',
  213. 'setUnion' => '\Predis\Commands\SetUnion',
  214. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  215. 'setUnionStore' => '\Predis\Commands\SetUnionStore',
  216. 'sdiff' => '\Predis\Commands\SetDifference',
  217. 'setDifference' => '\Predis\Commands\SetDifference',
  218. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  219. 'setDifferenceStore' => '\Predis\Commands\SetDifferenceStore',
  220. 'smembers' => '\Predis\Commands\SetMembers',
  221. 'setMembers' => '\Predis\Commands\SetMembers',
  222. 'srandmember' => '\Predis\Commands\SetRandomMember',
  223. 'setRandomMember' => '\Predis\Commands\SetRandomMember',
  224. /* commands operating on sorted sets */
  225. 'zadd' => '\Predis\Commands\ZSetAdd',
  226. 'zsetAdd' => '\Predis\Commands\ZSetAdd',
  227. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  228. 'zsetIncrementBy' => '\Predis\Commands\ZSetIncrementBy',
  229. 'zrem' => '\Predis\Commands\ZSetRemove',
  230. 'zsetRemove' => '\Predis\Commands\ZSetRemove',
  231. 'zrange' => '\Predis\Commands\ZSetRange',
  232. 'zsetRange' => '\Predis\Commands\ZSetRange',
  233. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  234. 'zsetReverseRange' => '\Predis\Commands\ZSetReverseRange',
  235. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  236. 'zsetRangeByScore' => '\Predis\Commands\ZSetRangeByScore',
  237. 'zcard' => '\Predis\Commands\ZSetCardinality',
  238. 'zsetCardinality' => '\Predis\Commands\ZSetCardinality',
  239. 'zscore' => '\Predis\Commands\ZSetScore',
  240. 'zsetScore' => '\Predis\Commands\ZSetScore',
  241. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  242. 'zsetRemoveRangeByScore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  243. /* multiple databases handling commands */
  244. 'select' => '\Predis\Commands\SelectDatabase',
  245. 'selectDatabase' => '\Predis\Commands\SelectDatabase',
  246. 'move' => '\Predis\Commands\MoveKey',
  247. 'moveKey' => '\Predis\Commands\MoveKey',
  248. 'flushdb' => '\Predis\Commands\FlushDatabase',
  249. 'flushDatabase' => '\Predis\Commands\FlushDatabase',
  250. 'flushall' => '\Predis\Commands\FlushAll',
  251. 'flushDatabases' => '\Predis\Commands\FlushAll',
  252. /* sorting */
  253. 'sort' => '\Predis\Commands\Sort',
  254. /* remote server control commands */
  255. 'info' => '\Predis\Commands\Info',
  256. 'slaveof' => '\Predis\Commands\SlaveOf',
  257. 'slaveOf' => '\Predis\Commands\SlaveOf',
  258. /* persistence control commands */
  259. 'save' => '\Predis\Commands\Save',
  260. 'bgsave' => '\Predis\Commands\BackgroundSave',
  261. 'backgroundSave' => '\Predis\Commands\BackgroundSave',
  262. 'lastsave' => '\Predis\Commands\LastSave',
  263. 'lastSave' => '\Predis\Commands\LastSave',
  264. 'shutdown' => '\Predis\Commands\Shutdown'
  265. );
  266. }
  267. }
  268. /* ------------------------------------------------------------------------- */
  269. abstract class Command {
  270. private $_arguments;
  271. public abstract function getCommandId();
  272. public abstract function serializeRequest($command, $arguments);
  273. public function canBeHashed() {
  274. return true;
  275. }
  276. public function closesConnection() {
  277. return false;
  278. }
  279. protected function filterArguments(Array $arguments) {
  280. return $arguments;
  281. }
  282. public function setArguments(/* arguments */) {
  283. $this->_arguments = $this->filterArguments(func_get_args());
  284. }
  285. public function setArgumentsArray(Array $arguments) {
  286. $this->_arguments = $this->filterArguments($arguments);
  287. }
  288. protected function getArguments() {
  289. return $this->_arguments !== null ? $this->_arguments : array();
  290. }
  291. public function getArgument($index = 0) {
  292. return $this->_arguments !== null ? $this->_arguments[$index] : null;
  293. }
  294. public function parseResponse($data) {
  295. return $data;
  296. }
  297. public final function __invoke() {
  298. return $this->serializeRequest($this->getCommandId(), $this->getArguments());
  299. }
  300. }
  301. abstract class InlineCommand extends Command {
  302. public function serializeRequest($command, $arguments) {
  303. if (isset($arguments[0]) && is_array($arguments[0])) {
  304. $arguments[0] = implode($arguments[0], ' ');
  305. }
  306. return $command . ' ' . implode($arguments, ' ') . Response::NEWLINE;
  307. }
  308. }
  309. abstract class BulkCommand extends Command {
  310. public function serializeRequest($command, $arguments) {
  311. $data = array_pop($arguments);
  312. if (is_array($data)) {
  313. $data = implode($data, ' ');
  314. }
  315. return $command . ' ' . implode($arguments, ' ') . ' ' . strlen($data) .
  316. Response::NEWLINE . $data . Response::NEWLINE;
  317. }
  318. }
  319. abstract class MultiBulkCommand extends Command {
  320. public function serializeRequest($command, $arguments) {
  321. $buffer = array();
  322. $cmd_args = null;
  323. if (count($arguments) === 1 && is_array($arguments[0])) {
  324. $cmd_args = array();
  325. foreach ($arguments[0] as $k => $v) {
  326. $cmd_args[] = $k;
  327. $cmd_args[] = $v;
  328. }
  329. }
  330. else {
  331. $cmd_args = $arguments;
  332. }
  333. $buffer[] = '*' . ((string) count($cmd_args) + 1) . Response::NEWLINE;
  334. $buffer[] = '$' . strlen($command) . Response::NEWLINE . $command . Response::NEWLINE;
  335. foreach ($cmd_args as $argument) {
  336. $buffer[] = '$' . strlen($argument) . Response::NEWLINE . $argument . Response::NEWLINE;
  337. }
  338. return implode('', $buffer);
  339. }
  340. }
  341. /* ------------------------------------------------------------------------- */
  342. class Response {
  343. const NEWLINE = "\r\n";
  344. const OK = 'OK';
  345. const ERROR = 'ERR';
  346. const NULL = 'nil';
  347. private static $_prefixHandlers;
  348. private static function initializePrefixHandlers() {
  349. return array(
  350. // status
  351. '+' => function($socket) {
  352. $status = rtrim(fgets($socket), Response::NEWLINE);
  353. return $status === Response::OK ? true : $status;
  354. },
  355. // error
  356. '-' => function($socket) {
  357. $errorMessage = rtrim(fgets($socket), Response::NEWLINE);
  358. throw new ServerException(substr($errorMessage, 4));
  359. },
  360. // bulk
  361. '$' => function($socket) {
  362. $dataLength = rtrim(fgets($socket), Response::NEWLINE);
  363. if (!is_numeric($dataLength)) {
  364. throw new ClientException("Cannot parse '$dataLength' as data length");
  365. }
  366. if ($dataLength > 0) {
  367. $value = fread($socket, $dataLength);
  368. fread($socket, 2);
  369. return $value;
  370. }
  371. else if ($dataLength == 0) {
  372. // TODO: I just have a doubt here...
  373. fread($socket, 2);
  374. }
  375. return null;
  376. },
  377. // multibulk
  378. '*' => function($socket) {
  379. $rawLength = rtrim(fgets($socket), Response::NEWLINE);
  380. if (!is_numeric($rawLength)) {
  381. throw new ClientException("Cannot parse '$rawLength' as data length");
  382. }
  383. $listLength = (int) $rawLength;
  384. if ($listLength === -1) {
  385. return null;
  386. }
  387. $list = array();
  388. if ($listLength > 0) {
  389. for ($i = 0; $i < $listLength; $i++) {
  390. $handler = Response::getPrefixHandler(fgetc($socket));
  391. $list[] = $handler($socket);
  392. }
  393. }
  394. return $list;
  395. },
  396. // integer
  397. ':' => function($socket) {
  398. $number = rtrim(fgets($socket), Response::NEWLINE);
  399. if (is_numeric($number)) {
  400. return (int) $number;
  401. }
  402. else {
  403. if ($number !== Response::NULL) {
  404. throw new ClientException("Cannot parse '$number' as numeric response");
  405. }
  406. return null;
  407. }
  408. }
  409. );
  410. }
  411. public static function getPrefixHandler($prefix) {
  412. if (self::$_prefixHandlers == null) {
  413. self::$_prefixHandlers = self::initializePrefixHandlers();
  414. }
  415. $handler = self::$_prefixHandlers[$prefix];
  416. if ($handler === null) {
  417. throw new MalformedServerResponse("Unknown prefix '$prefix'");
  418. }
  419. return $handler;
  420. }
  421. }
  422. class CommandPipeline {
  423. private $_redisClient, $_pipelineBuffer;
  424. public function __construct(Client $redisClient) {
  425. $this->_redisClient = $redisClient;
  426. $this->_pipelineBuffer = array();
  427. }
  428. public function __call($method, $arguments) {
  429. $command = $this->_redisClient->createCommandInstance($method, $arguments);
  430. $this->recordCommand($command);
  431. }
  432. private function recordCommand(Command $command) {
  433. $this->_pipelineBuffer[] = $command;
  434. }
  435. public function getRecordedCommands() {
  436. return $this->_pipelineBuffer;
  437. }
  438. }
  439. /* ------------------------------------------------------------------------- */
  440. interface IConnection {
  441. public function connect();
  442. public function disconnect();
  443. public function isConnected();
  444. public function writeCommand(Command $command);
  445. public function readResponse(Command $command);
  446. }
  447. class Connection implements IConnection {
  448. const DEFAULT_HOST = '127.0.0.1';
  449. const DEFAULT_PORT = 6379;
  450. const CONNECTION_TIMEOUT = 2;
  451. const READ_WRITE_TIMEOUT = 5;
  452. private $_host, $_port, $_socket;
  453. public function __construct($host = self::DEFAULT_HOST, $port = self::DEFAULT_PORT) {
  454. $this->_host = $host;
  455. $this->_port = $port;
  456. }
  457. public function __destruct() {
  458. $this->disconnect();
  459. }
  460. public function isConnected() {
  461. return is_resource($this->_socket);
  462. }
  463. public function connect() {
  464. if ($this->isConnected()) {
  465. throw new ClientException('Connection already estabilished');
  466. }
  467. $uri = sprintf('tcp://%s:%d/', $this->_host, $this->_port);
  468. $this->_socket = @stream_socket_client($uri, $errno, $errstr, self::CONNECTION_TIMEOUT);
  469. if (!$this->_socket) {
  470. throw new ClientException(trim($errstr), $errno);
  471. }
  472. stream_set_timeout($this->_socket, self::READ_WRITE_TIMEOUT);
  473. }
  474. public function disconnect() {
  475. if ($this->isConnected()) {
  476. fclose($this->_socket);
  477. }
  478. }
  479. public function writeCommand(Command $command) {
  480. fwrite($this->getSocket(), $command());
  481. }
  482. public function readResponse(Command $command) {
  483. $socket = $this->getSocket();
  484. $handler = Response::getPrefixHandler(fgetc($socket));
  485. $response = $command->parseResponse($handler($socket));
  486. return $response;
  487. }
  488. public function rawCommand($rawCommandData, $closesConnection = false) {
  489. $socket = $this->getSocket();
  490. fwrite($socket, $rawCommandData);
  491. if ($closesConnection) {
  492. return;
  493. }
  494. $handler = Response::getPrefixHandler(fgetc($socket));
  495. return $handler($socket);
  496. }
  497. public function getSocket() {
  498. if (!$this->isConnected()) {
  499. $this->connect();
  500. }
  501. return $this->_socket;
  502. }
  503. public function __toString() {
  504. return sprintf('tcp://%s:%d/', $this->_host, $this->_port);
  505. }
  506. }
  507. class ConnectionCluster implements IConnection {
  508. // TODO: storing a temporary map of commands hashes to hashring items (that
  509. // is, connections) could offer a notable speedup, but I am wondering
  510. // about the increased memory footprint.
  511. // TODO: find a clean way to handle connection failures of single nodes.
  512. private $_pool, $_ring;
  513. public function __construct() {
  514. $this->_pool = array();
  515. $this->_ring = new Utilities\HashRing();
  516. }
  517. public function __destruct() {
  518. $this->disconnect();
  519. }
  520. public function isConnected() {
  521. foreach ($this->_pool as $connection) {
  522. if ($connection->isConnected()) {
  523. return true;
  524. }
  525. }
  526. return false;
  527. }
  528. public function connect() {
  529. foreach ($this->_pool as $connection) {
  530. $connection->connect();
  531. }
  532. }
  533. public function disconnect() {
  534. foreach ($this->_pool as $connection) {
  535. $connection->disconnect();
  536. }
  537. }
  538. public function add(Connection $connection) {
  539. $this->_pool[] = $connection;
  540. $this->_ring->add($connection);
  541. }
  542. private function getConnectionFromRing(Command $command) {
  543. return $this->_ring->get($this->computeHash($command));
  544. }
  545. private function computeHash(Command $command) {
  546. return crc32($command->getArgument(0));
  547. }
  548. private function getConnection(Command $command) {
  549. return $command->canBeHashed()
  550. ? $this->getConnectionFromRing($command)
  551. : $this->getConnectionById(0);
  552. }
  553. public function getConnectionById($id = null) {
  554. return $this->_pool[$id === null ? 0 : $id];
  555. }
  556. public function writeCommand(Command $command) {
  557. $this->getConnection($command)->writeCommand($command);
  558. }
  559. public function readResponse(Command $command) {
  560. return $this->getConnection($command)->readResponse($command);
  561. }
  562. }
  563. /* ------------------------------------------------------------------------- */
  564. namespace Predis\Utilities;
  565. class HashRing {
  566. const DEFAULT_REPLICAS = 128;
  567. private $_ring, $_ringKeys, $_replicas;
  568. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  569. $this->_replicas = $replicas;
  570. $this->_ring = array();
  571. $this->_ringKeys = array();
  572. }
  573. public function add($node) {
  574. $nodeHash = (string) $node;
  575. for ($i = 0; $i < $this->_replicas; $i++) {
  576. $key = crc32($nodeHash . ':' . $i);
  577. $this->_ring[$key] = $node;
  578. }
  579. ksort($this->_ring, SORT_NUMERIC);
  580. $this->_ringKeys = array_keys($this->_ring);
  581. }
  582. public function remove($node) {
  583. $nodeHash = (string) $node;
  584. for ($i = 0; $i < $this->_replicas; $i++) {
  585. $key = crc32($nodeHash . ':' . $i);
  586. unset($this->_ring[$key]);
  587. $this->_ringKeys = array_filter($this->_ringKeys, function($rk) use($key) {
  588. return $rk !== $key;
  589. });
  590. }
  591. }
  592. public function get($key) {
  593. return $this->_ring[$this->getNodeKey($key)];
  594. }
  595. private function getNodeKey($key) {
  596. $upper = count($this->_ringKeys) - 1;
  597. $lower = 0;
  598. $index = 0;
  599. while ($lower <= $upper) {
  600. $index = ($lower + $upper) / 2;
  601. $item = $this->_ringKeys[$index];
  602. if ($item === $key) {
  603. return $index;
  604. }
  605. else if ($item > $key) {
  606. $upper = $index - 1;
  607. }
  608. else {
  609. $lower = $index + 1;
  610. }
  611. }
  612. return $this->_ringKeys[$upper];
  613. }
  614. }
  615. /* ------------------------------------------------------------------------- */
  616. namespace Predis\Commands;
  617. /* miscellaneous commands */
  618. class Ping extends \Predis\InlineCommand {
  619. public function canBeHashed() { return false; }
  620. public function getCommandId() { return 'PING'; }
  621. public function parseResponse($data) {
  622. return $data === 'PONG' ? true : false;
  623. }
  624. }
  625. class DoEcho extends \Predis\BulkCommand {
  626. public function canBeHashed() { return false; }
  627. public function getCommandId() { return 'ECHO'; }
  628. }
  629. class Auth extends \Predis\InlineCommand {
  630. public function canBeHashed() { return false; }
  631. public function getCommandId() { return 'AUTH'; }
  632. }
  633. /* connection handling */
  634. class Quit extends \Predis\InlineCommand {
  635. public function canBeHashed() { return false; }
  636. public function getCommandId() { return 'QUIT'; }
  637. public function closesConnection() { return true; }
  638. }
  639. /* commands operating on string values */
  640. class Set extends \Predis\BulkCommand {
  641. public function getCommandId() { return 'SET'; }
  642. }
  643. class SetPreserve extends \Predis\BulkCommand {
  644. public function getCommandId() { return 'SETNX'; }
  645. public function parseResponse($data) { return (bool) $data; }
  646. }
  647. class SetMultiple extends \Predis\MultiBulkCommand {
  648. public function canBeHashed() { return false; }
  649. public function getCommandId() { return 'MSET'; }
  650. }
  651. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  652. public function canBeHashed() { return false; }
  653. public function getCommandId() { return 'MSETNX'; }
  654. public function parseResponse($data) { return (bool) $data; }
  655. }
  656. class Get extends \Predis\InlineCommand {
  657. public function getCommandId() { return 'GET'; }
  658. }
  659. class GetMultiple extends \Predis\InlineCommand {
  660. public function canBeHashed() { return false; }
  661. public function getCommandId() { return 'MGET'; }
  662. }
  663. class GetSet extends \Predis\BulkCommand {
  664. public function getCommandId() { return 'GETSET'; }
  665. }
  666. class Increment extends \Predis\InlineCommand {
  667. public function getCommandId() { return 'INCR'; }
  668. }
  669. class IncrementBy extends \Predis\InlineCommand {
  670. public function getCommandId() { return 'INCRBY'; }
  671. }
  672. class Decrement extends \Predis\InlineCommand {
  673. public function getCommandId() { return 'DECR'; }
  674. }
  675. class DecrementBy extends \Predis\InlineCommand {
  676. public function getCommandId() { return 'DECRBY'; }
  677. }
  678. class Exists extends \Predis\InlineCommand {
  679. public function getCommandId() { return 'EXISTS'; }
  680. public function parseResponse($data) { return (bool) $data; }
  681. }
  682. class Delete extends \Predis\InlineCommand {
  683. public function getCommandId() { return 'DEL'; }
  684. public function parseResponse($data) { return (bool) $data; }
  685. }
  686. class Type extends \Predis\InlineCommand {
  687. public function getCommandId() { return 'TYPE'; }
  688. }
  689. /* commands operating on the key space */
  690. class Keys extends \Predis\InlineCommand {
  691. public function canBeHashed() { return false; }
  692. public function getCommandId() { return 'KEYS'; }
  693. public function parseResponse($data) {
  694. // TODO: is this behaviour correct?
  695. return strlen($data) > 0 ? explode(' ', $data) : array();
  696. }
  697. }
  698. class RandomKey extends \Predis\InlineCommand {
  699. public function canBeHashed() { return false; }
  700. public function getCommandId() { return 'RANDOMKEY'; }
  701. public function parseResponse($data) { return $data !== '' ? $data : null; }
  702. }
  703. class Rename extends \Predis\InlineCommand {
  704. // TODO: doesn't RENAME break the hash-based client-side sharding?
  705. public function canBeHashed() { return false; }
  706. public function getCommandId() { return 'RENAME'; }
  707. }
  708. class RenamePreserve extends \Predis\InlineCommand {
  709. public function canBeHashed() { return false; }
  710. public function getCommandId() { return 'RENAMENX'; }
  711. public function parseResponse($data) { return (bool) $data; }
  712. }
  713. class Expire extends \Predis\InlineCommand {
  714. public function getCommandId() { return 'EXPIRE'; }
  715. public function parseResponse($data) { return (bool) $data; }
  716. }
  717. class ExpireAt extends \Predis\InlineCommand {
  718. public function getCommandId() { return 'EXPIREAT'; }
  719. public function parseResponse($data) { return (bool) $data; }
  720. }
  721. class DatabaseSize extends \Predis\InlineCommand {
  722. public function canBeHashed() { return false; }
  723. public function getCommandId() { return 'DBSIZE'; }
  724. }
  725. class TimeToLive extends \Predis\InlineCommand {
  726. public function getCommandId() { return 'TTL'; }
  727. }
  728. /* commands operating on lists */
  729. class ListPushTail extends \Predis\BulkCommand {
  730. public function getCommandId() { return 'RPUSH'; }
  731. }
  732. class ListPushHead extends \Predis\BulkCommand {
  733. public function getCommandId() { return 'LPUSH'; }
  734. }
  735. class ListLength extends \Predis\InlineCommand {
  736. public function getCommandId() { return 'LLEN'; }
  737. }
  738. class ListRange extends \Predis\InlineCommand {
  739. public function getCommandId() { return 'LRANGE'; }
  740. }
  741. class ListTrim extends \Predis\InlineCommand {
  742. public function getCommandId() { return 'LTRIM'; }
  743. }
  744. class ListIndex extends \Predis\InlineCommand {
  745. public function getCommandId() { return 'LINDEX'; }
  746. }
  747. class ListSet extends \Predis\BulkCommand {
  748. public function getCommandId() { return 'LSET'; }
  749. }
  750. class ListRemove extends \Predis\BulkCommand {
  751. public function getCommandId() { return 'LREM'; }
  752. }
  753. class ListPushTailPopFirst extends \Predis\BulkCommand {
  754. public function getCommandId() { return 'RPOPLPUSH'; }
  755. }
  756. class ListPopFirst extends \Predis\InlineCommand {
  757. public function getCommandId() { return 'LPOP'; }
  758. }
  759. class ListPopLast extends \Predis\InlineCommand {
  760. public function getCommandId() { return 'RPOP'; }
  761. }
  762. /* commands operating on sets */
  763. class SetAdd extends \Predis\BulkCommand {
  764. public function getCommandId() { return 'SADD'; }
  765. public function parseResponse($data) { return (bool) $data; }
  766. }
  767. class SetRemove extends \Predis\BulkCommand {
  768. public function getCommandId() { return 'SREM'; }
  769. public function parseResponse($data) { return (bool) $data; }
  770. }
  771. class SetPop extends \Predis\InlineCommand {
  772. public function getCommandId() { return 'SPOP'; }
  773. }
  774. class SetMove extends \Predis\BulkCommand {
  775. public function canBeHashed() { return false; }
  776. public function getCommandId() { return 'SMOVE'; }
  777. public function parseResponse($data) { return (bool) $data; }
  778. }
  779. class SetCardinality extends \Predis\InlineCommand {
  780. public function getCommandId() { return 'SCARD'; }
  781. }
  782. class SetIsMember extends \Predis\BulkCommand {
  783. public function getCommandId() { return 'SISMEMBER'; }
  784. public function parseResponse($data) { return (bool) $data; }
  785. }
  786. class SetIntersection extends \Predis\InlineCommand {
  787. public function getCommandId() { return 'SINTER'; }
  788. }
  789. class SetIntersectionStore extends \Predis\InlineCommand {
  790. public function getCommandId() { return 'SINTERSTORE'; }
  791. }
  792. class SetUnion extends \Predis\InlineCommand {
  793. public function getCommandId() { return 'SUNION'; }
  794. }
  795. class SetUnionStore extends \Predis\InlineCommand {
  796. public function getCommandId() { return 'SUNIONSTORE'; }
  797. }
  798. class SetDifference extends \Predis\InlineCommand {
  799. public function getCommandId() { return 'SDIFF'; }
  800. }
  801. class SetDifferenceStore extends \Predis\InlineCommand {
  802. public function getCommandId() { return 'SDIFFSTORE'; }
  803. }
  804. class SetMembers extends \Predis\InlineCommand {
  805. public function getCommandId() { return 'SMEMBERS'; }
  806. }
  807. class SetRandomMember extends \Predis\InlineCommand {
  808. public function getCommandId() { return 'SRANDMEMBER'; }
  809. }
  810. /* commands operating on sorted sets */
  811. class ZSetAdd extends \Predis\BulkCommand {
  812. public function getCommandId() { return 'ZADD'; }
  813. public function parseResponse($data) { return (bool) $data; }
  814. }
  815. class ZSetIncrementBy extends \Predis\BulkCommand {
  816. public function getCommandId() { return 'ZINCRBY'; }
  817. }
  818. class ZSetRemove extends \Predis\BulkCommand {
  819. public function getCommandId() { return 'ZREM'; }
  820. public function parseResponse($data) { return (bool) $data; }
  821. }
  822. class ZSetRange extends \Predis\InlineCommand {
  823. public function getCommandId() { return 'ZRANGE'; }
  824. }
  825. class ZSetReverseRange extends \Predis\InlineCommand {
  826. public function getCommandId() { return 'ZREVRANGE'; }
  827. }
  828. class ZSetRangeByScore extends \Predis\InlineCommand {
  829. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  830. }
  831. class ZSetCardinality extends \Predis\InlineCommand {
  832. public function getCommandId() { return 'ZCARD'; }
  833. }
  834. class ZSetScore extends \Predis\BulkCommand {
  835. public function getCommandId() { return 'ZSCORE'; }
  836. }
  837. class ZSetRemoveRangeByScore extends \Predis\InlineCommand {
  838. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  839. }
  840. /* multiple databases handling commands */
  841. class SelectDatabase extends \Predis\InlineCommand {
  842. public function canBeHashed() { return false; }
  843. public function getCommandId() { return 'SELECT'; }
  844. }
  845. class MoveKey extends \Predis\InlineCommand {
  846. public function canBeHashed() { return false; }
  847. public function getCommandId() { return 'MOVE'; }
  848. public function parseResponse($data) { return (bool) $data; }
  849. }
  850. class FlushDatabase extends \Predis\InlineCommand {
  851. public function canBeHashed() { return false; }
  852. public function getCommandId() { return 'FLUSHDB'; }
  853. }
  854. class FlushAll extends \Predis\InlineCommand {
  855. public function canBeHashed() { return false; }
  856. public function getCommandId() { return 'FLUSHALL'; }
  857. }
  858. /* sorting */
  859. class Sort extends \Predis\InlineCommand {
  860. public function getCommandId() { return 'SORT'; }
  861. public function filterArguments($arguments) {
  862. if (count($arguments) === 1) {
  863. return $arguments;
  864. }
  865. // TODO: add more parameters checks
  866. $query = array($arguments[0]);
  867. $sortParams = $arguments[1];
  868. if (isset($sortParams['by'])) {
  869. $query[] = 'BY ' . $sortParams['by'];
  870. }
  871. if (isset($sortParams['get'])) {
  872. $query[] = 'GET ' . $sortParams['get'];
  873. }
  874. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  875. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  876. }
  877. if (isset($sortParams['sort'])) {
  878. $query[] = strtoupper($sortParams['sort']);
  879. }
  880. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  881. $query[] = 'ALPHA';
  882. }
  883. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  884. $query[] = 'STORE ' . $sortParams['store'];
  885. }
  886. return $query;
  887. }
  888. }
  889. /* persistence control commands */
  890. class Save extends \Predis\InlineCommand {
  891. public function canBeHashed() { return false; }
  892. public function getCommandId() { return 'SAVE'; }
  893. }
  894. class BackgroundSave extends \Predis\InlineCommand {
  895. public function canBeHashed() { return false; }
  896. public function getCommandId() { return 'BGSAVE'; }
  897. }
  898. class LastSave extends \Predis\InlineCommand {
  899. public function canBeHashed() { return false; }
  900. public function getCommandId() { return 'LASTSAVE'; }
  901. }
  902. class Shutdown extends \Predis\InlineCommand {
  903. public function canBeHashed() { return false; }
  904. public function getCommandId() { return 'SHUTDOWN'; }
  905. public function closesConnection() { return true; }
  906. }
  907. /* remote server control commands */
  908. class Info extends \Predis\InlineCommand {
  909. public function canBeHashed() { return false; }
  910. public function getCommandId() { return 'INFO'; }
  911. public function parseResponse($data) {
  912. $info = array();
  913. $infoLines = explode("\r\n", $data, -1);
  914. foreach ($infoLines as $row) {
  915. list($k, $v) = explode(':', $row);
  916. if (!preg_match('/^db\d+$/', $k)) {
  917. $info[$k] = $v;
  918. }
  919. else {
  920. $db = array();
  921. foreach (explode(',', $v) as $dbvar) {
  922. list($dbvk, $dbvv) = explode('=', $dbvar);
  923. $db[trim($dbvk)] = $dbvv;
  924. }
  925. $info[$k] = $db;
  926. }
  927. }
  928. return $info;
  929. }
  930. }
  931. class SlaveOf extends \Predis\InlineCommand {
  932. public function canBeHashed() { return false; }
  933. public function getCommandId() { return 'SLAVEOF'; }
  934. public function filterArguments($arguments) {
  935. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  936. }
  937. }
  938. ?>