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