Predis.php 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  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. for ($i = 0; $i < $this->_replicas; $i++) {
  699. $key = crc32($nodeHash . ':' . $i);
  700. $this->_ring[$key] = $node;
  701. }
  702. ksort($this->_ring, SORT_NUMERIC);
  703. $this->_ringKeys = array_keys($this->_ring);
  704. }
  705. public function remove($node) {
  706. $nodeHash = (string) $node;
  707. for ($i = 0; $i < $this->_replicas; $i++) {
  708. $key = crc32($nodeHash . ':' . $i);
  709. unset($this->_ring[$key]);
  710. $this->_ringKeys = array_filter($this->_ringKeys, function($rk) use($key) {
  711. return $rk !== $key;
  712. });
  713. }
  714. }
  715. public function get($key) {
  716. return $this->_ring[$this->getNodeKey($key)];
  717. }
  718. private function getNodeKey($key) {
  719. $upper = count($this->_ringKeys) - 1;
  720. $lower = 0;
  721. $index = 0;
  722. while ($lower <= $upper) {
  723. $index = ($lower + $upper) / 2;
  724. $item = $this->_ringKeys[$index];
  725. if ($item === $key) {
  726. return $index;
  727. }
  728. else if ($item > $key) {
  729. $upper = $index - 1;
  730. }
  731. else {
  732. $lower = $index + 1;
  733. }
  734. }
  735. return $this->_ringKeys[$upper];
  736. }
  737. }
  738. /* ------------------------------------------------------------------------- */
  739. namespace Predis\Commands;
  740. /* miscellaneous commands */
  741. class Ping extends \Predis\InlineCommand {
  742. public function canBeHashed() { return false; }
  743. public function getCommandId() { return 'PING'; }
  744. public function parseResponse($data) {
  745. return $data === 'PONG' ? true : false;
  746. }
  747. }
  748. class DoEcho extends \Predis\BulkCommand {
  749. public function canBeHashed() { return false; }
  750. public function getCommandId() { return 'ECHO'; }
  751. }
  752. class Auth extends \Predis\InlineCommand {
  753. public function canBeHashed() { return false; }
  754. public function getCommandId() { return 'AUTH'; }
  755. }
  756. /* connection handling */
  757. class Quit extends \Predis\InlineCommand {
  758. public function canBeHashed() { return false; }
  759. public function getCommandId() { return 'QUIT'; }
  760. public function closesConnection() { return true; }
  761. }
  762. /* commands operating on string values */
  763. class Set extends \Predis\BulkCommand {
  764. public function getCommandId() { return 'SET'; }
  765. }
  766. class SetPreserve extends \Predis\BulkCommand {
  767. public function getCommandId() { return 'SETNX'; }
  768. public function parseResponse($data) { return (bool) $data; }
  769. }
  770. class SetMultiple extends \Predis\MultiBulkCommand {
  771. public function canBeHashed() { return false; }
  772. public function getCommandId() { return 'MSET'; }
  773. }
  774. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  775. public function canBeHashed() { return false; }
  776. public function getCommandId() { return 'MSETNX'; }
  777. public function parseResponse($data) { return (bool) $data; }
  778. }
  779. class Get extends \Predis\InlineCommand {
  780. public function getCommandId() { return 'GET'; }
  781. }
  782. class GetMultiple extends \Predis\InlineCommand {
  783. public function canBeHashed() { return false; }
  784. public function getCommandId() { return 'MGET'; }
  785. }
  786. class GetSet extends \Predis\BulkCommand {
  787. public function getCommandId() { return 'GETSET'; }
  788. }
  789. class Increment extends \Predis\InlineCommand {
  790. public function getCommandId() { return 'INCR'; }
  791. }
  792. class IncrementBy extends \Predis\InlineCommand {
  793. public function getCommandId() { return 'INCRBY'; }
  794. }
  795. class Decrement extends \Predis\InlineCommand {
  796. public function getCommandId() { return 'DECR'; }
  797. }
  798. class DecrementBy extends \Predis\InlineCommand {
  799. public function getCommandId() { return 'DECRBY'; }
  800. }
  801. class Exists extends \Predis\InlineCommand {
  802. public function getCommandId() { return 'EXISTS'; }
  803. public function parseResponse($data) { return (bool) $data; }
  804. }
  805. class Delete extends \Predis\InlineCommand {
  806. public function getCommandId() { return 'DEL'; }
  807. public function parseResponse($data) { return (bool) $data; }
  808. }
  809. class Type extends \Predis\InlineCommand {
  810. public function getCommandId() { return 'TYPE'; }
  811. }
  812. /* commands operating on the key space */
  813. class Keys extends \Predis\InlineCommand {
  814. public function canBeHashed() { return false; }
  815. public function getCommandId() { return 'KEYS'; }
  816. public function parseResponse($data) {
  817. // TODO: is this behaviour correct?
  818. return strlen($data) > 0 ? explode(' ', $data) : array();
  819. }
  820. }
  821. class RandomKey extends \Predis\InlineCommand {
  822. public function canBeHashed() { return false; }
  823. public function getCommandId() { return 'RANDOMKEY'; }
  824. public function parseResponse($data) { return $data !== '' ? $data : null; }
  825. }
  826. class Rename extends \Predis\InlineCommand {
  827. // TODO: doesn't RENAME break the hash-based client-side sharding?
  828. public function canBeHashed() { return false; }
  829. public function getCommandId() { return 'RENAME'; }
  830. }
  831. class RenamePreserve extends \Predis\InlineCommand {
  832. public function canBeHashed() { return false; }
  833. public function getCommandId() { return 'RENAMENX'; }
  834. public function parseResponse($data) { return (bool) $data; }
  835. }
  836. class Expire extends \Predis\InlineCommand {
  837. public function getCommandId() { return 'EXPIRE'; }
  838. public function parseResponse($data) { return (bool) $data; }
  839. }
  840. class ExpireAt extends \Predis\InlineCommand {
  841. public function getCommandId() { return 'EXPIREAT'; }
  842. public function parseResponse($data) { return (bool) $data; }
  843. }
  844. class DatabaseSize extends \Predis\InlineCommand {
  845. public function canBeHashed() { return false; }
  846. public function getCommandId() { return 'DBSIZE'; }
  847. }
  848. class TimeToLive extends \Predis\InlineCommand {
  849. public function getCommandId() { return 'TTL'; }
  850. }
  851. /* commands operating on lists */
  852. class ListPushTail extends \Predis\BulkCommand {
  853. public function getCommandId() { return 'RPUSH'; }
  854. }
  855. class ListPushHead extends \Predis\BulkCommand {
  856. public function getCommandId() { return 'LPUSH'; }
  857. }
  858. class ListLength extends \Predis\InlineCommand {
  859. public function getCommandId() { return 'LLEN'; }
  860. }
  861. class ListRange extends \Predis\InlineCommand {
  862. public function getCommandId() { return 'LRANGE'; }
  863. }
  864. class ListTrim extends \Predis\InlineCommand {
  865. public function getCommandId() { return 'LTRIM'; }
  866. }
  867. class ListIndex extends \Predis\InlineCommand {
  868. public function getCommandId() { return 'LINDEX'; }
  869. }
  870. class ListSet extends \Predis\BulkCommand {
  871. public function getCommandId() { return 'LSET'; }
  872. }
  873. class ListRemove extends \Predis\BulkCommand {
  874. public function getCommandId() { return 'LREM'; }
  875. }
  876. class ListPopLastPushHead extends \Predis\BulkCommand {
  877. public function getCommandId() { return 'RPOPLPUSH'; }
  878. }
  879. class ListPopFirst extends \Predis\InlineCommand {
  880. public function getCommandId() { return 'LPOP'; }
  881. }
  882. class ListPopLast extends \Predis\InlineCommand {
  883. public function getCommandId() { return 'RPOP'; }
  884. }
  885. /* commands operating on sets */
  886. class SetAdd extends \Predis\BulkCommand {
  887. public function getCommandId() { return 'SADD'; }
  888. public function parseResponse($data) { return (bool) $data; }
  889. }
  890. class SetRemove extends \Predis\BulkCommand {
  891. public function getCommandId() { return 'SREM'; }
  892. public function parseResponse($data) { return (bool) $data; }
  893. }
  894. class SetPop extends \Predis\InlineCommand {
  895. public function getCommandId() { return 'SPOP'; }
  896. }
  897. class SetMove extends \Predis\BulkCommand {
  898. public function canBeHashed() { return false; }
  899. public function getCommandId() { return 'SMOVE'; }
  900. public function parseResponse($data) { return (bool) $data; }
  901. }
  902. class SetCardinality extends \Predis\InlineCommand {
  903. public function getCommandId() { return 'SCARD'; }
  904. }
  905. class SetIsMember extends \Predis\BulkCommand {
  906. public function getCommandId() { return 'SISMEMBER'; }
  907. public function parseResponse($data) { return (bool) $data; }
  908. }
  909. class SetIntersection extends \Predis\InlineCommand {
  910. public function getCommandId() { return 'SINTER'; }
  911. }
  912. class SetIntersectionStore extends \Predis\InlineCommand {
  913. public function getCommandId() { return 'SINTERSTORE'; }
  914. }
  915. class SetUnion extends \Predis\InlineCommand {
  916. public function getCommandId() { return 'SUNION'; }
  917. }
  918. class SetUnionStore extends \Predis\InlineCommand {
  919. public function getCommandId() { return 'SUNIONSTORE'; }
  920. }
  921. class SetDifference extends \Predis\InlineCommand {
  922. public function getCommandId() { return 'SDIFF'; }
  923. }
  924. class SetDifferenceStore extends \Predis\InlineCommand {
  925. public function getCommandId() { return 'SDIFFSTORE'; }
  926. }
  927. class SetMembers extends \Predis\InlineCommand {
  928. public function getCommandId() { return 'SMEMBERS'; }
  929. }
  930. class SetRandomMember extends \Predis\InlineCommand {
  931. public function getCommandId() { return 'SRANDMEMBER'; }
  932. }
  933. /* commands operating on sorted sets */
  934. class ZSetAdd extends \Predis\BulkCommand {
  935. public function getCommandId() { return 'ZADD'; }
  936. public function parseResponse($data) { return (bool) $data; }
  937. }
  938. class ZSetRemove extends \Predis\BulkCommand {
  939. public function getCommandId() { return 'ZREM'; }
  940. public function parseResponse($data) { return (bool) $data; }
  941. }
  942. class ZSetRange extends \Predis\InlineCommand {
  943. public function getCommandId() { return 'ZRANGE'; }
  944. }
  945. class ZSetReverseRange extends \Predis\InlineCommand {
  946. public function getCommandId() { return 'ZREVRANGE'; }
  947. }
  948. class ZSetRangeByScore extends \Predis\InlineCommand {
  949. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  950. }
  951. class ZSetCardinality extends \Predis\InlineCommand {
  952. public function getCommandId() { return 'ZCARD'; }
  953. }
  954. class ZSetScore extends \Predis\BulkCommand {
  955. public function getCommandId() { return 'ZSCORE'; }
  956. }
  957. class ZSetRemoveRangeByScore extends \Predis\InlineCommand {
  958. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  959. }
  960. /* multiple databases handling commands */
  961. class SelectDatabase extends \Predis\InlineCommand {
  962. public function canBeHashed() { return false; }
  963. public function getCommandId() { return 'SELECT'; }
  964. }
  965. class MoveKey extends \Predis\InlineCommand {
  966. public function canBeHashed() { return false; }
  967. public function getCommandId() { return 'MOVE'; }
  968. public function parseResponse($data) { return (bool) $data; }
  969. }
  970. class FlushDatabase extends \Predis\InlineCommand {
  971. public function canBeHashed() { return false; }
  972. public function getCommandId() { return 'FLUSHDB'; }
  973. }
  974. class FlushAll extends \Predis\InlineCommand {
  975. public function canBeHashed() { return false; }
  976. public function getCommandId() { return 'FLUSHALL'; }
  977. }
  978. /* sorting */
  979. class Sort extends \Predis\InlineCommand {
  980. public function getCommandId() { return 'SORT'; }
  981. public function filterArguments($arguments) {
  982. if (count($arguments) === 1) {
  983. return $arguments;
  984. }
  985. // TODO: add more parameters checks
  986. $query = array($arguments[0]);
  987. $sortParams = $arguments[1];
  988. if (isset($sortParams['by'])) {
  989. $query[] = 'BY ' . $sortParams['by'];
  990. }
  991. if (isset($sortParams['get'])) {
  992. $query[] = 'GET ' . $sortParams['get'];
  993. }
  994. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  995. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  996. }
  997. if (isset($sortParams['sort'])) {
  998. $query[] = strtoupper($sortParams['sort']);
  999. }
  1000. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  1001. $query[] = 'ALPHA';
  1002. }
  1003. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  1004. $query[] = 'STORE ' . $sortParams['store'];
  1005. }
  1006. return $query;
  1007. }
  1008. }
  1009. /* persistence control commands */
  1010. class Save extends \Predis\InlineCommand {
  1011. public function canBeHashed() { return false; }
  1012. public function getCommandId() { return 'SAVE'; }
  1013. }
  1014. class BackgroundSave extends \Predis\InlineCommand {
  1015. public function canBeHashed() { return false; }
  1016. public function getCommandId() { return 'BGSAVE'; }
  1017. }
  1018. class LastSave extends \Predis\InlineCommand {
  1019. public function canBeHashed() { return false; }
  1020. public function getCommandId() { return 'LASTSAVE'; }
  1021. }
  1022. class Shutdown extends \Predis\InlineCommand {
  1023. public function canBeHashed() { return false; }
  1024. public function getCommandId() { return 'SHUTDOWN'; }
  1025. public function closesConnection() { return true; }
  1026. }
  1027. /* remote server control commands */
  1028. class Info extends \Predis\InlineCommand {
  1029. public function canBeHashed() { return false; }
  1030. public function getCommandId() { return 'INFO'; }
  1031. public function parseResponse($data) {
  1032. $info = array();
  1033. $infoLines = explode("\r\n", $data, -1);
  1034. foreach ($infoLines as $row) {
  1035. list($k, $v) = explode(':', $row);
  1036. if (!preg_match('/^db\d+$/', $k)) {
  1037. $info[$k] = $v;
  1038. }
  1039. else {
  1040. $db = array();
  1041. foreach (explode(',', $v) as $dbvar) {
  1042. list($dbvk, $dbvv) = explode('=', $dbvar);
  1043. $db[trim($dbvk)] = $dbvv;
  1044. }
  1045. $info[$k] = $db;
  1046. }
  1047. }
  1048. return $info;
  1049. }
  1050. }
  1051. class SlaveOf extends \Predis\InlineCommand {
  1052. public function canBeHashed() { return false; }
  1053. public function getCommandId() { return 'SLAVEOF'; }
  1054. public function filterArguments($arguments) {
  1055. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1056. }
  1057. }
  1058. ?>