Predis.php 41 KB

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