Predis.php 42 KB

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