]> git.saurik.com Git - redis.git/blob - src/redis-cli.c
dd67ff84ab2c44315e3f174f0b3d1bdea68e7a83
[redis.git] / src / 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 #include "version.h"
33
34 #include <stdio.h>
35 #include <string.h>
36 #include <stdlib.h>
37 #include <unistd.h>
38 #include <ctype.h>
39 #include <errno.h>
40 #include <sys/stat.h>
41 #include <sys/time.h>
42 #include <assert.h>
43
44 #include "hiredis.h"
45 #include "sds.h"
46 #include "zmalloc.h"
47 #include "linenoise.h"
48 #include "help.h"
49
50 #define REDIS_NOTUSED(V) ((void) V)
51
52 static redisContext *context;
53 static struct config {
54 char *hostip;
55 int hostport;
56 char *hostsocket;
57 long repeat;
58 int dbnum;
59 int interactive;
60 int shutdown;
61 int monitor_mode;
62 int pubsub_mode;
63 int raw_output; /* output mode per command */
64 int tty; /* flag for default output format */
65 int stdinarg; /* get last arg from stdin. (-x option) */
66 char mb_sep;
67 char *auth;
68 char *historyfile;
69 } config;
70
71 static void usage();
72 char *redisGitSHA1(void);
73
74 /*------------------------------------------------------------------------------
75 * Utility functions
76 *--------------------------------------------------------------------------- */
77
78 static long long mstime(void) {
79 struct timeval tv;
80 long long mst;
81
82 gettimeofday(&tv, NULL);
83 mst = ((long)tv.tv_sec)*1000;
84 mst += tv.tv_usec/1000;
85 return mst;
86 }
87
88 /*------------------------------------------------------------------------------
89 * Help functions
90 *--------------------------------------------------------------------------- */
91
92 /* Output command help to stdout. */
93 static void cliOutputCommandHelp(struct commandHelp *help, int group) {
94 printf("\r\n \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\r\n", help->name, help->params);
95 printf(" \x1b[33msummary:\x1b[0m %s\r\n", help->summary);
96 printf(" \x1b[33msince:\x1b[0m %s\r\n", help->since);
97 if (group) {
98 printf(" \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups[help->group]);
99 }
100 }
101
102 /* Print generic help. */
103 static void cliOutputGenericHelp() {
104 printf(
105 "redis-cli %s\r\n"
106 "Type: \"help @<group>\" to get a list of commands in <group>\r\n"
107 " \"help <command>\" for help on <command>\r\n"
108 " \"help <tab>\" to get a list of possible help topics\r\n"
109 " \"quit\" to exit\r\n",
110 REDIS_VERSION
111 );
112 }
113
114 /* Output all command help, filtering by group or command name. */
115 static void cliOutputHelp(int argc, char **argv) {
116 int i, len;
117 struct commandHelp *help;
118 int group = -1;
119
120 if (argc == 0) {
121 cliOutputGenericHelp();
122 return;
123 } else if (argc > 0 && argv[0][0] == '@') {
124 len = sizeof(commandGroups)/sizeof(char*);
125 for (i = 0; i < len; i++) {
126 if (strcasecmp(argv[0]+1,commandGroups[i]) == 0) {
127 group = i;
128 break;
129 }
130 }
131 }
132
133 len = sizeof(commandHelp)/sizeof(struct commandHelp);
134 assert(argc > 0);
135 for (i = 0; i < len; i++) {
136 help = &commandHelp[i];
137 if (group == -1) {
138 if (strcasecmp(help->name, argv[0]) == 0) {
139 cliOutputCommandHelp(help,1);
140 }
141 } else {
142 if (group == help->group) {
143 cliOutputCommandHelp(help,0);
144 }
145 }
146 }
147 printf("\r\n");
148 }
149
150 #define CLI_COMPLETE_COMMAND 1
151 #define CLI_COMPLETE_GROUP 2
152
153 typedef struct {
154 char *name;
155 int type;
156 } completionEntry;
157
158 static completionEntry *completionEntries;
159 static int completionEntriesLen;
160
161 /* Build 2 different arrays for completion. One for raw command completion and one
162 * for completion using HELP (including groups). */
163 static void cliInitHelp() {
164 int commandslen = sizeof(commandHelp)/sizeof(struct commandHelp);
165 int groupslen = sizeof(commandGroups)/sizeof(char*);
166 int i, len, pos = 0;
167 completionEntry tmp;
168
169 completionEntriesLen = len = commandslen+groupslen;
170 completionEntries = malloc(sizeof(completionEntry)*len);
171
172 for (i = 0; i < groupslen; i++) {
173 tmp.name = malloc(strlen(commandGroups[i]+2));
174 sprintf(tmp.name,"@%s",commandGroups[i]);
175 tmp.type = CLI_COMPLETE_GROUP;
176 completionEntries[pos++] = tmp;
177 }
178
179 for (i = 0; i < commandslen; i++) {
180 tmp.name = commandHelp[i].name;
181 tmp.type = CLI_COMPLETE_COMMAND;
182 completionEntries[pos++] = tmp;
183 }
184 }
185
186 static void completionCallback(const char *buf, linenoiseCompletions *lc) {
187 size_t startpos = 0;
188 int mask;
189 int i;
190 size_t matchlen;
191 char *tmp;
192 size_t tmpsize;
193
194 if (strncasecmp(buf,"help ",5) == 0) {
195 startpos = 5;
196 while (isspace(buf[startpos])) startpos++;
197 mask = CLI_COMPLETE_COMMAND | CLI_COMPLETE_GROUP;
198 } else {
199 mask = CLI_COMPLETE_COMMAND;
200 }
201
202 for (i = 0; i < completionEntriesLen; i++) {
203 if (!(completionEntries[i].type & mask)) continue;
204
205 matchlen = strlen(buf+startpos);
206 if (strncasecmp(buf+startpos,completionEntries[i].name,matchlen) == 0) {
207 tmpsize = startpos+strlen(completionEntries[i].name)+1;
208 tmp = malloc(tmpsize);
209 memcpy(tmp,buf,startpos);
210 memcpy(tmp+startpos,completionEntries[i].name,tmpsize-startpos);
211 linenoiseAddCompletion(lc,tmp);
212 free(tmp);
213 }
214 }
215 }
216
217 /*------------------------------------------------------------------------------
218 * Networking / parsing
219 *--------------------------------------------------------------------------- */
220
221 /* Send AUTH command to the server */
222 static int cliAuth() {
223 redisReply *reply;
224 if (config.auth == NULL) return REDIS_OK;
225
226 reply = redisCommand(context,"AUTH %s",config.auth);
227 if (reply != NULL) {
228 freeReplyObject(reply);
229 return REDIS_OK;
230 }
231 return REDIS_ERR;
232 }
233
234 /* Send SELECT dbnum to the server */
235 static int cliSelect() {
236 redisReply *reply;
237 char dbnum[16];
238 if (config.dbnum == 0) return REDIS_OK;
239
240 snprintf(dbnum,sizeof(dbnum),"%d",config.dbnum);
241 reply = redisCommand(context,"SELECT %s",dbnum);
242 if (reply != NULL) {
243 freeReplyObject(reply);
244 return REDIS_OK;
245 }
246 return REDIS_ERR;
247 }
248
249 /* Connect to the client. If force is not zero the connection is performed
250 * even if there is already a connected socket. */
251 static int cliConnect(int force) {
252 if (context == NULL || force) {
253 if (context != NULL)
254 redisFree(context);
255
256 if (config.hostsocket == NULL) {
257 context = redisConnect(config.hostip,config.hostport);
258 } else {
259 context = redisConnectUnix(config.hostsocket);
260 }
261
262 if (context->err) {
263 fprintf(stderr,"Could not connect to Redis at ");
264 if (config.hostsocket == NULL)
265 fprintf(stderr,"%s:%d: %s\n",config.hostip,config.hostport,context->errstr);
266 else
267 fprintf(stderr,"%s: %s\n",config.hostsocket,context->errstr);
268 redisFree(context);
269 context = NULL;
270 return REDIS_ERR;
271 }
272
273 /* Do AUTH and select the right DB. */
274 if (cliAuth() != REDIS_OK)
275 return REDIS_ERR;
276 if (cliSelect() != REDIS_OK)
277 return REDIS_ERR;
278 }
279 return REDIS_OK;
280 }
281
282 static void cliPrintContextErrorAndExit() {
283 if (context == NULL) return;
284 fprintf(stderr,"Error: %s\n",context->errstr);
285 exit(1);
286 }
287
288 static sds cliFormatReply(redisReply *r, char *prefix) {
289 sds out = sdsempty();
290 switch (r->type) {
291 case REDIS_REPLY_ERROR:
292 if (config.tty) out = sdscat(out,"(error) ");
293 out = sdscatprintf(out,"%s\n", r->str);
294 break;
295 case REDIS_REPLY_STATUS:
296 out = sdscat(out,r->str);
297 out = sdscat(out,"\n");
298 break;
299 case REDIS_REPLY_INTEGER:
300 if (config.tty) out = sdscat(out,"(integer) ");
301 out = sdscatprintf(out,"%lld\n",r->integer);
302 break;
303 case REDIS_REPLY_STRING:
304 if (config.raw_output || !config.tty) {
305 out = sdscatlen(out,r->str,r->len);
306 } else {
307 /* If you are producing output for the standard output we want
308 * a more interesting output with quoted characters and so forth */
309 out = sdscatrepr(out,r->str,r->len);
310 out = sdscat(out,"\n");
311 }
312 break;
313 case REDIS_REPLY_NIL:
314 out = sdscat(out,"(nil)\n");
315 break;
316 case REDIS_REPLY_ARRAY:
317 if (r->elements == 0) {
318 out = sdscat(out,"(empty list or set)\n");
319 } else {
320 unsigned int i, idxlen = 0;
321 char _prefixlen[16];
322 char _prefixfmt[16];
323 sds _prefix;
324 sds tmp;
325
326 /* Calculate chars needed to represent the largest index */
327 i = r->elements;
328 do {
329 idxlen++;
330 i /= 10;
331 } while(i);
332
333 /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
334 memset(_prefixlen,' ',idxlen+2);
335 _prefixlen[idxlen+2] = '\0';
336 _prefix = sdscat(sdsnew(prefix),_prefixlen);
337
338 /* Setup prefix format for every entry */
339 snprintf(_prefixfmt,sizeof(_prefixfmt),"%%s%%%dd) ",idxlen);
340
341 for (i = 0; i < r->elements; i++) {
342 /* Don't use the prefix for the first element, as the parent
343 * caller already prepended the index number. */
344 out = sdscatprintf(out,_prefixfmt,i == 0 ? "" : prefix,i+1);
345
346 /* Format the multi bulk entry */
347 tmp = cliFormatReply(r->element[i],_prefix);
348 out = sdscatlen(out,tmp,sdslen(tmp));
349 sdsfree(tmp);
350 }
351 sdsfree(_prefix);
352 }
353 break;
354 default:
355 fprintf(stderr,"Unknown reply type: %d\n", r->type);
356 exit(1);
357 }
358 return out;
359 }
360
361 static int cliReadReply() {
362 redisReply *reply;
363 sds out;
364
365 if (redisGetReply(context,(void**)&reply) != REDIS_OK) {
366 if (config.shutdown)
367 return REDIS_OK;
368 if (config.interactive) {
369 /* Filter cases where we should reconnect */
370 if (context->err == REDIS_ERR_IO && errno == ECONNRESET)
371 return REDIS_ERR;
372 if (context->err == REDIS_ERR_EOF)
373 return REDIS_ERR;
374 }
375 cliPrintContextErrorAndExit();
376 return REDIS_ERR; /* avoid compiler warning */
377 }
378
379 out = cliFormatReply(reply,"");
380 freeReplyObject(reply);
381 fwrite(out,sdslen(out),1,stdout);
382 sdsfree(out);
383 return REDIS_OK;
384 }
385
386 static int cliSendCommand(int argc, char **argv, int repeat) {
387 char *command = argv[0];
388 size_t *argvlen;
389 int j;
390
391 config.raw_output = !strcasecmp(command,"info");
392 if (!strcasecmp(command,"help") || !strcasecmp(command,"?")) {
393 cliOutputHelp(--argc, ++argv);
394 return REDIS_OK;
395 }
396 if (!strcasecmp(command,"shutdown")) config.shutdown = 1;
397 if (!strcasecmp(command,"monitor")) config.monitor_mode = 1;
398 if (!strcasecmp(command,"subscribe") ||
399 !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1;
400
401 /* Setup argument length */
402 argvlen = malloc(argc*sizeof(size_t));
403 for (j = 0; j < argc; j++)
404 argvlen[j] = sdslen(argv[j]);
405
406 while(repeat--) {
407 redisAppendCommandArgv(context,argc,(const char**)argv,argvlen);
408 while (config.monitor_mode) {
409 if (cliReadReply() != REDIS_OK) exit(1);
410 fflush(stdout);
411 }
412
413 if (config.pubsub_mode) {
414 printf("Reading messages... (press Ctrl-C to quit)\n");
415 while (1) {
416 if (cliReadReply() != REDIS_OK) exit(1);
417 }
418 }
419
420 if (cliReadReply() != REDIS_OK)
421 return REDIS_ERR;
422 }
423 return REDIS_OK;
424 }
425
426 /*------------------------------------------------------------------------------
427 * User interface
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 config.hostip = argv[i+1];
438 i++;
439 } else if (!strcmp(argv[i],"-h") && lastarg) {
440 usage();
441 } else if (!strcmp(argv[i],"-x")) {
442 config.stdinarg = 1;
443 } else if (!strcmp(argv[i],"-p") && !lastarg) {
444 config.hostport = atoi(argv[i+1]);
445 i++;
446 } else if (!strcmp(argv[i],"-s") && !lastarg) {
447 config.hostsocket = 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 fprintf(stderr,
460 "Starting interactive mode using -i is deprecated. Interactive mode is started\n"
461 "by default when redis-cli is executed without a command to execute.\n"
462 );
463 } else if (!strcmp(argv[i],"-c")) {
464 fprintf(stderr,
465 "Reading last argument from standard input using -c is deprecated.\n"
466 "When standard input is connected to a pipe or regular file, it is\n"
467 "automatically used as last argument.\n"
468 );
469 } else if (!strcmp(argv[i],"-v")) {
470 printf("redis-cli shipped with Redis version %s (%s)\n", REDIS_VERSION, redisGitSHA1());
471 exit(0);
472 } else {
473 break;
474 }
475 }
476 return i;
477 }
478
479 static sds readArgFromStdin(void) {
480 char buf[1024];
481 sds arg = sdsempty();
482
483 while(1) {
484 int nread = read(fileno(stdin),buf,1024);
485
486 if (nread == 0) break;
487 else if (nread == -1) {
488 perror("Reading from standard input");
489 exit(1);
490 }
491 arg = sdscatlen(arg,buf,nread);
492 }
493 return arg;
494 }
495
496 static void usage() {
497 fprintf(stderr, "usage: redis-cli [-iv] [-h host] [-p port] [-s /path/to/socket] [-a authpw] [-r repeat_times] [-n db_num] cmd arg1 arg2 arg3 ... argN\n");
498 fprintf(stderr, "usage: echo \"argN\" | redis-cli -x [options] cmd arg1 arg2 ... arg(N-1)\n\n");
499 fprintf(stderr, "example: cat /etc/passwd | redis-cli -x set my_passwd\n");
500 fprintf(stderr, "example: redis-cli get my_passwd\n");
501 fprintf(stderr, "example: redis-cli -r 100 lpush mylist x\n");
502 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
503 exit(1);
504 }
505
506 /* Turn the plain C strings into Sds strings */
507 static char **convertToSds(int count, char** args) {
508 int j;
509 char **sds = zmalloc(sizeof(char*)*count);
510
511 for(j = 0; j < count; j++)
512 sds[j] = sdsnew(args[j]);
513
514 return sds;
515 }
516
517 #define LINE_BUFLEN 4096
518 static void repl() {
519 int argc, j;
520 char *line;
521 sds *argv;
522
523 config.interactive = 1;
524 linenoiseSetCompletionCallback(completionCallback);
525 while((line = linenoise("redis> ")) != NULL) {
526 if (line[0] != '\0') {
527 argv = sdssplitargs(line,&argc);
528 linenoiseHistoryAdd(line);
529 if (config.historyfile) linenoiseHistorySave(config.historyfile);
530 if (argv == NULL) {
531 printf("Invalid argument(s)\n");
532 continue;
533 } else if (argc > 0) {
534 if (strcasecmp(argv[0],"quit") == 0 ||
535 strcasecmp(argv[0],"exit") == 0)
536 {
537 exit(0);
538 } else {
539 long long start_time = mstime(), elapsed;
540
541 if (cliSendCommand(argc,argv,1) != REDIS_OK) {
542 printf("Reconnecting... ");
543 fflush(stdout);
544 if (cliConnect(1) != REDIS_OK) exit(1);
545 printf("OK\n");
546
547 /* If we still cannot send the command,
548 * print error and abort. */
549 if (cliSendCommand(argc,argv,1) != REDIS_OK)
550 cliPrintContextErrorAndExit();
551 }
552 elapsed = mstime()-start_time;
553 if (elapsed >= 500) {
554 printf("(%.2fs)\n",(double)elapsed/1000);
555 }
556 }
557 }
558 /* Free the argument vector */
559 for (j = 0; j < argc; j++)
560 sdsfree(argv[j]);
561 zfree(argv);
562 }
563 /* linenoise() returns malloc-ed lines like readline() */
564 free(line);
565 }
566 exit(0);
567 }
568
569 static int noninteractive(int argc, char **argv) {
570 int retval = 0;
571 if (config.stdinarg) {
572 argv = zrealloc(argv, (argc+1)*sizeof(char*));
573 argv[argc] = readArgFromStdin();
574 retval = cliSendCommand(argc+1, argv, config.repeat);
575 } else {
576 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
577 retval = cliSendCommand(argc, argv, config.repeat);
578 }
579 return retval;
580 }
581
582 int main(int argc, char **argv) {
583 int firstarg;
584
585 config.hostip = "127.0.0.1";
586 config.hostport = 6379;
587 config.hostsocket = NULL;
588 config.repeat = 1;
589 config.dbnum = 0;
590 config.interactive = 0;
591 config.shutdown = 0;
592 config.monitor_mode = 0;
593 config.pubsub_mode = 0;
594 config.raw_output = 0;
595 config.stdinarg = 0;
596 config.auth = NULL;
597 config.historyfile = NULL;
598 config.tty = isatty(fileno(stdout)) || (getenv("FAKETTY") != NULL);
599 config.mb_sep = '\n';
600 cliInitHelp();
601
602 if (getenv("HOME") != NULL) {
603 config.historyfile = malloc(256);
604 snprintf(config.historyfile,256,"%s/.rediscli_history",getenv("HOME"));
605 linenoiseHistoryLoad(config.historyfile);
606 }
607
608 firstarg = parseOptions(argc,argv);
609 argc -= firstarg;
610 argv += firstarg;
611
612 /* Try to connect */
613 if (cliConnect(0) != REDIS_OK) exit(1);
614
615 /* Start interactive mode when no command is provided */
616 if (argc == 0) repl();
617 /* Otherwise, we have some arguments to execute */
618 return noninteractive(argc,convertToSds(argc,argv));
619 }