Predis.php 43 KB

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