Predis.php 41 KB

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