Predis.php 41 KB

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