Predis.php 41 KB

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