]>
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.
47 #include "linenoise.h"
50 #define REDIS_NOTUSED(V) ((void) V)
52 #define OUTPUT_STANDARD 0
56 static redisContext
*context
;
57 static struct config
{
70 int cluster_reissue_command
;
72 int stdinarg
; /* get last arg from stdin. (-x option) */
74 int output
; /* output mode, see OUTPUT_* defines */
81 char *redisGitSHA1(void);
82 char *redisGitDirty(void);
84 /*------------------------------------------------------------------------------
86 *--------------------------------------------------------------------------- */
88 static long long mstime(void) {
92 gettimeofday(&tv
, NULL
);
93 mst
= ((long)tv
.tv_sec
)*1000;
94 mst
+= tv
.tv_usec
/1000;
98 static void cliRefreshPrompt(void) {
101 if (config
.hostsocket
!= NULL
)
102 len
= snprintf(config
.prompt
,sizeof(config
.prompt
),"redis %s",
105 len
= snprintf(config
.prompt
,sizeof(config
.prompt
),"redis %s:%d",
106 config
.hostip
, config
.hostport
);
107 /* Add [dbnum] if needed */
108 if (config
.dbnum
!= 0)
109 len
+= snprintf(config
.prompt
+len
,sizeof(config
.prompt
)-len
,"[%d]",
111 snprintf(config
.prompt
+len
,sizeof(config
.prompt
)-len
,"> ");
114 /*------------------------------------------------------------------------------
116 *--------------------------------------------------------------------------- */
118 #define CLI_HELP_COMMAND 1
119 #define CLI_HELP_GROUP 2
127 /* Only used for help on commands */
128 struct commandHelp
*org
;
131 static helpEntry
*helpEntries
;
132 static int helpEntriesLen
;
134 static sds
cliVersion() {
136 version
= sdscatprintf(sdsempty(), "%s", REDIS_VERSION
);
138 /* Add git commit and working tree status when available */
139 if (strtoll(redisGitSHA1(),NULL
,16)) {
140 version
= sdscatprintf(version
, " (git:%s", redisGitSHA1());
141 if (strtoll(redisGitDirty(),NULL
,10))
142 version
= sdscatprintf(version
, "-dirty");
143 version
= sdscat(version
, ")");
148 static void cliInitHelp() {
149 int commandslen
= sizeof(commandHelp
)/sizeof(struct commandHelp
);
150 int groupslen
= sizeof(commandGroups
)/sizeof(char*);
154 helpEntriesLen
= len
= commandslen
+groupslen
;
155 helpEntries
= malloc(sizeof(helpEntry
)*len
);
157 for (i
= 0; i
< groupslen
; i
++) {
159 tmp
.argv
= malloc(sizeof(sds
));
160 tmp
.argv
[0] = sdscatprintf(sdsempty(),"@%s",commandGroups
[i
]);
161 tmp
.full
= tmp
.argv
[0];
162 tmp
.type
= CLI_HELP_GROUP
;
164 helpEntries
[pos
++] = tmp
;
167 for (i
= 0; i
< commandslen
; i
++) {
168 tmp
.argv
= sdssplitargs(commandHelp
[i
].name
,&tmp
.argc
);
169 tmp
.full
= sdsnew(commandHelp
[i
].name
);
170 tmp
.type
= CLI_HELP_COMMAND
;
171 tmp
.org
= &commandHelp
[i
];
172 helpEntries
[pos
++] = tmp
;
176 /* Output command help to stdout. */
177 static void cliOutputCommandHelp(struct commandHelp
*help
, int group
) {
178 printf("\r\n \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\r\n", help
->name
, help
->params
);
179 printf(" \x1b[33msummary:\x1b[0m %s\r\n", help
->summary
);
180 printf(" \x1b[33msince:\x1b[0m %s\r\n", help
->since
);
182 printf(" \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups
[help
->group
]);
186 /* Print generic help. */
187 static void cliOutputGenericHelp() {
188 sds version
= cliVersion();
191 "Type: \"help @<group>\" to get a list of commands in <group>\r\n"
192 " \"help <command>\" for help on <command>\r\n"
193 " \"help <tab>\" to get a list of possible help topics\r\n"
194 " \"quit\" to exit\r\n",
200 /* Output all command help, filtering by group or command name. */
201 static void cliOutputHelp(int argc
, char **argv
) {
205 struct commandHelp
*help
;
208 cliOutputGenericHelp();
210 } else if (argc
> 0 && argv
[0][0] == '@') {
211 len
= sizeof(commandGroups
)/sizeof(char*);
212 for (i
= 0; i
< len
; i
++) {
213 if (strcasecmp(argv
[0]+1,commandGroups
[i
]) == 0) {
221 for (i
= 0; i
< helpEntriesLen
; i
++) {
222 entry
= &helpEntries
[i
];
223 if (entry
->type
!= CLI_HELP_COMMAND
) continue;
227 /* Compare all arguments */
228 if (argc
== entry
->argc
) {
229 for (j
= 0; j
< argc
; j
++) {
230 if (strcasecmp(argv
[j
],entry
->argv
[j
]) != 0) break;
233 cliOutputCommandHelp(help
,1);
237 if (group
== help
->group
) {
238 cliOutputCommandHelp(help
,0);
245 static void completionCallback(const char *buf
, linenoiseCompletions
*lc
) {
252 if (strncasecmp(buf
,"help ",5) == 0) {
254 while (isspace(buf
[startpos
])) startpos
++;
255 mask
= CLI_HELP_COMMAND
| CLI_HELP_GROUP
;
257 mask
= CLI_HELP_COMMAND
;
260 for (i
= 0; i
< helpEntriesLen
; i
++) {
261 if (!(helpEntries
[i
].type
& mask
)) continue;
263 matchlen
= strlen(buf
+startpos
);
264 if (strncasecmp(buf
+startpos
,helpEntries
[i
].full
,matchlen
) == 0) {
265 tmp
= sdsnewlen(buf
,startpos
);
266 tmp
= sdscat(tmp
,helpEntries
[i
].full
);
267 linenoiseAddCompletion(lc
,tmp
);
273 /*------------------------------------------------------------------------------
274 * Networking / parsing
275 *--------------------------------------------------------------------------- */
277 /* Send AUTH command to the server */
278 static int cliAuth() {
280 if (config
.auth
== NULL
) return REDIS_OK
;
282 reply
= redisCommand(context
,"AUTH %s",config
.auth
);
284 freeReplyObject(reply
);
290 /* Send SELECT dbnum to the server */
291 static int cliSelect() {
293 if (config
.dbnum
== 0) return REDIS_OK
;
295 reply
= redisCommand(context
,"SELECT %d",config
.dbnum
);
297 freeReplyObject(reply
);
303 /* Connect to the client. If force is not zero the connection is performed
304 * even if there is already a connected socket. */
305 static int cliConnect(int force
) {
306 if (context
== NULL
|| force
) {
310 if (config
.hostsocket
== NULL
) {
311 context
= redisConnect(config
.hostip
,config
.hostport
);
313 context
= redisConnectUnix(config
.hostsocket
);
317 fprintf(stderr
,"Could not connect to Redis at ");
318 if (config
.hostsocket
== NULL
)
319 fprintf(stderr
,"%s:%d: %s\n",config
.hostip
,config
.hostport
,context
->errstr
);
321 fprintf(stderr
,"%s: %s\n",config
.hostsocket
,context
->errstr
);
327 /* Do AUTH and select the right DB. */
328 if (cliAuth() != REDIS_OK
)
330 if (cliSelect() != REDIS_OK
)
336 static void cliPrintContextError() {
337 if (context
== NULL
) return;
338 fprintf(stderr
,"Error: %s\n",context
->errstr
);
341 static sds
cliFormatReplyTTY(redisReply
*r
, char *prefix
) {
342 sds out
= sdsempty();
344 case REDIS_REPLY_ERROR
:
345 out
= sdscatprintf(out
,"(error) %s\n", r
->str
);
347 case REDIS_REPLY_STATUS
:
348 out
= sdscat(out
,r
->str
);
349 out
= sdscat(out
,"\n");
351 case REDIS_REPLY_INTEGER
:
352 out
= sdscatprintf(out
,"(integer) %lld\n",r
->integer
);
354 case REDIS_REPLY_STRING
:
355 /* If you are producing output for the standard output we want
356 * a more interesting output with quoted characters and so forth */
357 out
= sdscatrepr(out
,r
->str
,r
->len
);
358 out
= sdscat(out
,"\n");
360 case REDIS_REPLY_NIL
:
361 out
= sdscat(out
,"(nil)\n");
363 case REDIS_REPLY_ARRAY
:
364 if (r
->elements
== 0) {
365 out
= sdscat(out
,"(empty list or set)\n");
367 unsigned int i
, idxlen
= 0;
373 /* Calculate chars needed to represent the largest index */
380 /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
381 memset(_prefixlen
,' ',idxlen
+2);
382 _prefixlen
[idxlen
+2] = '\0';
383 _prefix
= sdscat(sdsnew(prefix
),_prefixlen
);
385 /* Setup prefix format for every entry */
386 snprintf(_prefixfmt
,sizeof(_prefixfmt
),"%%s%%%dd) ",idxlen
);
388 for (i
= 0; i
< r
->elements
; i
++) {
389 /* Don't use the prefix for the first element, as the parent
390 * caller already prepended the index number. */
391 out
= sdscatprintf(out
,_prefixfmt
,i
== 0 ? "" : prefix
,i
+1);
393 /* Format the multi bulk entry */
394 tmp
= cliFormatReplyTTY(r
->element
[i
],_prefix
);
395 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
402 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
408 static sds
cliFormatReplyRaw(redisReply
*r
) {
409 sds out
= sdsempty(), tmp
;
413 case REDIS_REPLY_NIL
:
416 case REDIS_REPLY_ERROR
:
417 out
= sdscatlen(out
,r
->str
,r
->len
);
418 out
= sdscatlen(out
,"\n",1);
420 case REDIS_REPLY_STATUS
:
421 case REDIS_REPLY_STRING
:
422 out
= sdscatlen(out
,r
->str
,r
->len
);
424 case REDIS_REPLY_INTEGER
:
425 out
= sdscatprintf(out
,"%lld",r
->integer
);
427 case REDIS_REPLY_ARRAY
:
428 for (i
= 0; i
< r
->elements
; i
++) {
429 if (i
> 0) out
= sdscat(out
,config
.mb_delim
);
430 tmp
= cliFormatReplyRaw(r
->element
[i
]);
431 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
436 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
442 static sds
cliFormatReplyCSV(redisReply
*r
) {
445 sds out
= sdsempty();
447 case REDIS_REPLY_ERROR
:
448 out
= sdscat(out
,"ERROR,");
449 out
= sdscatrepr(out
,r
->str
,strlen(r
->str
));
451 case REDIS_REPLY_STATUS
:
452 out
= sdscatrepr(out
,r
->str
,r
->len
);
454 case REDIS_REPLY_INTEGER
:
455 out
= sdscatprintf(out
,"%lld",r
->integer
);
457 case REDIS_REPLY_STRING
:
458 out
= sdscatrepr(out
,r
->str
,r
->len
);
460 case REDIS_REPLY_NIL
:
461 out
= sdscat(out
,"NIL\n");
463 case REDIS_REPLY_ARRAY
:
464 for (i
= 0; i
< r
->elements
; i
++) {
465 sds tmp
= cliFormatReplyCSV(r
->element
[i
]);
466 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
467 if (i
!= r
->elements
-1) out
= sdscat(out
,",");
472 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
478 static int cliReadReply(int output_raw_strings
) {
484 if (redisGetReply(context
,&_reply
) != REDIS_OK
) {
487 if (config
.interactive
) {
488 /* Filter cases where we should reconnect */
489 if (context
->err
== REDIS_ERR_IO
&& errno
== ECONNRESET
)
491 if (context
->err
== REDIS_ERR_EOF
)
494 cliPrintContextError();
496 return REDIS_ERR
; /* avoid compiler warning */
499 reply
= (redisReply
*)_reply
;
501 /* Check if we need to connect to a different node and reissue the
503 if (config
.cluster_mode
&& reply
->type
== REDIS_REPLY_ERROR
&&
504 (!strncmp(reply
->str
,"MOVED",5) || !strcmp(reply
->str
,"ASK")))
506 char *p
= reply
->str
, *s
;
510 /* Comments show the position of the pointer as:
512 * [S] for pointer 's'
513 * [P] for pointer 'p'
515 s
= strchr(p
,' '); /* MOVED[S]3999 127.0.0.1:6381 */
516 p
= strchr(s
+1,' '); /* MOVED[S]3999[P]127.0.0.1:6381 */
519 s
= strchr(p
+1,':'); /* MOVED 3999[P]127.0.0.1[S]6381 */
521 sdsfree(config
.hostip
);
522 config
.hostip
= sdsnew(p
+1);
523 config
.hostport
= atoi(s
+1);
524 if (config
.interactive
)
525 printf("-> Redirected to slot [%d] located at %s:%d\n",
526 slot
, config
.hostip
, config
.hostport
);
527 config
.cluster_reissue_command
= 1;
531 if (output_raw_strings
) {
532 out
= cliFormatReplyRaw(reply
);
534 if (config
.output
== OUTPUT_RAW
) {
535 out
= cliFormatReplyRaw(reply
);
536 out
= sdscat(out
,"\n");
537 } else if (config
.output
== OUTPUT_STANDARD
) {
538 out
= cliFormatReplyTTY(reply
,"");
539 } else if (config
.output
== OUTPUT_CSV
) {
540 out
= cliFormatReplyCSV(reply
);
541 out
= sdscat(out
,"\n");
544 fwrite(out
,sdslen(out
),1,stdout
);
547 freeReplyObject(reply
);
551 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
552 char *command
= argv
[0];
556 if (!strcasecmp(command
,"help") || !strcasecmp(command
,"?")) {
557 cliOutputHelp(--argc
, ++argv
);
561 if (context
== NULL
) return REDIS_ERR
;
564 if (!strcasecmp(command
,"info") ||
565 (argc
== 2 && !strcasecmp(command
,"cluster") &&
566 (!strcasecmp(argv
[1],"nodes") ||
567 !strcasecmp(argv
[1],"info"))) ||
568 (argc
== 2 && !strcasecmp(command
,"client") &&
569 !strcasecmp(argv
[1],"list")))
575 if (!strcasecmp(command
,"shutdown")) config
.shutdown
= 1;
576 if (!strcasecmp(command
,"monitor")) config
.monitor_mode
= 1;
577 if (!strcasecmp(command
,"subscribe") ||
578 !strcasecmp(command
,"psubscribe")) config
.pubsub_mode
= 1;
580 /* Setup argument length */
581 argvlen
= malloc(argc
*sizeof(size_t));
582 for (j
= 0; j
< argc
; j
++)
583 argvlen
[j
] = sdslen(argv
[j
]);
586 redisAppendCommandArgv(context
,argc
,(const char**)argv
,argvlen
);
587 while (config
.monitor_mode
) {
588 if (cliReadReply(output_raw
) != REDIS_OK
) exit(1);
592 if (config
.pubsub_mode
) {
593 if (config
.output
!= OUTPUT_RAW
)
594 printf("Reading messages... (press Ctrl-C to quit)\n");
596 if (cliReadReply(output_raw
) != REDIS_OK
) exit(1);
600 if (cliReadReply(output_raw
) != REDIS_OK
) {
604 /* Store database number when SELECT was successfully executed. */
605 if (!strcasecmp(command
,"select") && argc
== 2) {
606 config
.dbnum
= atoi(argv
[1]);
610 if (config
.interval
) usleep(config
.interval
);
611 fflush(stdout
); /* Make it grep friendly */
618 /*------------------------------------------------------------------------------
620 *--------------------------------------------------------------------------- */
622 static int parseOptions(int argc
, char **argv
) {
625 for (i
= 1; i
< argc
; i
++) {
626 int lastarg
= i
==argc
-1;
628 if (!strcmp(argv
[i
],"-h") && !lastarg
) {
629 sdsfree(config
.hostip
);
630 config
.hostip
= sdsnew(argv
[++i
]);
631 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
633 } else if (!strcmp(argv
[i
],"--help")) {
635 } else if (!strcmp(argv
[i
],"-x")) {
637 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
638 config
.hostport
= atoi(argv
[++i
]);
639 } else if (!strcmp(argv
[i
],"-s") && !lastarg
) {
640 config
.hostsocket
= argv
[++i
];
641 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
642 config
.repeat
= strtoll(argv
[++i
],NULL
,10);
643 } else if (!strcmp(argv
[i
],"-i") && !lastarg
) {
644 double seconds
= atof(argv
[++i
]);
645 config
.interval
= seconds
*1000000;
646 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
647 config
.dbnum
= atoi(argv
[++i
]);
648 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
649 config
.auth
= argv
[++i
];
650 } else if (!strcmp(argv
[i
],"--raw")) {
651 config
.output
= OUTPUT_RAW
;
652 } else if (!strcmp(argv
[i
],"--csv")) {
653 config
.output
= OUTPUT_CSV
;
654 } else if (!strcmp(argv
[i
],"--latency")) {
655 config
.latency_mode
= 1;
656 } else if (!strcmp(argv
[i
],"--slave")) {
657 config
.slave_mode
= 1;
658 } else if (!strcmp(argv
[i
],"--eval") && !lastarg
) {
659 config
.eval
= argv
[++i
];
660 } else if (!strcmp(argv
[i
],"-c")) {
661 config
.cluster_mode
= 1;
662 } else if (!strcmp(argv
[i
],"-d") && !lastarg
) {
663 sdsfree(config
.mb_delim
);
664 config
.mb_delim
= sdsnew(argv
[++i
]);
665 } else if (!strcmp(argv
[i
],"-v") || !strcmp(argv
[i
], "--version")) {
666 sds version
= cliVersion();
667 printf("redis-cli %s\n", version
);
677 static sds
readArgFromStdin(void) {
679 sds arg
= sdsempty();
682 int nread
= read(fileno(stdin
),buf
,1024);
684 if (nread
== 0) break;
685 else if (nread
== -1) {
686 perror("Reading from standard input");
689 arg
= sdscatlen(arg
,buf
,nread
);
694 static void usage() {
695 sds version
= cliVersion();
699 "Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n"
700 " -h <hostname> Server hostname (default: 127.0.0.1)\n"
701 " -p <port> Server port (default: 6379)\n"
702 " -s <socket> Server socket (overrides hostname and port)\n"
703 " -a <password> Password to use when connecting to the server\n"
704 " -r <repeat> Execute specified command N times\n"
705 " -i <interval> When -r is used, waits <interval> seconds per command.\n"
706 " It is possible to specify sub-second times like -i 0.1.\n"
707 " -n <db> Database number\n"
708 " -x Read last argument from STDIN\n"
709 " -d <delimiter> Multi-bulk delimiter in for raw formatting (default: \\n)\n"
710 " -c Enable cluster mode (follow -ASK and -MOVED redirections)\n"
711 " --raw Use raw formatting for replies (default when STDOUT is not a tty)\n"
712 " --latency Enter a special mode continuously sampling latency.\n"
713 " --slave Simulate a slave showing commands received from the master.\n"
714 " --eval <file> Send an EVAL command using the Lua script at <file>.\n"
715 " --help Output this help and exit\n"
716 " --version Output version and exit\n"
719 " cat /etc/passwd | redis-cli -x set mypasswd\n"
720 " redis-cli get mypasswd\n"
721 " redis-cli -r 100 lpush mylist x\n"
722 " redis-cli -r 100 -i 1 info | grep used_memory_human:\n"
723 " redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3\n"
724 " (Note: when using --eval the comma separates KEYS[] from ARGV[] items)\n"
726 "When no command is given, redis-cli starts in interactive mode.\n"
727 "Type \"help\" in interactive mode for information on available commands.\n"
734 /* Turn the plain C strings into Sds strings */
735 static char **convertToSds(int count
, char** args
) {
737 char **sds
= zmalloc(sizeof(char*)*count
);
739 for(j
= 0; j
< count
; j
++)
740 sds
[j
] = sdsnew(args
[j
]);
745 #define LINE_BUFLEN 4096
747 sds historyfile
= NULL
;
753 config
.interactive
= 1;
754 linenoiseSetCompletionCallback(completionCallback
);
756 /* Only use history when stdin is a tty. */
757 if (isatty(fileno(stdin
))) {
760 if (getenv("HOME") != NULL
) {
761 historyfile
= sdscatprintf(sdsempty(),"%s/.rediscli_history",getenv("HOME"));
762 linenoiseHistoryLoad(historyfile
);
767 while((line
= linenoise(context
? config
.prompt
: "not connected> ")) != NULL
) {
768 if (line
[0] != '\0') {
769 argv
= sdssplitargs(line
,&argc
);
770 if (history
) linenoiseHistoryAdd(line
);
771 if (historyfile
) linenoiseHistorySave(historyfile
);
774 printf("Invalid argument(s)\n");
777 } else if (argc
> 0) {
778 if (strcasecmp(argv
[0],"quit") == 0 ||
779 strcasecmp(argv
[0],"exit") == 0)
782 } else if (argc
== 3 && !strcasecmp(argv
[0],"connect")) {
783 sdsfree(config
.hostip
);
784 config
.hostip
= sdsnew(argv
[1]);
785 config
.hostport
= atoi(argv
[2]);
787 } else if (argc
== 1 && !strcasecmp(argv
[0],"clear")) {
788 linenoiseClearScreen();
790 long long start_time
= mstime(), elapsed
;
791 int repeat
, skipargs
= 0;
793 repeat
= atoi(argv
[0]);
794 if (argc
> 1 && repeat
) {
801 config
.cluster_reissue_command
= 0;
802 if (cliSendCommand(argc
-skipargs
,argv
+skipargs
,repeat
)
807 /* If we still cannot send the command print error.
808 * We'll try to reconnect the next time. */
809 if (cliSendCommand(argc
-skipargs
,argv
+skipargs
,repeat
)
811 cliPrintContextError();
813 /* Issue the command again if we got redirected in cluster mode */
814 if (config
.cluster_mode
&& config
.cluster_reissue_command
) {
820 elapsed
= mstime()-start_time
;
821 if (elapsed
>= 500) {
822 printf("(%.2fs)\n",(double)elapsed
/1000);
826 /* Free the argument vector */
827 while(argc
--) sdsfree(argv
[argc
]);
830 /* linenoise() returns malloc-ed lines like readline() */
836 static int noninteractive(int argc
, char **argv
) {
838 if (config
.stdinarg
) {
839 argv
= zrealloc(argv
, (argc
+1)*sizeof(char*));
840 argv
[argc
] = readArgFromStdin();
841 retval
= cliSendCommand(argc
+1, argv
, config
.repeat
);
843 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
844 retval
= cliSendCommand(argc
, argv
, config
.repeat
);
849 static int evalMode(int argc
, char **argv
) {
850 sds script
= sdsempty();
855 int j
, got_comma
= 0, keys
= 0;
857 /* Load the script from the file, as an sds string. */
858 fp
= fopen(config
.eval
,"r");
861 "Can't open file '%s': %s\n", config
.eval
, strerror(errno
));
864 while((nread
= fread(buf
,1,sizeof(buf
),fp
)) != 0) {
865 script
= sdscatlen(script
,buf
,nread
);
869 /* Create our argument vector */
870 argv2
= zmalloc(sizeof(sds
)*(argc
+3));
871 argv2
[0] = sdsnew("EVAL");
873 for (j
= 0; j
< argc
; j
++) {
874 if (!got_comma
&& argv
[j
][0] == ',' && argv
[j
][1] == 0) {
878 argv2
[j
+3-got_comma
] = sdsnew(argv
[j
]);
879 if (!got_comma
) keys
++;
881 argv2
[2] = sdscatprintf(sdsempty(),"%d",keys
);
884 return cliSendCommand(argc
+3-got_comma
, argv2
, config
.repeat
);
887 static void latencyMode(void) {
889 long long start
, latency
, min
, max
, tot
, count
= 0;
892 if (!context
) exit(1);
895 reply
= redisCommand(context
,"PING");
897 fprintf(stderr
,"\nI/O error\n");
900 latency
= mstime()-start
;
901 freeReplyObject(reply
);
904 min
= max
= tot
= latency
;
905 avg
= (double) latency
;
907 if (latency
< min
) min
= latency
;
908 if (latency
> max
) max
= latency
;
910 avg
= (double) tot
/count
;
912 printf("\x1b[0G\x1b[2Kmin: %lld, max: %lld, avg: %.2f (%lld samples)",
913 min
, max
, avg
, count
);
919 static void slaveMode(void) {
920 /* To start we need to send the SYNC command and return the payload.
921 * The hiredis client lib does not understand this part of the protocol
922 * and we don't want to mess with its buffers, so everything is performed
923 * using direct low-level I/O. */
924 int fd
= context
->fd
;
927 unsigned long long payload
;
929 /* Send the SYNC command. */
930 if (write(fd
,"SYNC\r\n",6) != 6) {
931 fprintf(stderr
,"Error writing to master\n");
935 /* Read $<payload>\r\n, making sure to read just up to "\n" */
938 nread
= read(fd
,p
,1);
940 fprintf(stderr
,"Error reading bulk length while SYNCing\n");
943 if (*p
== '\n') break;
947 payload
= strtoull(buf
+1,NULL
,10);
948 fprintf(stderr
,"SYNC with master, discarding %lld bytes of bulk tranfer...\n",
951 /* Discard the payload. */
953 nread
= read(fd
,buf
,(payload
> sizeof(buf
)) ? sizeof(buf
) : payload
);
955 fprintf(stderr
,"Error reading RDB payload while SYNCing\n");
960 fprintf(stderr
,"SYNC done. Logging commands from master.\n");
962 /* Now we can use the hiredis to read the incoming protocol. */
963 config
.output
= OUTPUT_CSV
;
964 while (cliReadReply(0) == REDIS_OK
);
967 int main(int argc
, char **argv
) {
970 config
.hostip
= sdsnew("127.0.0.1");
971 config
.hostport
= 6379;
972 config
.hostsocket
= NULL
;
976 config
.interactive
= 0;
978 config
.monitor_mode
= 0;
979 config
.pubsub_mode
= 0;
980 config
.latency_mode
= 0;
981 config
.cluster_mode
= 0;
985 if (!isatty(fileno(stdout
)) && (getenv("FAKETTY") == NULL
))
986 config
.output
= OUTPUT_RAW
;
988 config
.output
= OUTPUT_STANDARD
;
989 config
.mb_delim
= sdsnew("\n");
992 firstarg
= parseOptions(argc
,argv
);
996 /* Start in latency mode if appropriate */
997 if (config
.latency_mode
) {
1002 /* Start in slave mode if appropriate */
1003 if (config
.slave_mode
) {
1008 /* Start interactive mode when no command is provided */
1009 if (argc
== 0 && !config
.eval
) {
1010 /* Note that in repl mode we don't abort on connection error.
1011 * A new attempt will be performed for every command send. */
1016 /* Otherwise, we have some arguments to execute */
1017 if (cliConnect(0) != REDIS_OK
) exit(1);
1019 return evalMode(argc
,argv
);
1021 return noninteractive(argc
,convertToSds(argc
,argv
));