]>
git.saurik.com Git - redis.git/blob - src/redis-cli.c
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"
48 #define REDIS_NOTUSED(V) ((void) V)
50 static redisContext
*context
;
51 static struct config
{
61 int raw_output
; /* output mode per command */
62 int tty
; /* flag for default output format */
63 int stdinarg
; /* get last arg from stdin. (-x option) */
70 char *redisGitSHA1(void);
72 /*------------------------------------------------------------------------------
74 *--------------------------------------------------------------------------- */
76 static long long mstime(void) {
80 gettimeofday(&tv
, NULL
);
81 mst
= ((long)tv
.tv_sec
)*1000;
82 mst
+= tv
.tv_usec
/1000;
86 /*------------------------------------------------------------------------------
87 * Networking / parsing
88 *--------------------------------------------------------------------------- */
90 /* Send AUTH command to the server */
91 static int cliAuth() {
93 if (config
.auth
== NULL
) return REDIS_OK
;
95 reply
= redisCommand(context
,"AUTH %s",config
.auth
);
97 freeReplyObject(reply
);
103 /* Send SELECT dbnum to the server */
104 static int cliSelect() {
107 if (config
.dbnum
== 0) return REDIS_OK
;
109 snprintf(dbnum
,sizeof(dbnum
),"%d",config
.dbnum
);
110 reply
= redisCommand(context
,"SELECT %s",dbnum
);
112 freeReplyObject(reply
);
118 /* Connect to the client. If force is not zero the connection is performed
119 * even if there is already a connected socket. */
120 static int cliConnect(int force
) {
121 if (context
== NULL
|| force
) {
125 if (config
.hostsocket
== NULL
) {
126 context
= redisConnect(config
.hostip
,config
.hostport
);
128 context
= redisConnectUnix(config
.hostsocket
);
132 fprintf(stderr
,"Could not connect to Redis at ");
133 if (config
.hostsocket
== NULL
)
134 fprintf(stderr
,"%s:%d: %s\n",config
.hostip
,config
.hostport
,context
->errstr
);
136 fprintf(stderr
,"%s: %s\n",config
.hostsocket
,context
->errstr
);
142 /* Do AUTH and select the right DB. */
143 if (cliAuth() != REDIS_OK
)
145 if (cliSelect() != REDIS_OK
)
151 static void cliPrintContextErrorAndExit() {
152 if (context
== NULL
) return;
153 fprintf(stderr
,"Error: %s\n",context
->errstr
);
157 static sds
cliFormatReply(redisReply
*r
, char *prefix
) {
158 sds out
= sdsempty();
160 case REDIS_REPLY_ERROR
:
161 if (config
.tty
) out
= sdscat(out
,"(error) ");
162 out
= sdscatprintf(out
,"%s\n", r
->str
);
164 case REDIS_REPLY_STATUS
:
165 out
= sdscat(out
,r
->str
);
166 out
= sdscat(out
,"\n");
168 case REDIS_REPLY_INTEGER
:
169 if (config
.tty
) out
= sdscat(out
,"(integer) ");
170 out
= sdscatprintf(out
,"%lld\n",r
->integer
);
172 case REDIS_REPLY_STRING
:
173 if (config
.raw_output
|| !config
.tty
) {
174 out
= sdscatlen(out
,r
->str
,r
->len
);
176 /* If you are producing output for the standard output we want
177 * a more interesting output with quoted characters and so forth */
178 out
= sdscatrepr(out
,r
->str
,r
->len
);
179 out
= sdscat(out
,"\n");
182 case REDIS_REPLY_NIL
:
183 out
= sdscat(out
,"(nil)\n");
185 case REDIS_REPLY_ARRAY
:
186 if (r
->elements
== 0) {
187 out
= sdscat(out
,"(empty list or set)\n");
189 unsigned int i
, idxlen
= 0;
195 /* Calculate chars needed to represent the largest index */
202 /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
203 memset(_prefixlen
,' ',idxlen
+2);
204 _prefixlen
[idxlen
+2] = '\0';
205 _prefix
= sdscat(sdsnew(prefix
),_prefixlen
);
207 /* Setup prefix format for every entry */
208 snprintf(_prefixfmt
,sizeof(_prefixfmt
),"%%s%%%dd) ",idxlen
);
210 for (i
= 0; i
< r
->elements
; i
++) {
211 /* Don't use the prefix for the first element, as the parent
212 * caller already prepended the index number. */
213 out
= sdscatprintf(out
,_prefixfmt
,i
== 0 ? "" : prefix
,i
+1);
215 /* Format the multi bulk entry */
216 tmp
= cliFormatReply(r
->element
[i
],_prefix
);
217 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
224 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
230 static int cliReadReply() {
234 if (redisGetReply(context
,(void**)&reply
) != REDIS_OK
) {
237 if (config
.interactive
) {
238 /* Filter cases where we should reconnect */
239 if (context
->err
== REDIS_ERR_IO
&& errno
== ECONNRESET
)
241 if (context
->err
== REDIS_ERR_EOF
)
244 cliPrintContextErrorAndExit();
245 return REDIS_ERR
; /* avoid compiler warning */
248 out
= cliFormatReply(reply
,"");
249 freeReplyObject(reply
);
250 fwrite(out
,sdslen(out
),1,stdout
);
255 static void showInteractiveHelp(void) {
258 "Welcome to redis-cli " REDIS_VERSION
"!\n"
259 "Just type any valid Redis command to see a pretty printed output.\n"
261 "It is possible to quote strings, like in:\n"
262 " set \"my key\" \"some string \\xff\\n\"\n"
264 "You can find a list of valid Redis commands at\n"
265 " http://code.google.com/p/redis/wiki/CommandReference\n"
267 "Note: redis-cli supports line editing, use up/down arrows for history."
271 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
272 char *command
= argv
[0];
276 if (context
== NULL
) {
277 printf("Not connected, please use: connect <host> <port>\n");
281 config
.raw_output
= !strcasecmp(command
,"info");
282 if (!strcasecmp(command
,"help")) {
283 showInteractiveHelp();
286 if (!strcasecmp(command
,"shutdown")) config
.shutdown
= 1;
287 if (!strcasecmp(command
,"monitor")) config
.monitor_mode
= 1;
288 if (!strcasecmp(command
,"subscribe") ||
289 !strcasecmp(command
,"psubscribe")) config
.pubsub_mode
= 1;
291 /* Setup argument length */
292 argvlen
= malloc(argc
*sizeof(size_t));
293 for (j
= 0; j
< argc
; j
++)
294 argvlen
[j
] = sdslen(argv
[j
]);
297 redisAppendCommandArgv(context
,argc
,(const char**)argv
,argvlen
);
298 while (config
.monitor_mode
) {
299 if (cliReadReply() != REDIS_OK
) exit(1);
303 if (config
.pubsub_mode
) {
304 printf("Reading messages... (press Ctrl-C to quit)\n");
306 if (cliReadReply() != REDIS_OK
) exit(1);
310 if (cliReadReply() != REDIS_OK
)
316 /*------------------------------------------------------------------------------
318 *--------------------------------------------------------------------------- */
320 static int parseOptions(int argc
, char **argv
) {
323 for (i
= 1; i
< argc
; i
++) {
324 int lastarg
= i
==argc
-1;
326 if (!strcmp(argv
[i
],"-h") && !lastarg
) {
327 sdsfree(config
.hostip
);
328 config
.hostip
= sdsnew(argv
[i
+1]);
330 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
332 } else if (!strcmp(argv
[i
],"-x")) {
334 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
335 config
.hostport
= atoi(argv
[i
+1]);
337 } else if (!strcmp(argv
[i
],"-s") && !lastarg
) {
338 config
.hostsocket
= argv
[i
+1];
340 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
341 config
.repeat
= strtoll(argv
[i
+1],NULL
,10);
343 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
344 config
.dbnum
= atoi(argv
[i
+1]);
346 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
347 config
.auth
= argv
[i
+1];
349 } else if (!strcmp(argv
[i
],"-i")) {
351 "Starting interactive mode using -i is deprecated. Interactive mode is started\n"
352 "by default when redis-cli is executed without a command to execute.\n"
354 } else if (!strcmp(argv
[i
],"-c")) {
356 "Reading last argument from standard input using -c is deprecated.\n"
357 "When standard input is connected to a pipe or regular file, it is\n"
358 "automatically used as last argument.\n"
360 } else if (!strcmp(argv
[i
],"-v")) {
361 printf("redis-cli shipped with Redis version %s (%s)\n", REDIS_VERSION
, redisGitSHA1());
370 static sds
readArgFromStdin(void) {
372 sds arg
= sdsempty();
375 int nread
= read(fileno(stdin
),buf
,1024);
377 if (nread
== 0) break;
378 else if (nread
== -1) {
379 perror("Reading from standard input");
382 arg
= sdscatlen(arg
,buf
,nread
);
387 static void usage() {
388 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");
389 fprintf(stderr
, "usage: echo \"argN\" | redis-cli -x [options] cmd arg1 arg2 ... arg(N-1)\n\n");
390 fprintf(stderr
, "example: cat /etc/passwd | redis-cli -x set my_passwd\n");
391 fprintf(stderr
, "example: redis-cli get my_passwd\n");
392 fprintf(stderr
, "example: redis-cli -r 100 lpush mylist x\n");
393 fprintf(stderr
, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
397 /* Turn the plain C strings into Sds strings */
398 static char **convertToSds(int count
, char** args
) {
400 char **sds
= zmalloc(sizeof(char*)*count
);
402 for(j
= 0; j
< count
; j
++)
403 sds
[j
] = sdsnew(args
[j
]);
408 #define LINE_BUFLEN 4096
414 config
.interactive
= 1;
415 while((line
= linenoise(context
? "redis> " : "not connected> ")) != NULL
) {
416 if (line
[0] != '\0') {
417 argv
= sdssplitargs(line
,&argc
);
418 linenoiseHistoryAdd(line
);
419 if (config
.historyfile
) linenoiseHistorySave(config
.historyfile
);
421 printf("Invalid argument(s)\n");
423 } else if (argc
> 0) {
424 if (strcasecmp(argv
[0],"quit") == 0 ||
425 strcasecmp(argv
[0],"exit") == 0)
428 } else if (argc
== 3 && !strcasecmp(argv
[0],"connect")) {
429 sdsfree(config
.hostip
);
430 config
.hostip
= sdsnew(argv
[1]);
431 config
.hostport
= atoi(argv
[2]);
434 long long start_time
= mstime(), elapsed
;
436 if (cliSendCommand(argc
,argv
,1) != REDIS_OK
) {
439 /* If we still cannot send the command,
440 * print error and abort. */
441 if (cliSendCommand(argc
,argv
,1) != REDIS_OK
)
442 cliPrintContextErrorAndExit();
444 elapsed
= mstime()-start_time
;
445 if (elapsed
>= 500) {
446 printf("(%.2fs)\n",(double)elapsed
/1000);
450 /* Free the argument vector */
451 for (j
= 0; j
< argc
; j
++)
455 /* linenoise() returns malloc-ed lines like readline() */
461 static int noninteractive(int argc
, char **argv
) {
463 if (config
.stdinarg
) {
464 argv
= zrealloc(argv
, (argc
+1)*sizeof(char*));
465 argv
[argc
] = readArgFromStdin();
466 retval
= cliSendCommand(argc
+1, argv
, config
.repeat
);
468 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
469 retval
= cliSendCommand(argc
, argv
, config
.repeat
);
474 int main(int argc
, char **argv
) {
477 config
.hostip
= sdsnew("127.0.0.1");
478 config
.hostport
= 6379;
479 config
.hostsocket
= NULL
;
482 config
.interactive
= 0;
484 config
.monitor_mode
= 0;
485 config
.pubsub_mode
= 0;
486 config
.raw_output
= 0;
489 config
.historyfile
= NULL
;
490 config
.tty
= isatty(fileno(stdout
)) || (getenv("FAKETTY") != NULL
);
491 config
.mb_sep
= '\n';
493 if (getenv("HOME") != NULL
) {
494 config
.historyfile
= malloc(256);
495 snprintf(config
.historyfile
,256,"%s/.rediscli_history",getenv("HOME"));
496 linenoiseHistoryLoad(config
.historyfile
);
499 firstarg
= parseOptions(argc
,argv
);
504 if (cliConnect(0) != REDIS_OK
) exit(1);
506 /* Start interactive mode when no command is provided */
507 if (argc
== 0) repl();
508 /* Otherwise, we have some arguments to execute */
509 return noninteractive(argc
,convertToSds(argc
,argv
));