]>
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) */
71 /*------------------------------------------------------------------------------
73 *--------------------------------------------------------------------------- */
75 static long long mstime(void) {
79 gettimeofday(&tv
, NULL
);
80 mst
= ((long)tv
.tv_sec
)*1000;
81 mst
+= tv
.tv_usec
/1000;
85 /*------------------------------------------------------------------------------
86 * Networking / parsing
87 *--------------------------------------------------------------------------- */
89 /* Send AUTH command to the server */
90 static int cliAuth() {
92 if (config
.auth
== NULL
) return REDIS_OK
;
94 reply
= redisCommand(context
,"AUTH %s",config
.auth
);
96 freeReplyObject(reply
);
102 /* Send SELECT dbnum to the server */
103 static int cliSelect() {
106 if (config
.dbnum
== 0) return REDIS_OK
;
108 snprintf(dbnum
,sizeof(dbnum
),"%d",config
.dbnum
);
109 reply
= redisCommand(context
,"SELECT %s",dbnum
);
111 freeReplyObject(reply
);
117 /* Connect to the client. If force is not zero the connection is performed
118 * even if there is already a connected socket. */
119 static int cliConnect(int force
) {
120 if (context
== NULL
|| force
) {
124 if (config
.hostsocket
== NULL
) {
125 context
= redisConnect(config
.hostip
,config
.hostport
);
127 context
= redisConnectUnix(config
.hostsocket
);
131 fprintf(stderr
,"Could not connect to Redis at ");
132 if (config
.hostsocket
== NULL
)
133 fprintf(stderr
,"%s:%d: %s\n",config
.hostip
,config
.hostport
,context
->errstr
);
135 fprintf(stderr
,"%s: %s\n",config
.hostsocket
,context
->errstr
);
141 /* Do AUTH and select the right DB. */
142 if (cliAuth() != REDIS_OK
)
144 if (cliSelect() != REDIS_OK
)
150 static void cliPrintContextErrorAndExit() {
151 if (context
== NULL
) return;
152 fprintf(stderr
,"Error: %s\n",context
->errstr
);
156 static sds
cliFormatReply(redisReply
*r
, char *prefix
) {
157 sds out
= sdsempty();
159 case REDIS_REPLY_ERROR
:
160 out
= sdscat(out
,prefix
);
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
,prefix
);
166 out
= sdscat(out
,r
->str
);
167 out
= sdscat(out
,"\n");
169 case REDIS_REPLY_INTEGER
:
170 out
= sdscat(out
,prefix
);
171 if (config
.tty
) out
= sdscat(out
,"(integer) ");
172 out
= sdscatprintf(out
,"%lld\n",r
->integer
);
174 case REDIS_REPLY_STRING
:
175 out
= sdscat(out
,prefix
);
176 if (config
.raw_output
|| !config
.tty
) {
177 out
= sdscatlen(out
,r
->str
,r
->len
);
179 /* If you are producing output for the standard output we want
180 * a more interesting output with quoted characters and so forth */
181 out
= sdscatrepr(out
,r
->str
,r
->len
);
182 out
= sdscat(out
,"\n");
185 case REDIS_REPLY_NIL
:
186 out
= sdscat(out
,prefix
);
187 out
= sdscat(out
,"(nil)\n");
189 case REDIS_REPLY_ARRAY
:
190 if (r
->elements
== 0) {
191 out
= sdscat(out
,prefix
);
192 out
= sdscat(out
,"(empty list or set)\n");
197 for (i
= 0; i
< r
->elements
; i
++) {
198 tmp
= cliFormatReply(r
->element
[i
],prefix
);
199 out
= sdscat(out
,prefix
);
200 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
206 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
212 static int cliReadReply() {
216 if (redisGetReply(context
,(void**)&reply
) != REDIS_OK
) {
219 if (config
.interactive
) {
220 /* Filter cases where we should reconnect */
221 if (context
->err
== REDIS_ERR_IO
&& errno
== ECONNRESET
)
223 if (context
->err
== REDIS_ERR_EOF
)
226 cliPrintContextErrorAndExit();
227 return REDIS_ERR
; /* avoid compiler warning */
230 out
= cliFormatReply(reply
,"");
231 freeReplyObject(reply
);
232 fwrite(out
,sdslen(out
),1,stdout
);
237 static void showInteractiveHelp(void) {
240 "Welcome to redis-cli " REDIS_VERSION
"!\n"
241 "Just type any valid Redis command to see a pretty printed output.\n"
243 "It is possible to quote strings, like in:\n"
244 " set \"my key\" \"some string \\xff\\n\"\n"
246 "You can find a list of valid Redis commands at\n"
247 " http://code.google.com/p/redis/wiki/CommandReference\n"
249 "Note: redis-cli supports line editing, use up/down arrows for history."
253 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
254 char *command
= argv
[0];
258 config
.raw_output
= !strcasecmp(command
,"info");
259 if (!strcasecmp(command
,"help")) {
260 showInteractiveHelp();
263 if (!strcasecmp(command
,"shutdown")) config
.shutdown
= 1;
264 if (!strcasecmp(command
,"monitor")) config
.monitor_mode
= 1;
265 if (!strcasecmp(command
,"subscribe") ||
266 !strcasecmp(command
,"psubscribe")) config
.pubsub_mode
= 1;
268 /* Setup argument length */
269 argvlen
= malloc(argc
*sizeof(size_t));
270 for (j
= 0; j
< argc
; j
++)
271 argvlen
[j
] = sdslen(argv
[j
]);
274 redisAppendCommandArgv(context
,argc
,(const char**)argv
,argvlen
);
275 while (config
.monitor_mode
) {
276 if (cliReadReply() != REDIS_OK
) exit(1);
279 if (config
.pubsub_mode
) {
280 printf("Reading messages... (press Ctrl-C to quit)\n");
282 if (cliReadReply() != REDIS_OK
) exit(1);
286 if (cliReadReply() != REDIS_OK
)
292 /*------------------------------------------------------------------------------
294 *--------------------------------------------------------------------------- */
296 static int parseOptions(int argc
, char **argv
) {
299 for (i
= 1; i
< argc
; i
++) {
300 int lastarg
= i
==argc
-1;
302 if (!strcmp(argv
[i
],"-h") && !lastarg
) {
303 config
.hostip
= argv
[i
+1];
305 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
307 } else if (!strcmp(argv
[i
],"-x")) {
309 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
310 config
.hostport
= atoi(argv
[i
+1]);
312 } else if (!strcmp(argv
[i
],"-s") && !lastarg
) {
313 config
.hostsocket
= argv
[i
+1];
315 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
316 config
.repeat
= strtoll(argv
[i
+1],NULL
,10);
318 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
319 config
.dbnum
= atoi(argv
[i
+1]);
321 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
322 config
.auth
= argv
[i
+1];
324 } else if (!strcmp(argv
[i
],"-i")) {
326 "Starting interactive mode using -i is deprecated. Interactive mode is started\n"
327 "by default when redis-cli is executed without a command to execute.\n"
329 } else if (!strcmp(argv
[i
],"-c")) {
331 "Reading last argument from standard input using -c is deprecated.\n"
332 "When standard input is connected to a pipe or regular file, it is\n"
333 "automatically used as last argument.\n"
335 } else if (!strcmp(argv
[i
],"-v")) {
336 printf("redis-cli shipped with Redis version %s\n", REDIS_VERSION
);
345 static sds
readArgFromStdin(void) {
347 sds arg
= sdsempty();
350 int nread
= read(fileno(stdin
),buf
,1024);
352 if (nread
== 0) break;
353 else if (nread
== -1) {
354 perror("Reading from standard input");
357 arg
= sdscatlen(arg
,buf
,nread
);
362 static void usage() {
363 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");
364 fprintf(stderr
, "usage: echo \"argN\" | redis-cli -x [options] cmd arg1 arg2 ... arg(N-1)\n\n");
365 fprintf(stderr
, "example: cat /etc/passwd | redis-cli -x set my_passwd\n");
366 fprintf(stderr
, "example: redis-cli get my_passwd\n");
367 fprintf(stderr
, "example: redis-cli -r 100 lpush mylist x\n");
368 fprintf(stderr
, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
372 /* Turn the plain C strings into Sds strings */
373 static char **convertToSds(int count
, char** args
) {
375 char **sds
= zmalloc(sizeof(char*)*count
);
377 for(j
= 0; j
< count
; j
++)
378 sds
[j
] = sdsnew(args
[j
]);
383 #define LINE_BUFLEN 4096
389 config
.interactive
= 1;
390 while((line
= linenoise("redis> ")) != NULL
) {
391 if (line
[0] != '\0') {
392 argv
= sdssplitargs(line
,&argc
);
393 linenoiseHistoryAdd(line
);
394 if (config
.historyfile
) linenoiseHistorySave(config
.historyfile
);
396 printf("Invalid argument(s)\n");
398 } else if (argc
> 0) {
399 if (strcasecmp(argv
[0],"quit") == 0 ||
400 strcasecmp(argv
[0],"exit") == 0)
404 long long start_time
= mstime(), elapsed
;
406 if (cliSendCommand(argc
,argv
,1) != REDIS_OK
) {
407 printf("Reconnecting... ");
409 if (cliConnect(1) != REDIS_OK
) exit(1);
412 /* If we still cannot send the command,
413 * print error and abort. */
414 if (cliSendCommand(argc
,argv
,1) != REDIS_OK
)
415 cliPrintContextErrorAndExit();
417 elapsed
= mstime()-start_time
;
418 if (elapsed
> 500) printf("%.2f seconds\n",
419 (double)elapsed
/1000);
422 /* Free the argument vector */
423 for (j
= 0; j
< argc
; j
++)
427 /* linenoise() returns malloc-ed lines like readline() */
433 static int noninteractive(int argc
, char **argv
) {
435 if (config
.stdinarg
) {
436 argv
= zrealloc(argv
, (argc
+1)*sizeof(char*));
437 argv
[argc
] = readArgFromStdin();
438 retval
= cliSendCommand(argc
+1, argv
, config
.repeat
);
440 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
441 retval
= cliSendCommand(argc
, argv
, config
.repeat
);
446 int main(int argc
, char **argv
) {
449 config
.hostip
= "127.0.0.1";
450 config
.hostport
= 6379;
451 config
.hostsocket
= NULL
;
454 config
.interactive
= 0;
456 config
.monitor_mode
= 0;
457 config
.pubsub_mode
= 0;
458 config
.raw_output
= 0;
461 config
.historyfile
= NULL
;
462 config
.tty
= isatty(fileno(stdout
)) || (getenv("FAKETTY") != NULL
);
463 config
.mb_sep
= '\n';
465 if (getenv("HOME") != NULL
) {
466 config
.historyfile
= malloc(256);
467 snprintf(config
.historyfile
,256,"%s/.rediscli_history",getenv("HOME"));
468 linenoiseHistoryLoad(config
.historyfile
);
471 firstarg
= parseOptions(argc
,argv
);
476 if (cliConnect(0) != REDIS_OK
) exit(1);
478 /* Start interactive mode when no command is provided */
479 if (argc
== 0) repl();
480 /* Otherwise, we have some arguments to execute */
481 return noninteractive(argc
,convertToSds(argc
,argv
));