]>
git.saurik.com Git - redis.git/blob - src/redis-cli.c
5f01a936e0d5851fbdd2a64602f0ede0d5789cd6
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 /*------------------------------------------------------------------------------
88 * Networking / parsing
89 *--------------------------------------------------------------------------- */
91 /* Send AUTH command to the server */
92 static int cliAuth() {
94 if (config
.auth
== NULL
) return REDIS_OK
;
96 reply
= redisCommand(context
,"AUTH %s",config
.auth
);
98 freeReplyObject(reply
);
104 /* Send SELECT dbnum to the server */
105 static int cliSelect() {
108 if (config
.dbnum
== 0) return REDIS_OK
;
110 snprintf(dbnum
,sizeof(dbnum
),"%d",config
.dbnum
);
111 reply
= redisCommand(context
,"SELECT %s",dbnum
);
113 freeReplyObject(reply
);
119 /* Connect to the client. If force is not zero the connection is performed
120 * even if there is already a connected socket. */
121 static int cliConnect(int force
) {
122 if (context
== NULL
|| force
) {
126 if (config
.hostsocket
== NULL
) {
127 context
= redisConnect(config
.hostip
,config
.hostport
);
129 context
= redisConnectUnix(config
.hostsocket
);
133 fprintf(stderr
,"Could not connect to Redis at ");
134 if (config
.hostsocket
== NULL
)
135 fprintf(stderr
,"%s:%d: %s\n",config
.hostip
,config
.hostport
,context
->errstr
);
137 fprintf(stderr
,"%s: %s\n",config
.hostsocket
,context
->errstr
);
143 /* Do AUTH and select the right DB. */
144 if (cliAuth() != REDIS_OK
)
146 if (cliSelect() != REDIS_OK
)
152 static void cliPrintContextErrorAndExit() {
153 if (context
== NULL
) return;
154 fprintf(stderr
,"Error: %s\n",context
->errstr
);
158 static sds
cliFormatReply(redisReply
*r
, char *prefix
) {
159 sds out
= sdsempty();
161 case REDIS_REPLY_ERROR
:
162 if (config
.tty
) out
= sdscat(out
,"(error) ");
163 out
= sdscatprintf(out
,"%s\n", r
->str
);
165 case REDIS_REPLY_STATUS
:
166 out
= sdscat(out
,r
->str
);
167 out
= sdscat(out
,"\n");
169 case REDIS_REPLY_INTEGER
:
170 if (config
.tty
) out
= sdscat(out
,"(integer) ");
171 out
= sdscatprintf(out
,"%lld\n",r
->integer
);
173 case REDIS_REPLY_STRING
:
174 if (config
.raw_output
|| !config
.tty
) {
175 out
= sdscatlen(out
,r
->str
,r
->len
);
177 /* If you are producing output for the standard output we want
178 * a more interesting output with quoted characters and so forth */
179 out
= sdscatrepr(out
,r
->str
,r
->len
);
180 out
= sdscat(out
,"\n");
183 case REDIS_REPLY_NIL
:
184 out
= sdscat(out
,"(nil)\n");
186 case REDIS_REPLY_ARRAY
:
187 if (r
->elements
== 0) {
188 out
= sdscat(out
,"(empty list or set)\n");
190 unsigned int i
, idxlen
= 0;
196 /* Calculate chars needed to represent the largest index */
203 /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
204 memset(_prefixlen
,' ',idxlen
+2);
205 _prefixlen
[idxlen
+2] = '\0';
206 _prefix
= sdscat(sdsnew(prefix
),_prefixlen
);
208 /* Setup prefix format for every entry */
209 snprintf(_prefixfmt
,sizeof(_prefixfmt
),"%%s%%%dd) ",idxlen
);
211 for (i
= 0; i
< r
->elements
; i
++) {
212 /* Don't use the prefix for the first element, as the parent
213 * caller already prepended the index number. */
214 out
= sdscatprintf(out
,_prefixfmt
,i
== 0 ? "" : prefix
,i
+1);
216 /* Format the multi bulk entry */
217 tmp
= cliFormatReply(r
->element
[i
],_prefix
);
218 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
225 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
231 static int cliReadReply() {
235 if (redisGetReply(context
,(void**)&reply
) != REDIS_OK
) {
238 if (config
.interactive
) {
239 /* Filter cases where we should reconnect */
240 if (context
->err
== REDIS_ERR_IO
&& errno
== ECONNRESET
)
242 if (context
->err
== REDIS_ERR_EOF
)
245 cliPrintContextErrorAndExit();
246 return REDIS_ERR
; /* avoid compiler warning */
249 out
= cliFormatReply(reply
,"");
250 freeReplyObject(reply
);
251 fwrite(out
,sdslen(out
),1,stdout
);
256 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
257 char *command
= argv
[0];
261 config
.raw_output
= !strcasecmp(command
,"info");
262 if (!strcasecmp(command
,"help")) {
263 output_help(--argc
, ++argv
);
266 if (!strcasecmp(command
,"shutdown")) config
.shutdown
= 1;
267 if (!strcasecmp(command
,"monitor")) config
.monitor_mode
= 1;
268 if (!strcasecmp(command
,"subscribe") ||
269 !strcasecmp(command
,"psubscribe")) config
.pubsub_mode
= 1;
271 /* Setup argument length */
272 argvlen
= malloc(argc
*sizeof(size_t));
273 for (j
= 0; j
< argc
; j
++)
274 argvlen
[j
] = sdslen(argv
[j
]);
277 redisAppendCommandArgv(context
,argc
,(const char**)argv
,argvlen
);
278 while (config
.monitor_mode
) {
279 if (cliReadReply() != REDIS_OK
) exit(1);
283 if (config
.pubsub_mode
) {
284 printf("Reading messages... (press Ctrl-C to quit)\n");
286 if (cliReadReply() != REDIS_OK
) exit(1);
290 if (cliReadReply() != REDIS_OK
)
296 /*------------------------------------------------------------------------------
298 *--------------------------------------------------------------------------- */
300 static int parseOptions(int argc
, char **argv
) {
303 for (i
= 1; i
< argc
; i
++) {
304 int lastarg
= i
==argc
-1;
306 if (!strcmp(argv
[i
],"-h") && !lastarg
) {
307 config
.hostip
= argv
[i
+1];
309 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
311 } else if (!strcmp(argv
[i
],"-x")) {
313 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
314 config
.hostport
= atoi(argv
[i
+1]);
316 } else if (!strcmp(argv
[i
],"-s") && !lastarg
) {
317 config
.hostsocket
= argv
[i
+1];
319 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
320 config
.repeat
= strtoll(argv
[i
+1],NULL
,10);
322 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
323 config
.dbnum
= atoi(argv
[i
+1]);
325 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
326 config
.auth
= argv
[i
+1];
328 } else if (!strcmp(argv
[i
],"-i")) {
330 "Starting interactive mode using -i is deprecated. Interactive mode is started\n"
331 "by default when redis-cli is executed without a command to execute.\n"
333 } else if (!strcmp(argv
[i
],"-c")) {
335 "Reading last argument from standard input using -c is deprecated.\n"
336 "When standard input is connected to a pipe or regular file, it is\n"
337 "automatically used as last argument.\n"
339 } else if (!strcmp(argv
[i
],"-v")) {
340 printf("redis-cli shipped with Redis version %s (%s)\n", REDIS_VERSION
, redisGitSHA1());
349 static sds
readArgFromStdin(void) {
351 sds arg
= sdsempty();
354 int nread
= read(fileno(stdin
),buf
,1024);
356 if (nread
== 0) break;
357 else if (nread
== -1) {
358 perror("Reading from standard input");
361 arg
= sdscatlen(arg
,buf
,nread
);
366 static void usage() {
367 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");
368 fprintf(stderr
, "usage: echo \"argN\" | redis-cli -x [options] cmd arg1 arg2 ... arg(N-1)\n\n");
369 fprintf(stderr
, "example: cat /etc/passwd | redis-cli -x set my_passwd\n");
370 fprintf(stderr
, "example: redis-cli get my_passwd\n");
371 fprintf(stderr
, "example: redis-cli -r 100 lpush mylist x\n");
372 fprintf(stderr
, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
376 /* Turn the plain C strings into Sds strings */
377 static char **convertToSds(int count
, char** args
) {
379 char **sds
= zmalloc(sizeof(char*)*count
);
381 for(j
= 0; j
< count
; j
++)
382 sds
[j
] = sdsnew(args
[j
]);
387 #define LINE_BUFLEN 4096
393 config
.interactive
= 1;
394 while((line
= linenoise("redis> ")) != NULL
) {
395 if (line
[0] != '\0') {
396 argv
= sdssplitargs(line
,&argc
);
397 linenoiseHistoryAdd(line
);
398 if (config
.historyfile
) linenoiseHistorySave(config
.historyfile
);
400 printf("Invalid argument(s)\n");
402 } else if (argc
> 0) {
403 if (strcasecmp(argv
[0],"quit") == 0 ||
404 strcasecmp(argv
[0],"exit") == 0)
408 long long start_time
= mstime(), elapsed
;
410 if (cliSendCommand(argc
,argv
,1) != REDIS_OK
) {
411 printf("Reconnecting... ");
413 if (cliConnect(1) != REDIS_OK
) exit(1);
416 /* If we still cannot send the command,
417 * print error and abort. */
418 if (cliSendCommand(argc
,argv
,1) != REDIS_OK
)
419 cliPrintContextErrorAndExit();
421 elapsed
= mstime()-start_time
;
422 if (elapsed
>= 500) {
423 printf("(%.2fs)\n",(double)elapsed
/1000);
427 /* Free the argument vector */
428 for (j
= 0; j
< argc
; j
++)
432 /* linenoise() returns malloc-ed lines like readline() */
438 static int noninteractive(int argc
, char **argv
) {
440 if (config
.stdinarg
) {
441 argv
= zrealloc(argv
, (argc
+1)*sizeof(char*));
442 argv
[argc
] = readArgFromStdin();
443 retval
= cliSendCommand(argc
+1, argv
, config
.repeat
);
445 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
446 retval
= cliSendCommand(argc
, argv
, config
.repeat
);
451 int main(int argc
, char **argv
) {
454 config
.hostip
= "127.0.0.1";
455 config
.hostport
= 6379;
456 config
.hostsocket
= NULL
;
459 config
.interactive
= 0;
461 config
.monitor_mode
= 0;
462 config
.pubsub_mode
= 0;
463 config
.raw_output
= 0;
466 config
.historyfile
= NULL
;
467 config
.tty
= isatty(fileno(stdout
)) || (getenv("FAKETTY") != NULL
);
468 config
.mb_sep
= '\n';
470 if (getenv("HOME") != NULL
) {
471 config
.historyfile
= malloc(256);
472 snprintf(config
.historyfile
,256,"%s/.rediscli_history",getenv("HOME"));
473 linenoiseHistoryLoad(config
.historyfile
);
476 firstarg
= parseOptions(argc
,argv
);
481 if (cliConnect(0) != REDIS_OK
) exit(1);
483 /* Start interactive mode when no command is provided */
484 if (argc
== 0) repl();
485 /* Otherwise, we have some arguments to execute */
486 return noninteractive(argc
,convertToSds(argc
,argv
));