Predis.php 43 KB

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