]> git.saurik.com Git - redis.git/blob - redis-cli.c
d6520bf906dea223902354943a25afe9597b1cc0
[redis.git] / redis-cli.c
1 /* Redis CLI (command line interface)
2 *
3 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
9 * * Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * * Neither the name of Redis nor the names of its contributors may be used
15 * to endorse or promote products derived from this software without
16 * specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 #include "fmacros.h"
32
33 #include <stdio.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <unistd.h>
37 #include <ctype.h>
38
39 #include "anet.h"
40 #include "sds.h"
41 #include "adlist.h"
42 #include "zmalloc.h"
43 #include "linenoise.h"
44
45 #define REDIS_CMD_INLINE 1
46 #define REDIS_CMD_BULK 2
47 #define REDIS_CMD_MULTIBULK 4
48
49 #define REDIS_NOTUSED(V) ((void) V)
50
51 static struct config {
52 char *hostip;
53 int hostport;
54 long repeat;
55 int dbnum;
56 int interactive;
57 int monitor_mode;
58 int pubsub_mode;
59 char *auth;
60 } config;
61
62 struct redisCommand {
63 char *name;
64 int arity;
65 int flags;
66 };
67
68 static struct redisCommand cmdTable[] = {
69 {"auth",2,REDIS_CMD_INLINE},
70 {"get",2,REDIS_CMD_INLINE},
71 {"set",3,REDIS_CMD_BULK},
72 {"setnx",3,REDIS_CMD_BULK},
73 {"setex",4,REDIS_CMD_BULK},
74 {"append",3,REDIS_CMD_BULK},
75 {"substr",4,REDIS_CMD_INLINE},
76 {"del",-2,REDIS_CMD_INLINE},
77 {"exists",2,REDIS_CMD_INLINE},
78 {"incr",2,REDIS_CMD_INLINE},
79 {"decr",2,REDIS_CMD_INLINE},
80 {"rpush",3,REDIS_CMD_BULK},
81 {"lpush",3,REDIS_CMD_BULK},
82 {"rpop",2,REDIS_CMD_INLINE},
83 {"lpop",2,REDIS_CMD_INLINE},
84 {"brpop",-3,REDIS_CMD_INLINE},
85 {"blpop",-3,REDIS_CMD_INLINE},
86 {"llen",2,REDIS_CMD_INLINE},
87 {"lindex",3,REDIS_CMD_INLINE},
88 {"lset",4,REDIS_CMD_BULK},
89 {"lrange",4,REDIS_CMD_INLINE},
90 {"ltrim",4,REDIS_CMD_INLINE},
91 {"lrem",4,REDIS_CMD_BULK},
92 {"rpoplpush",3,REDIS_CMD_BULK},
93 {"sadd",3,REDIS_CMD_BULK},
94 {"srem",3,REDIS_CMD_BULK},
95 {"smove",4,REDIS_CMD_BULK},
96 {"sismember",3,REDIS_CMD_BULK},
97 {"scard",2,REDIS_CMD_INLINE},
98 {"spop",2,REDIS_CMD_INLINE},
99 {"srandmember",2,REDIS_CMD_INLINE},
100 {"sinter",-2,REDIS_CMD_INLINE},
101 {"sinterstore",-3,REDIS_CMD_INLINE},
102 {"sunion",-2,REDIS_CMD_INLINE},
103 {"sunionstore",-3,REDIS_CMD_INLINE},
104 {"sdiff",-2,REDIS_CMD_INLINE},
105 {"sdiffstore",-3,REDIS_CMD_INLINE},
106 {"smembers",2,REDIS_CMD_INLINE},
107 {"zadd",4,REDIS_CMD_BULK},
108 {"zincrby",4,REDIS_CMD_BULK},
109 {"zrem",3,REDIS_CMD_BULK},
110 {"zremrangebyscore",4,REDIS_CMD_INLINE},
111 {"zmerge",-3,REDIS_CMD_INLINE},
112 {"zmergeweighed",-4,REDIS_CMD_INLINE},
113 {"zrange",-4,REDIS_CMD_INLINE},
114 {"zrank",3,REDIS_CMD_BULK},
115 {"zrevrank",3,REDIS_CMD_BULK},
116 {"zrangebyscore",-4,REDIS_CMD_INLINE},
117 {"zcount",4,REDIS_CMD_INLINE},
118 {"zrevrange",-4,REDIS_CMD_INLINE},
119 {"zcard",2,REDIS_CMD_INLINE},
120 {"zscore",3,REDIS_CMD_BULK},
121 {"incrby",3,REDIS_CMD_INLINE},
122 {"decrby",3,REDIS_CMD_INLINE},
123 {"getset",3,REDIS_CMD_BULK},
124 {"randomkey",1,REDIS_CMD_INLINE},
125 {"select",2,REDIS_CMD_INLINE},
126 {"move",3,REDIS_CMD_INLINE},
127 {"rename",3,REDIS_CMD_INLINE},
128 {"renamenx",3,REDIS_CMD_INLINE},
129 {"keys",2,REDIS_CMD_INLINE},
130 {"dbsize",1,REDIS_CMD_INLINE},
131 {"ping",1,REDIS_CMD_INLINE},
132 {"echo",2,REDIS_CMD_BULK},
133 {"save",1,REDIS_CMD_INLINE},
134 {"bgsave",1,REDIS_CMD_INLINE},
135 {"rewriteaof",1,REDIS_CMD_INLINE},
136 {"bgrewriteaof",1,REDIS_CMD_INLINE},
137 {"shutdown",1,REDIS_CMD_INLINE},
138 {"lastsave",1,REDIS_CMD_INLINE},
139 {"type",2,REDIS_CMD_INLINE},
140 {"flushdb",1,REDIS_CMD_INLINE},
141 {"flushall",1,REDIS_CMD_INLINE},
142 {"sort",-2,REDIS_CMD_INLINE},
143 {"info",1,REDIS_CMD_INLINE},
144 {"mget",-2,REDIS_CMD_INLINE},
145 {"expire",3,REDIS_CMD_INLINE},
146 {"expireat",3,REDIS_CMD_INLINE},
147 {"ttl",2,REDIS_CMD_INLINE},
148 {"slaveof",3,REDIS_CMD_INLINE},
149 {"debug",-2,REDIS_CMD_INLINE},
150 {"mset",-3,REDIS_CMD_MULTIBULK},
151 {"msetnx",-3,REDIS_CMD_MULTIBULK},
152 {"monitor",1,REDIS_CMD_INLINE},
153 {"multi",1,REDIS_CMD_INLINE},
154 {"exec",1,REDIS_CMD_INLINE},
155 {"discard",1,REDIS_CMD_INLINE},
156 {"hset",4,REDIS_CMD_MULTIBULK},
157 {"hget",3,REDIS_CMD_BULK},
158 {"hmset",-4,REDIS_CMD_MULTIBULK},
159 {"hmget",-3,REDIS_CMD_MULTIBULK},
160 {"hincrby",4,REDIS_CMD_INLINE},
161 {"hdel",3,REDIS_CMD_BULK},
162 {"hlen",2,REDIS_CMD_INLINE},
163 {"hkeys",2,REDIS_CMD_INLINE},
164 {"hvals",2,REDIS_CMD_INLINE},
165 {"hgetall",2,REDIS_CMD_INLINE},
166 {"hexists",3,REDIS_CMD_BULK},
167 {"config",-2,REDIS_CMD_BULK},
168 {"subscribe",-2,REDIS_CMD_INLINE},
169 {"unsubscribe",-1,REDIS_CMD_INLINE},
170 {"psubscribe",-2,REDIS_CMD_INLINE},
171 {"punsubscribe",-1,REDIS_CMD_INLINE},
172 {"publish",3,REDIS_CMD_BULK},
173 {NULL,0,0}
174 };
175
176 static int cliReadReply(int fd);
177 static void usage();
178
179 static struct redisCommand *lookupCommand(char *name) {
180 int j = 0;
181 while(cmdTable[j].name != NULL) {
182 if (!strcasecmp(name,cmdTable[j].name)) return &cmdTable[j];
183 j++;
184 }
185 return NULL;
186 }
187
188 static int cliConnect(void) {
189 char err[ANET_ERR_LEN];
190 static int fd = ANET_ERR;
191
192 if (fd == ANET_ERR) {
193 fd = anetTcpConnect(err,config.hostip,config.hostport);
194 if (fd == ANET_ERR) {
195 fprintf(stderr, "Could not connect to Redis at %s:%d: %s", config.hostip, config.hostport, err);
196 return -1;
197 }
198 anetTcpNoDelay(NULL,fd);
199 }
200 return fd;
201 }
202
203 static sds cliReadLine(int fd) {
204 sds line = sdsempty();
205
206 while(1) {
207 char c;
208 ssize_t ret;
209
210 ret = read(fd,&c,1);
211 if (ret == -1) {
212 sdsfree(line);
213 return NULL;
214 } else if ((ret == 0) || (c == '\n')) {
215 break;
216 } else {
217 line = sdscatlen(line,&c,1);
218 }
219 }
220 return sdstrim(line,"\r\n");
221 }
222
223 static int cliReadSingleLineReply(int fd, int quiet) {
224 sds reply = cliReadLine(fd);
225
226 if (reply == NULL) return 1;
227 if (!quiet)
228 printf("%s\n", reply);
229 sdsfree(reply);
230 return 0;
231 }
232
233 static void printStringRepr(char *s, int len) {
234 printf("\"");
235 while(len--) {
236 switch(*s) {
237 case '\\':
238 case '"':
239 printf("\\%c",*s);
240 break;
241 case '\n': printf("\\n"); break;
242 case '\r': printf("\\r"); break;
243 case '\t': printf("\\t"); break;
244 case '\a': printf("\\a"); break;
245 case '\b': printf("\\b"); break;
246 default:
247 if (isprint(*s))
248 printf("%c",*s);
249 else
250 printf("\\x%02x",(unsigned char)*s);
251 break;
252 }
253 s++;
254 }
255 printf("\"\n");
256 }
257
258 static int cliReadBulkReply(int fd) {
259 sds replylen = cliReadLine(fd);
260 char *reply, crlf[2];
261 int bulklen;
262
263 if (replylen == NULL) return 1;
264 bulklen = atoi(replylen);
265 if (bulklen == -1) {
266 sdsfree(replylen);
267 printf("(nil)\n");
268 return 0;
269 }
270 reply = zmalloc(bulklen);
271 anetRead(fd,reply,bulklen);
272 anetRead(fd,crlf,2);
273 if (!isatty(fileno(stdout))) {
274 if (bulklen && fwrite(reply,bulklen,1,stdout) == 0) {
275 zfree(reply);
276 return 1;
277 }
278 } else {
279 /* If you are producing output for the standard output we want
280 * a more interesting output with quoted characters and so forth */
281 printStringRepr(reply,bulklen);
282 }
283 zfree(reply);
284 return 0;
285 }
286
287 static int cliReadMultiBulkReply(int fd) {
288 sds replylen = cliReadLine(fd);
289 int elements, c = 1;
290
291 if (replylen == NULL) return 1;
292 elements = atoi(replylen);
293 if (elements == -1) {
294 sdsfree(replylen);
295 printf("(nil)\n");
296 return 0;
297 }
298 if (elements == 0) {
299 printf("(empty list or set)\n");
300 }
301 while(elements--) {
302 printf("%d. ", c);
303 if (cliReadReply(fd)) return 1;
304 c++;
305 }
306 return 0;
307 }
308
309 static int cliReadReply(int fd) {
310 char type;
311
312 if (anetRead(fd,&type,1) <= 0) exit(1);
313 switch(type) {
314 case '-':
315 printf("(error) ");
316 cliReadSingleLineReply(fd,0);
317 return 1;
318 case '+':
319 return cliReadSingleLineReply(fd,0);
320 case ':':
321 printf("(integer) ");
322 return cliReadSingleLineReply(fd,0);
323 case '$':
324 return cliReadBulkReply(fd);
325 case '*':
326 return cliReadMultiBulkReply(fd);
327 default:
328 printf("protocol error, got '%c' as reply type byte\n", type);
329 return 1;
330 }
331 }
332
333 static int selectDb(int fd) {
334 int retval;
335 sds cmd;
336 char type;
337
338 if (config.dbnum == 0)
339 return 0;
340
341 cmd = sdsempty();
342 cmd = sdscatprintf(cmd,"SELECT %d\r\n",config.dbnum);
343 anetWrite(fd,cmd,sdslen(cmd));
344 anetRead(fd,&type,1);
345 if (type <= 0 || type != '+') return 1;
346 retval = cliReadSingleLineReply(fd,1);
347 if (retval) {
348 return retval;
349 }
350 return 0;
351 }
352
353 static int cliSendCommand(int argc, char **argv, int repeat) {
354 struct redisCommand *rc = lookupCommand(argv[0]);
355 int fd, j, retval = 0;
356 sds cmd;
357
358 if (!rc) {
359 fprintf(stderr,"Unknown command '%s'\n",argv[0]);
360 return 1;
361 }
362
363 if ((rc->arity > 0 && argc != rc->arity) ||
364 (rc->arity < 0 && argc < -rc->arity)) {
365 fprintf(stderr,"Wrong number of arguments for '%s'\n",rc->name);
366 return 1;
367 }
368 if (!strcasecmp(rc->name,"monitor")) config.monitor_mode = 1;
369 if (!strcasecmp(rc->name,"subscribe") ||
370 !strcasecmp(rc->name,"psubscribe")) config.pubsub_mode = 1;
371 if ((fd = cliConnect()) == -1) return 1;
372
373 /* Select db number */
374 retval = selectDb(fd);
375 if (retval) {
376 fprintf(stderr,"Error setting DB num\n");
377 return 1;
378 }
379
380 while(repeat--) {
381 /* Build the command to send */
382 cmd = sdsempty();
383 if (rc->flags & REDIS_CMD_MULTIBULK) {
384 cmd = sdscatprintf(cmd,"*%d\r\n",argc);
385 for (j = 0; j < argc; j++) {
386 cmd = sdscatprintf(cmd,"$%lu\r\n",
387 (unsigned long)sdslen(argv[j]));
388 cmd = sdscatlen(cmd,argv[j],sdslen(argv[j]));
389 cmd = sdscatlen(cmd,"\r\n",2);
390 }
391 } else {
392 for (j = 0; j < argc; j++) {
393 if (j != 0) cmd = sdscat(cmd," ");
394 if (j == argc-1 && rc->flags & REDIS_CMD_BULK) {
395 cmd = sdscatprintf(cmd,"%lu",
396 (unsigned long)sdslen(argv[j]));
397 } else {
398 cmd = sdscatlen(cmd,argv[j],sdslen(argv[j]));
399 }
400 }
401 cmd = sdscat(cmd,"\r\n");
402 if (rc->flags & REDIS_CMD_BULK) {
403 cmd = sdscatlen(cmd,argv[argc-1],sdslen(argv[argc-1]));
404 cmd = sdscatlen(cmd,"\r\n",2);
405 }
406 }
407 anetWrite(fd,cmd,sdslen(cmd));
408 sdsfree(cmd);
409
410 while (config.monitor_mode) {
411 cliReadSingleLineReply(fd,0);
412 }
413
414 if (config.pubsub_mode) {
415 printf("Reading messages... (press Ctrl-c to quit)\n");
416 while (1) {
417 cliReadReply(fd);
418 printf("\n");
419 }
420 }
421
422 retval = cliReadReply(fd);
423 if (retval) {
424 return retval;
425 }
426 }
427 return 0;
428 }
429
430 static int parseOptions(int argc, char **argv) {
431 int i;
432
433 for (i = 1; i < argc; i++) {
434 int lastarg = i==argc-1;
435
436 if (!strcmp(argv[i],"-h") && !lastarg) {
437 char *ip = zmalloc(32);
438 if (anetResolve(NULL,argv[i+1],ip) == ANET_ERR) {
439 printf("Can't resolve %s\n", argv[i]);
440 exit(1);
441 }
442 config.hostip = ip;
443 i++;
444 } else if (!strcmp(argv[i],"-h") && lastarg) {
445 usage();
446 } else if (!strcmp(argv[i],"-p") && !lastarg) {
447 config.hostport = atoi(argv[i+1]);
448 i++;
449 } else if (!strcmp(argv[i],"-r") && !lastarg) {
450 config.repeat = strtoll(argv[i+1],NULL,10);
451 i++;
452 } else if (!strcmp(argv[i],"-n") && !lastarg) {
453 config.dbnum = atoi(argv[i+1]);
454 i++;
455 } else if (!strcmp(argv[i],"-a") && !lastarg) {
456 config.auth = argv[i+1];
457 i++;
458 } else if (!strcmp(argv[i],"-i")) {
459 config.interactive = 1;
460 } else {
461 break;
462 }
463 }
464 return i;
465 }
466
467 static sds readArgFromStdin(void) {
468 char buf[1024];
469 sds arg = sdsempty();
470
471 while(1) {
472 int nread = read(fileno(stdin),buf,1024);
473
474 if (nread == 0) break;
475 else if (nread == -1) {
476 perror("Reading from standard input");
477 exit(1);
478 }
479 arg = sdscatlen(arg,buf,nread);
480 }
481 return arg;
482 }
483
484 static void usage() {
485 fprintf(stderr, "usage: redis-cli [-h host] [-p port] [-a authpw] [-r repeat_times] [-n db_num] [-i] cmd arg1 arg2 arg3 ... argN\n");
486 fprintf(stderr, "usage: echo \"argN\" | redis-cli [-h host] [-a authpw] [-p port] [-r repeat_times] [-n db_num] cmd arg1 arg2 ... arg(N-1)\n");
487 fprintf(stderr, "\nIf a pipe from standard input is detected this data is used as last argument.\n\n");
488 fprintf(stderr, "example: cat /etc/passwd | redis-cli set my_passwd\n");
489 fprintf(stderr, "example: redis-cli get my_passwd\n");
490 fprintf(stderr, "example: redis-cli -r 100 lpush mylist x\n");
491 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
492 exit(1);
493 }
494
495 /* Turn the plain C strings into Sds strings */
496 static char **convertToSds(int count, char** args) {
497 int j;
498 char **sds = zmalloc(sizeof(char*)*count+1);
499
500 for(j = 0; j < count; j++)
501 sds[j] = sdsnew(args[j]);
502
503 return sds;
504 }
505
506 static char **splitArguments(char *line, int *argc) {
507 char *p = line;
508 char *current = NULL;
509 char **vector = NULL;
510
511 *argc = 0;
512 while(1) {
513 /* skip blanks */
514 while(*p && isspace(*p)) p++;
515 if (*p) {
516 /* get a token */
517 int inq=0; /* set to 1 if we are in "quotes" */
518 int done = 0;
519
520 if (current == NULL) current = sdsempty();
521 while(!done) {
522 if (inq) {
523 if (*p == '\\' && *(p+1)) {
524 char c;
525
526 p++;
527 switch(*p) {
528 case 'n': c = '\n'; break;
529 case 'r': c = '\r'; break;
530 case 't': c = '\t'; break;
531 case 'b': c = '\b'; break;
532 case 'a': c = '\a'; break;
533 default: c = *p; break;
534 }
535 current = sdscatlen(current,&c,1);
536 } else if (*p == '"') {
537 done = 1;
538 } else {
539 current = sdscatlen(current,p,1);
540 }
541 } else {
542 switch(*p) {
543 case ' ':
544 case '\n':
545 case '\r':
546 case '\t':
547 case '\0':
548 done=1;
549 break;
550 case '"':
551 inq=1;
552 break;
553 default:
554 current = sdscatlen(current,p,1);
555 break;
556 }
557 }
558 if (*p) p++;
559 }
560 /* add the token to the vector */
561 vector = zrealloc(vector,((*argc)+1)*sizeof(char*));
562 vector[*argc] = current;
563 (*argc)++;
564 current = NULL;
565 } else {
566 return vector;
567 }
568 }
569 }
570
571 #define LINE_BUFLEN 4096
572 static void repl() {
573 int argc, j;
574 char *line, **argv;
575
576 while((line = linenoise("redis> ")) != NULL) {
577 if (line[0] != '\0') {
578 argv = splitArguments(line,&argc);
579 linenoiseHistoryAdd(line);
580 if (argc > 0) {
581 if (strcasecmp(argv[0],"quit") == 0 ||
582 strcasecmp(argv[0],"exit") == 0)
583 exit(0);
584 else
585 cliSendCommand(argc, argv, 1);
586 }
587 /* Free the argument vector */
588 for (j = 0; j < argc; j++)
589 sdsfree(argv[j]);
590 free(argv);
591 }
592 /* linenoise() returns malloc-ed lines like readline() */
593 free(line);
594 }
595 exit(0);
596 }
597
598 int main(int argc, char **argv) {
599 int firstarg;
600 char **argvcopy;
601 struct redisCommand *rc;
602
603 config.hostip = "127.0.0.1";
604 config.hostport = 6379;
605 config.repeat = 1;
606 config.dbnum = 0;
607 config.interactive = 0;
608 config.monitor_mode = 0;
609 config.pubsub_mode = 0;
610 config.auth = NULL;
611
612 firstarg = parseOptions(argc,argv);
613 argc -= firstarg;
614 argv += firstarg;
615
616 if (config.auth != NULL) {
617 char *authargv[2];
618
619 authargv[0] = "AUTH";
620 authargv[1] = config.auth;
621 cliSendCommand(2, convertToSds(2, authargv), 1);
622 }
623
624 if (argc == 0 || config.interactive == 1) repl();
625
626 argvcopy = convertToSds(argc, argv);
627
628 /* Read the last argument from stdandard input if needed */
629 if ((rc = lookupCommand(argv[0])) != NULL) {
630 if (rc->arity > 0 && argc == rc->arity-1) {
631 sds lastarg = readArgFromStdin();
632 argvcopy[argc] = lastarg;
633 argc++;
634 }
635 }
636
637 return cliSendCommand(argc, argvcopy, config.repeat);
638 }