Predis.php 43 KB

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