Predis.php 43 KB

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