Predis.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  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. $details = array();
  472. foreach (explode('&', $parsed['query']) as $kv) {
  473. list($k, $v) = explode('=', $kv);
  474. switch ($k) {
  475. case 'database':
  476. $details['database'] = $v;
  477. break;
  478. case 'password':
  479. $details['password'] = $v;
  480. break;
  481. }
  482. }
  483. return self::filterConnectionParams(array_merge($parsed, $details));
  484. }
  485. private static function filterConnectionParams($parameters) {
  486. return array(
  487. 'host' => $parameters['host'] != null
  488. ? $parameters['host']
  489. : Connection::DEFAULT_HOST,
  490. 'port' => $parameters['port'] != null
  491. ? (int) $parameters['port']
  492. : Connection::DEFAULT_PORT,
  493. 'database' => $parameters['database'],
  494. 'password' => $parameters['password'],
  495. );
  496. }
  497. public function __get($parameter) {
  498. return $this->_parameters[$parameter];
  499. }
  500. }
  501. interface IConnection {
  502. public function connect();
  503. public function disconnect();
  504. public function isConnected();
  505. public function writeCommand(Command $command);
  506. public function readResponse(Command $command);
  507. }
  508. class Connection implements IConnection {
  509. const DEFAULT_HOST = '127.0.0.1';
  510. const DEFAULT_PORT = 6379;
  511. const CONNECTION_TIMEOUT = 2;
  512. const READ_WRITE_TIMEOUT = 5;
  513. private $_params, $_socket, $_initCmds;
  514. public function __construct(ConnectionParameters $parameters) {
  515. $this->_params = $parameters;
  516. $this->_initCmds = array();
  517. }
  518. public function __destruct() {
  519. $this->disconnect();
  520. }
  521. public function isConnected() {
  522. return is_resource($this->_socket);
  523. }
  524. public function connect() {
  525. if ($this->isConnected()) {
  526. throw new ClientException('Connection already estabilished');
  527. }
  528. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  529. $this->_socket = @stream_socket_client($uri, $errno, $errstr, self::CONNECTION_TIMEOUT);
  530. if (!$this->_socket) {
  531. throw new ClientException(trim($errstr), $errno);
  532. }
  533. stream_set_timeout($this->_socket, self::READ_WRITE_TIMEOUT);
  534. if (count($this->_initCmds) > 0){
  535. $this->sendInitializationCommands();
  536. }
  537. }
  538. public function disconnect() {
  539. if ($this->isConnected()) {
  540. fclose($this->_socket);
  541. }
  542. }
  543. public function pushInitCommand(Command $command){
  544. $this->_initCmds[] = $command;
  545. }
  546. private function sendInitializationCommands() {
  547. foreach ($this->_initCmds as $command) {
  548. $this->writeCommand($command);
  549. }
  550. foreach ($this->_initCmds as $command) {
  551. $this->readResponse($command);
  552. }
  553. }
  554. public function writeCommand(Command $command) {
  555. fwrite($this->getSocket(), $command());
  556. }
  557. public function readResponse(Command $command) {
  558. $socket = $this->getSocket();
  559. $handler = Response::getPrefixHandler(fgetc($socket));
  560. $response = $command->parseResponse($handler($socket));
  561. return $response;
  562. }
  563. public function rawCommand($rawCommandData, $closesConnection = false) {
  564. $socket = $this->getSocket();
  565. fwrite($socket, $rawCommandData);
  566. if ($closesConnection) {
  567. return;
  568. }
  569. $handler = Response::getPrefixHandler(fgetc($socket));
  570. return $handler($socket);
  571. }
  572. public function getSocket() {
  573. if (!$this->isConnected()) {
  574. $this->connect();
  575. }
  576. return $this->_socket;
  577. }
  578. public function __toString() {
  579. return sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  580. }
  581. }
  582. class ConnectionCluster implements IConnection {
  583. // TODO: storing a temporary map of commands hashes to hashring items (that
  584. // is, connections) could offer a notable speedup, but I am wondering
  585. // about the increased memory footprint.
  586. // TODO: find a clean way to handle connection failures of single nodes.
  587. private $_pool, $_ring;
  588. public function __construct() {
  589. $this->_pool = array();
  590. $this->_ring = new Utilities\HashRing();
  591. }
  592. public function __destruct() {
  593. $this->disconnect();
  594. }
  595. public function isConnected() {
  596. foreach ($this->_pool as $connection) {
  597. if ($connection->isConnected()) {
  598. return true;
  599. }
  600. }
  601. return false;
  602. }
  603. public function connect() {
  604. foreach ($this->_pool as $connection) {
  605. $connection->connect();
  606. }
  607. }
  608. public function disconnect() {
  609. foreach ($this->_pool as $connection) {
  610. $connection->disconnect();
  611. }
  612. }
  613. public function add(Connection $connection) {
  614. $this->_pool[] = $connection;
  615. $this->_ring->add($connection);
  616. }
  617. private function getConnectionFromRing(Command $command) {
  618. return $this->_ring->get($this->computeHash($command));
  619. }
  620. private function computeHash(Command $command) {
  621. return crc32($command->getArgument(0));
  622. }
  623. private function getConnection(Command $command) {
  624. return $command->canBeHashed()
  625. ? $this->getConnectionFromRing($command)
  626. : $this->getConnectionById(0);
  627. }
  628. public function getConnectionById($id = null) {
  629. return $this->_pool[$id === null ? 0 : $id];
  630. }
  631. public function writeCommand(Command $command) {
  632. $this->getConnection($command)->writeCommand($command);
  633. }
  634. public function readResponse(Command $command) {
  635. return $this->getConnection($command)->readResponse($command);
  636. }
  637. }
  638. /* ------------------------------------------------------------------------- */
  639. namespace Predis\Utilities;
  640. class HashRing {
  641. const NUMBER_OF_REPLICAS = 64;
  642. private $_ring, $_ringKeys;
  643. public function __construct() {
  644. $this->_ring = array();
  645. $this->_ringKeys = array();
  646. }
  647. public function add($node) {
  648. for ($i = 0; $i < self::NUMBER_OF_REPLICAS; $i++) {
  649. $key = crc32((string)$node . ':' . $i);
  650. $this->_ring[$key] = $node;
  651. }
  652. ksort($this->_ring, SORT_NUMERIC);
  653. $this->_ringKeys = array_keys($this->_ring);
  654. }
  655. public function remove($node) {
  656. for ($i = 0; $i < self::NUMBER_OF_REPLICAS; $i++) {
  657. $key = crc32((string)$node . '_' . $i);
  658. unset($this->_ring[$key]);
  659. $this->_ringKeys = array_filter($this->_ringKeys, function($rk) use($key) {
  660. return $rk !== $key;
  661. });
  662. }
  663. }
  664. public function get($key) {
  665. return $this->_ring[$this->getNodeKey($key)];
  666. }
  667. private function getNodeKey($key) {
  668. $upper = count($this->_ringKeys) - 1;
  669. $lower = 0;
  670. $index = 0;
  671. while ($lower <= $upper) {
  672. $index = ($lower + $upper) / 2;
  673. $item = $this->_ringKeys[$index];
  674. if ($item === $key) {
  675. return $index;
  676. }
  677. else if ($item > $key) {
  678. $upper = $index - 1;
  679. }
  680. else {
  681. $lower = $index + 1;
  682. }
  683. }
  684. return $this->_ringKeys[$upper];
  685. }
  686. }
  687. /* ------------------------------------------------------------------------- */
  688. namespace Predis\Commands;
  689. /* miscellaneous commands */
  690. class Ping extends \Predis\InlineCommand {
  691. public function canBeHashed() { return false; }
  692. public function getCommandId() { return 'PING'; }
  693. public function parseResponse($data) {
  694. return $data === 'PONG' ? true : false;
  695. }
  696. }
  697. class DoEcho extends \Predis\BulkCommand {
  698. public function canBeHashed() { return false; }
  699. public function getCommandId() { return 'ECHO'; }
  700. }
  701. class Auth extends \Predis\InlineCommand {
  702. public function canBeHashed() { return false; }
  703. public function getCommandId() { return 'AUTH'; }
  704. }
  705. /* connection handling */
  706. class Quit extends \Predis\InlineCommand {
  707. public function canBeHashed() { return false; }
  708. public function getCommandId() { return 'QUIT'; }
  709. public function closesConnection() { return true; }
  710. }
  711. /* commands operating on string values */
  712. class Set extends \Predis\BulkCommand {
  713. public function getCommandId() { return 'SET'; }
  714. }
  715. class SetPreserve extends \Predis\BulkCommand {
  716. public function getCommandId() { return 'SETNX'; }
  717. public function parseResponse($data) { return (bool) $data; }
  718. }
  719. class SetMultiple extends \Predis\MultiBulkCommand {
  720. public function canBeHashed() { return false; }
  721. public function getCommandId() { return 'MSET'; }
  722. }
  723. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  724. public function canBeHashed() { return false; }
  725. public function getCommandId() { return 'MSETNX'; }
  726. public function parseResponse($data) { return (bool) $data; }
  727. }
  728. class Get extends \Predis\InlineCommand {
  729. public function getCommandId() { return 'GET'; }
  730. }
  731. class GetMultiple extends \Predis\InlineCommand {
  732. public function canBeHashed() { return false; }
  733. public function getCommandId() { return 'MGET'; }
  734. }
  735. class GetSet extends \Predis\BulkCommand {
  736. public function getCommandId() { return 'GETSET'; }
  737. }
  738. class Increment extends \Predis\InlineCommand {
  739. public function getCommandId() { return 'INCR'; }
  740. }
  741. class IncrementBy extends \Predis\InlineCommand {
  742. public function getCommandId() { return 'INCRBY'; }
  743. }
  744. class Decrement extends \Predis\InlineCommand {
  745. public function getCommandId() { return 'DECR'; }
  746. }
  747. class DecrementBy extends \Predis\InlineCommand {
  748. public function getCommandId() { return 'DECRBY'; }
  749. }
  750. class Exists extends \Predis\InlineCommand {
  751. public function getCommandId() { return 'EXISTS'; }
  752. public function parseResponse($data) { return (bool) $data; }
  753. }
  754. class Delete extends \Predis\InlineCommand {
  755. public function getCommandId() { return 'DEL'; }
  756. public function parseResponse($data) { return (bool) $data; }
  757. }
  758. class Type extends \Predis\InlineCommand {
  759. public function getCommandId() { return 'TYPE'; }
  760. }
  761. /* commands operating on the key space */
  762. class Keys extends \Predis\InlineCommand {
  763. public function canBeHashed() { return false; }
  764. public function getCommandId() { return 'KEYS'; }
  765. public function parseResponse($data) {
  766. // TODO: is this behaviour correct?
  767. return strlen($data) > 0 ? explode(' ', $data) : array();
  768. }
  769. }
  770. class RandomKey extends \Predis\InlineCommand {
  771. public function canBeHashed() { return false; }
  772. public function getCommandId() { return 'RANDOMKEY'; }
  773. public function parseResponse($data) { return $data !== '' ? $data : null; }
  774. }
  775. class Rename extends \Predis\InlineCommand {
  776. // TODO: doesn't RENAME break the hash-based client-side sharding?
  777. public function canBeHashed() { return false; }
  778. public function getCommandId() { return 'RENAME'; }
  779. }
  780. class RenamePreserve extends \Predis\InlineCommand {
  781. public function canBeHashed() { return false; }
  782. public function getCommandId() { return 'RENAMENX'; }
  783. public function parseResponse($data) { return (bool) $data; }
  784. }
  785. class Expire extends \Predis\InlineCommand {
  786. public function getCommandId() { return 'EXPIRE'; }
  787. public function parseResponse($data) { return (bool) $data; }
  788. }
  789. class ExpireAt extends \Predis\InlineCommand {
  790. public function getCommandId() { return 'EXPIREAT'; }
  791. public function parseResponse($data) { return (bool) $data; }
  792. }
  793. class DatabaseSize extends \Predis\InlineCommand {
  794. public function canBeHashed() { return false; }
  795. public function getCommandId() { return 'DBSIZE'; }
  796. }
  797. class TimeToLive extends \Predis\InlineCommand {
  798. public function getCommandId() { return 'TTL'; }
  799. }
  800. /* commands operating on lists */
  801. class ListPushTail extends \Predis\BulkCommand {
  802. public function getCommandId() { return 'RPUSH'; }
  803. }
  804. class ListPushHead extends \Predis\BulkCommand {
  805. public function getCommandId() { return 'LPUSH'; }
  806. }
  807. class ListLength extends \Predis\InlineCommand {
  808. public function getCommandId() { return 'LLEN'; }
  809. }
  810. class ListRange extends \Predis\InlineCommand {
  811. public function getCommandId() { return 'LRANGE'; }
  812. }
  813. class ListTrim extends \Predis\InlineCommand {
  814. public function getCommandId() { return 'LTRIM'; }
  815. }
  816. class ListIndex extends \Predis\InlineCommand {
  817. public function getCommandId() { return 'LINDEX'; }
  818. }
  819. class ListSet extends \Predis\BulkCommand {
  820. public function getCommandId() { return 'LSET'; }
  821. }
  822. class ListRemove extends \Predis\BulkCommand {
  823. public function getCommandId() { return 'LREM'; }
  824. }
  825. class ListPopFirst extends \Predis\InlineCommand {
  826. public function getCommandId() { return 'LPOP'; }
  827. }
  828. class ListPopLast extends \Predis\InlineCommand {
  829. public function getCommandId() { return 'RPOP'; }
  830. }
  831. /* commands operating on sets */
  832. class SetAdd extends \Predis\BulkCommand {
  833. public function getCommandId() { return 'SADD'; }
  834. public function parseResponse($data) { return (bool) $data; }
  835. }
  836. class SetRemove extends \Predis\BulkCommand {
  837. public function getCommandId() { return 'SREM'; }
  838. public function parseResponse($data) { return (bool) $data; }
  839. }
  840. class SetPop extends \Predis\InlineCommand {
  841. public function getCommandId() { return 'SPOP'; }
  842. }
  843. class SetMove extends \Predis\BulkCommand {
  844. public function canBeHashed() { return false; }
  845. public function getCommandId() { return 'SMOVE'; }
  846. public function parseResponse($data) { return (bool) $data; }
  847. }
  848. class SetCardinality extends \Predis\InlineCommand {
  849. public function getCommandId() { return 'SCARD'; }
  850. }
  851. class SetIsMember extends \Predis\BulkCommand {
  852. public function getCommandId() { return 'SISMEMBER'; }
  853. public function parseResponse($data) { return (bool) $data; }
  854. }
  855. class SetIntersection extends \Predis\InlineCommand {
  856. public function getCommandId() { return 'SINTER'; }
  857. }
  858. class SetIntersectionStore extends \Predis\InlineCommand {
  859. public function getCommandId() { return 'SINTERSTORE'; }
  860. }
  861. class SetUnion extends \Predis\InlineCommand {
  862. public function getCommandId() { return 'SUNION'; }
  863. }
  864. class SetUnionStore extends \Predis\InlineCommand {
  865. public function getCommandId() { return 'SUNIONSTORE'; }
  866. }
  867. class SetDifference extends \Predis\InlineCommand {
  868. public function getCommandId() { return 'SDIFF'; }
  869. }
  870. class SetDifferenceStore extends \Predis\InlineCommand {
  871. public function getCommandId() { return 'SDIFFSTORE'; }
  872. }
  873. class SetMembers extends \Predis\InlineCommand {
  874. public function getCommandId() { return 'SMEMBERS'; }
  875. }
  876. class SetRandomMember extends \Predis\InlineCommand {
  877. public function getCommandId() { return 'SRANDMEMBER'; }
  878. }
  879. /* commands operating on sorted sets */
  880. class ZSetAdd extends \Predis\BulkCommand {
  881. public function getCommandId() { return 'ZADD'; }
  882. public function parseResponse($data) { return (bool) $data; }
  883. }
  884. class ZSetRemove extends \Predis\BulkCommand {
  885. public function getCommandId() { return 'ZREM'; }
  886. public function parseResponse($data) { return (bool) $data; }
  887. }
  888. class ZSetRange extends \Predis\InlineCommand {
  889. public function getCommandId() { return 'ZRANGE'; }
  890. }
  891. class ZSetReverseRange extends \Predis\InlineCommand {
  892. public function getCommandId() { return 'ZREVRANGE'; }
  893. }
  894. class ZSetRangeByScore extends \Predis\InlineCommand {
  895. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  896. }
  897. class ZSetCardinality extends \Predis\InlineCommand {
  898. public function getCommandId() { return 'ZCARD'; }
  899. }
  900. class ZSetScore extends \Predis\BulkCommand {
  901. public function getCommandId() { return 'ZSCORE'; }
  902. }
  903. class ZSetRemoveRangeByScore extends \Predis\InlineCommand {
  904. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  905. }
  906. /* multiple databases handling commands */
  907. class SelectDatabase extends \Predis\InlineCommand {
  908. public function canBeHashed() { return false; }
  909. public function getCommandId() { return 'SELECT'; }
  910. }
  911. class MoveKey extends \Predis\InlineCommand {
  912. public function canBeHashed() { return false; }
  913. public function getCommandId() { return 'MOVE'; }
  914. public function parseResponse($data) { return (bool) $data; }
  915. }
  916. class FlushDatabase extends \Predis\InlineCommand {
  917. public function canBeHashed() { return false; }
  918. public function getCommandId() { return 'FLUSHDB'; }
  919. }
  920. class FlushAll extends \Predis\InlineCommand {
  921. public function canBeHashed() { return false; }
  922. public function getCommandId() { return 'FLUSHALL'; }
  923. }
  924. /* sorting */
  925. class Sort extends \Predis\InlineCommand {
  926. public function getCommandId() { return 'SORT'; }
  927. public function filterArguments($arguments) {
  928. if (count($arguments) === 1) {
  929. return $arguments;
  930. }
  931. // TODO: add more parameters checks
  932. $query = array($arguments[0]);
  933. $sortParams = $arguments[1];
  934. if (isset($sortParams['by'])) {
  935. $query[] = 'BY ' . $sortParams['by'];
  936. }
  937. if (isset($sortParams['get'])) {
  938. $query[] = 'GET ' . $sortParams['get'];
  939. }
  940. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  941. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  942. }
  943. if (isset($sortParams['sort'])) {
  944. $query[] = strtoupper($sortParams['sort']);
  945. }
  946. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  947. $query[] = 'ALPHA';
  948. }
  949. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  950. $query[] = 'STORE ' . $sortParams['store'];
  951. }
  952. return $query;
  953. }
  954. }
  955. /* persistence control commands */
  956. class Save extends \Predis\InlineCommand {
  957. public function canBeHashed() { return false; }
  958. public function getCommandId() { return 'SAVE'; }
  959. }
  960. class BackgroundSave extends \Predis\InlineCommand {
  961. public function canBeHashed() { return false; }
  962. public function getCommandId() { return 'BGSAVE'; }
  963. }
  964. class LastSave extends \Predis\InlineCommand {
  965. public function canBeHashed() { return false; }
  966. public function getCommandId() { return 'LASTSAVE'; }
  967. }
  968. class Shutdown extends \Predis\InlineCommand {
  969. public function canBeHashed() { return false; }
  970. public function getCommandId() { return 'SHUTDOWN'; }
  971. public function closesConnection() { return true; }
  972. }
  973. /* remote server control commands */
  974. class Info extends \Predis\InlineCommand {
  975. public function canBeHashed() { return false; }
  976. public function getCommandId() { return 'INFO'; }
  977. public function parseResponse($data) {
  978. $info = array();
  979. $infoLines = explode("\r\n", $data, -1);
  980. foreach ($infoLines as $row) {
  981. list($k, $v) = explode(':', $row);
  982. $info[$k] = $v;
  983. }
  984. return $info;
  985. }
  986. }
  987. class SlaveOf extends \Predis\InlineCommand {
  988. public function canBeHashed() { return false; }
  989. public function getCommandId() { return 'SLAVEOF'; }
  990. public function filterArguments($arguments) {
  991. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  992. }
  993. }
  994. ?>