]>
git.saurik.com Git - redis.git/blob - src/redis-cli.c
865f093135550fdd8b7c36fe4214e87e90af95cd
1 /* Redis CLI (command line interface)
3 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
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.
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.
46 #include "linenoise.h"
49 #define REDIS_NOTUSED(V) ((void) V)
51 static redisContext
*context
;
52 static struct config
{
62 int raw_output
; /* output mode per command */
63 int tty
; /* flag for default output format */
64 int stdinarg
; /* get last arg from stdin. (-x option) */
71 char *redisGitSHA1(void);
73 /*------------------------------------------------------------------------------
75 *--------------------------------------------------------------------------- */
77 static long long mstime(void) {
81 gettimeofday(&tv
, NULL
);
82 mst
= ((long)tv
.tv_sec
)*1000;
83 mst
+= tv
.tv_usec
/1000;
87 /*------------------------------------------------------------------------------
89 *--------------------------------------------------------------------------- */
91 /* Output command help to stdout. */
92 static void outputCommandHelp(struct commandHelp
*help
) {
93 printf("\n \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\n", help
->name
, help
->params
);
94 printf(" \x1b[33msummary:\x1b[0m %s\n", help
->summary
);
95 printf(" \x1b[33msince:\x1b[0m %s\n", help
->since
);
96 printf(" \x1b[33mgroup:\x1b[0m %s\n", commandGroups
[help
->group
]);
99 /* Return command group type by name string. */
100 static int commandGroupIndex(const char *name
) {
101 int i
, len
= sizeof(commandGroups
)/sizeof(char*);
102 for (i
= 0; i
< len
; i
++)
103 if (strcasecmp(name
, commandGroups
[i
]) == 0)
108 /* Output group names. */
109 static void outputGroupHelp() {
110 int i
, len
= sizeof(commandGroups
)/sizeof(char*);
111 for (i
= 0; i
< len
; i
++)
112 printf(" \x1b[90m-\x1b[0m %s\n", commandGroups
[i
]);
115 /* Output all command help, filtering by group or command name. */
116 static void outputHelp(int argc
, char **argv
) {
117 int i
, len
= sizeof(commandHelp
) / sizeof(struct commandHelp
);
119 struct commandHelp
*help
;
121 if (argc
&& strcasecmp("groups", argv
[0]) == 0) {
126 group
= argc
? commandGroupIndex(argv
[0]) : -1;
127 for (i
= 0; i
< len
; i
++) {
128 help
= &commandHelp
[i
];
131 if (strcasecmp(help
->name
, argv
[0]) == 0) {
132 outputCommandHelp(help
);
135 outputCommandHelp(help
);
138 if (group
== help
->group
) {
139 outputCommandHelp(help
);
146 /*------------------------------------------------------------------------------
147 * Networking / parsing
148 *--------------------------------------------------------------------------- */
150 /* Send AUTH command to the server */
151 static int cliAuth() {
153 if (config
.auth
== NULL
) return REDIS_OK
;
155 reply
= redisCommand(context
,"AUTH %s",config
.auth
);
157 freeReplyObject(reply
);
163 /* Send SELECT dbnum to the server */
164 static int cliSelect() {
167 if (config
.dbnum
== 0) return REDIS_OK
;
169 snprintf(dbnum
,sizeof(dbnum
),"%d",config
.dbnum
);
170 reply
= redisCommand(context
,"SELECT %s",dbnum
);
172 freeReplyObject(reply
);
178 /* Connect to the client. If force is not zero the connection is performed
179 * even if there is already a connected socket. */
180 static int cliConnect(int force
) {
181 if (context
== NULL
|| force
) {
185 if (config
.hostsocket
== NULL
) {
186 context
= redisConnect(config
.hostip
,config
.hostport
);
188 context
= redisConnectUnix(config
.hostsocket
);
192 fprintf(stderr
,"Could not connect to Redis at ");
193 if (config
.hostsocket
== NULL
)
194 fprintf(stderr
,"%s:%d: %s\n",config
.hostip
,config
.hostport
,context
->errstr
);
196 fprintf(stderr
,"%s: %s\n",config
.hostsocket
,context
->errstr
);
202 /* Do AUTH and select the right DB. */
203 if (cliAuth() != REDIS_OK
)
205 if (cliSelect() != REDIS_OK
)
211 static void cliPrintContextErrorAndExit() {
212 if (context
== NULL
) return;
213 fprintf(stderr
,"Error: %s\n",context
->errstr
);
217 static sds
cliFormatReply(redisReply
*r
, char *prefix
) {
218 sds out
= sdsempty();
220 case REDIS_REPLY_ERROR
:
221 if (config
.tty
) out
= sdscat(out
,"(error) ");
222 out
= sdscatprintf(out
,"%s\n", r
->str
);
224 case REDIS_REPLY_STATUS
:
225 out
= sdscat(out
,r
->str
);
226 out
= sdscat(out
,"\n");
228 case REDIS_REPLY_INTEGER
:
229 if (config
.tty
) out
= sdscat(out
,"(integer) ");
230 out
= sdscatprintf(out
,"%lld\n",r
->integer
);
232 case REDIS_REPLY_STRING
:
233 if (config
.raw_output
|| !config
.tty
) {
234 out
= sdscatlen(out
,r
->str
,r
->len
);
236 /* If you are producing output for the standard output we want
237 * a more interesting output with quoted characters and so forth */
238 out
= sdscatrepr(out
,r
->str
,r
->len
);
239 out
= sdscat(out
,"\n");
242 case REDIS_REPLY_NIL
:
243 out
= sdscat(out
,"(nil)\n");
245 case REDIS_REPLY_ARRAY
:
246 if (r
->elements
== 0) {
247 out
= sdscat(out
,"(empty list or set)\n");
249 unsigned int i
, idxlen
= 0;
255 /* Calculate chars needed to represent the largest index */
262 /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
263 memset(_prefixlen
,' ',idxlen
+2);
264 _prefixlen
[idxlen
+2] = '\0';
265 _prefix
= sdscat(sdsnew(prefix
),_prefixlen
);
267 /* Setup prefix format for every entry */
268 snprintf(_prefixfmt
,sizeof(_prefixfmt
),"%%s%%%dd) ",idxlen
);
270 for (i
= 0; i
< r
->elements
; i
++) {
271 /* Don't use the prefix for the first element, as the parent
272 * caller already prepended the index number. */
273 out
= sdscatprintf(out
,_prefixfmt
,i
== 0 ? "" : prefix
,i
+1);
275 /* Format the multi bulk entry */
276 tmp
= cliFormatReply(r
->element
[i
],_prefix
);
277 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
284 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
290 static int cliReadReply() {
294 if (redisGetReply(context
,(void**)&reply
) != REDIS_OK
) {
297 if (config
.interactive
) {
298 /* Filter cases where we should reconnect */
299 if (context
->err
== REDIS_ERR_IO
&& errno
== ECONNRESET
)
301 if (context
->err
== REDIS_ERR_EOF
)
304 cliPrintContextErrorAndExit();
305 return REDIS_ERR
; /* avoid compiler warning */
308 out
= cliFormatReply(reply
,"");
309 freeReplyObject(reply
);
310 fwrite(out
,sdslen(out
),1,stdout
);
315 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
316 char *command
= argv
[0];
320 config
.raw_output
= !strcasecmp(command
,"info");
321 if (!strcasecmp(command
,"help")) {
322 outputHelp(--argc
, ++argv
);
325 if (!strcasecmp(command
,"shutdown")) config
.shutdown
= 1;
326 if (!strcasecmp(command
,"monitor")) config
.monitor_mode
= 1;
327 if (!strcasecmp(command
,"subscribe") ||
328 !strcasecmp(command
,"psubscribe")) config
.pubsub_mode
= 1;
330 /* Setup argument length */
331 argvlen
= malloc(argc
*sizeof(size_t));
332 for (j
= 0; j
< argc
; j
++)
333 argvlen
[j
] = sdslen(argv
[j
]);
336 redisAppendCommandArgv(context
,argc
,(const char**)argv
,argvlen
);
337 while (config
.monitor_mode
) {
338 if (cliReadReply() != REDIS_OK
) exit(1);
342 if (config
.pubsub_mode
) {
343 printf("Reading messages... (press Ctrl-C to quit)\n");
345 if (cliReadReply() != REDIS_OK
) exit(1);
349 if (cliReadReply() != REDIS_OK
)
355 /*------------------------------------------------------------------------------
357 *--------------------------------------------------------------------------- */
359 static int parseOptions(int argc
, char **argv
) {
362 for (i
= 1; i
< argc
; i
++) {
363 int lastarg
= i
==argc
-1;
365 if (!strcmp(argv
[i
],"-h") && !lastarg
) {
366 config
.hostip
= argv
[i
+1];
368 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
370 } else if (!strcmp(argv
[i
],"-x")) {
372 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
373 config
.hostport
= atoi(argv
[i
+1]);
375 } else if (!strcmp(argv
[i
],"-s") && !lastarg
) {
376 config
.hostsocket
= argv
[i
+1];
378 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
379 config
.repeat
= strtoll(argv
[i
+1],NULL
,10);
381 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
382 config
.dbnum
= atoi(argv
[i
+1]);
384 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
385 config
.auth
= argv
[i
+1];
387 } else if (!strcmp(argv
[i
],"-i")) {
389 "Starting interactive mode using -i is deprecated. Interactive mode is started\n"
390 "by default when redis-cli is executed without a command to execute.\n"
392 } else if (!strcmp(argv
[i
],"-c")) {
394 "Reading last argument from standard input using -c is deprecated.\n"
395 "When standard input is connected to a pipe or regular file, it is\n"
396 "automatically used as last argument.\n"
398 } else if (!strcmp(argv
[i
],"-v")) {
399 printf("redis-cli shipped with Redis version %s (%s)\n", REDIS_VERSION
, redisGitSHA1());
408 static sds
readArgFromStdin(void) {
410 sds arg
= sdsempty();
413 int nread
= read(fileno(stdin
),buf
,1024);
415 if (nread
== 0) break;
416 else if (nread
== -1) {
417 perror("Reading from standard input");
420 arg
= sdscatlen(arg
,buf
,nread
);
425 static void usage() {
426 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");
427 fprintf(stderr
, "usage: echo \"argN\" | redis-cli -x [options] cmd arg1 arg2 ... arg(N-1)\n\n");
428 fprintf(stderr
, "example: cat /etc/passwd | redis-cli -x set my_passwd\n");
429 fprintf(stderr
, "example: redis-cli get my_passwd\n");
430 fprintf(stderr
, "example: redis-cli -r 100 lpush mylist x\n");
431 fprintf(stderr
, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
435 /* Turn the plain C strings into Sds strings */
436 static char **convertToSds(int count
, char** args
) {
438 char **sds
= zmalloc(sizeof(char*)*count
);
440 for(j
= 0; j
< count
; j
++)
441 sds
[j
] = sdsnew(args
[j
]);
446 #define LINE_BUFLEN 4096
452 config
.interactive
= 1;
453 while((line
= linenoise("redis> ")) != NULL
) {
454 if (line
[0] != '\0') {
455 argv
= sdssplitargs(line
,&argc
);
456 linenoiseHistoryAdd(line
);
457 if (config
.historyfile
) linenoiseHistorySave(config
.historyfile
);
459 printf("Invalid argument(s)\n");
461 } else if (argc
> 0) {
462 if (strcasecmp(argv
[0],"quit") == 0 ||
463 strcasecmp(argv
[0],"exit") == 0)
467 long long start_time
= mstime(), elapsed
;
469 if (cliSendCommand(argc
,argv
,1) != REDIS_OK
) {
470 printf("Reconnecting... ");
472 if (cliConnect(1) != REDIS_OK
) exit(1);
475 /* If we still cannot send the command,
476 * print error and abort. */
477 if (cliSendCommand(argc
,argv
,1) != REDIS_OK
)
478 cliPrintContextErrorAndExit();
480 elapsed
= mstime()-start_time
;
481 if (elapsed
>= 500) {
482 printf("(%.2fs)\n",(double)elapsed
/1000);
486 /* Free the argument vector */
487 for (j
= 0; j
< argc
; j
++)
491 /* linenoise() returns malloc-ed lines like readline() */
497 static int noninteractive(int argc
, char **argv
) {
499 if (config
.stdinarg
) {
500 argv
= zrealloc(argv
, (argc
+1)*sizeof(char*));
501 argv
[argc
] = readArgFromStdin();
502 retval
= cliSendCommand(argc
+1, argv
, config
.repeat
);
504 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
505 retval
= cliSendCommand(argc
, argv
, config
.repeat
);
510 int main(int argc
, char **argv
) {
513 config
.hostip
= "127.0.0.1";
514 config
.hostport
= 6379;
515 config
.hostsocket
= NULL
;
518 config
.interactive
= 0;
520 config
.monitor_mode
= 0;
521 config
.pubsub_mode
= 0;
522 config
.raw_output
= 0;
525 config
.historyfile
= NULL
;
526 config
.tty
= isatty(fileno(stdout
)) || (getenv("FAKETTY") != NULL
);
527 config
.mb_sep
= '\n';
529 if (getenv("HOME") != NULL
) {
530 config
.historyfile
= malloc(256);
531 snprintf(config
.historyfile
,256,"%s/.rediscli_history",getenv("HOME"));
532 linenoiseHistoryLoad(config
.historyfile
);
535 firstarg
= parseOptions(argc
,argv
);
540 if (cliConnect(0) != REDIS_OK
) exit(1);
542 /* Start interactive mode when no command is provided */
543 if (argc
== 0) repl();
544 /* Otherwise, we have some arguments to execute */
545 return noninteractive(argc
,convertToSds(argc
,argv
));