Predis.php 45 KB

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