Predis.php 38 KB

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