]>
git.saurik.com Git - redis.git/blob - src/redis-cli.c
3b3ef50442e614d5ce109f4a944512b0c5dbdd0a
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 static redisContext
*context
;
53 static struct config
{
66 int cluster_reissue_command
;
68 int stdinarg
; /* get last arg from stdin. (-x option) */
70 int raw_output
; /* output mode per command */
77 char *redisGitSHA1(void);
78 char *redisGitDirty(void);
80 /*------------------------------------------------------------------------------
82 *--------------------------------------------------------------------------- */
84 static long long mstime(void) {
88 gettimeofday(&tv
, NULL
);
89 mst
= ((long)tv
.tv_sec
)*1000;
90 mst
+= tv
.tv_usec
/1000;
94 static void cliRefreshPrompt(void) {
97 if (config
.hostsocket
!= NULL
)
98 len
= snprintf(config
.prompt
,sizeof(config
.prompt
),"redis %s",
101 len
= snprintf(config
.prompt
,sizeof(config
.prompt
),"redis %s:%d",
102 config
.hostip
, config
.hostport
);
103 /* Add [dbnum] if needed */
104 if (config
.dbnum
!= 0)
105 len
+= snprintf(config
.prompt
+len
,sizeof(config
.prompt
)-len
,"[%d]",
107 snprintf(config
.prompt
+len
,sizeof(config
.prompt
)-len
,"> ");
110 /*------------------------------------------------------------------------------
112 *--------------------------------------------------------------------------- */
114 #define CLI_HELP_COMMAND 1
115 #define CLI_HELP_GROUP 2
123 /* Only used for help on commands */
124 struct commandHelp
*org
;
127 static helpEntry
*helpEntries
;
128 static int helpEntriesLen
;
130 static sds
cliVersion() {
132 version
= sdscatprintf(sdsempty(), "%s", REDIS_VERSION
);
134 /* Add git commit and working tree status when available */
135 if (strtoll(redisGitSHA1(),NULL
,16)) {
136 version
= sdscatprintf(version
, " (git:%s", redisGitSHA1());
137 if (strtoll(redisGitDirty(),NULL
,10))
138 version
= sdscatprintf(version
, "-dirty");
139 version
= sdscat(version
, ")");
144 static void cliInitHelp() {
145 int commandslen
= sizeof(commandHelp
)/sizeof(struct commandHelp
);
146 int groupslen
= sizeof(commandGroups
)/sizeof(char*);
150 helpEntriesLen
= len
= commandslen
+groupslen
;
151 helpEntries
= malloc(sizeof(helpEntry
)*len
);
153 for (i
= 0; i
< groupslen
; i
++) {
155 tmp
.argv
= malloc(sizeof(sds
));
156 tmp
.argv
[0] = sdscatprintf(sdsempty(),"@%s",commandGroups
[i
]);
157 tmp
.full
= tmp
.argv
[0];
158 tmp
.type
= CLI_HELP_GROUP
;
160 helpEntries
[pos
++] = tmp
;
163 for (i
= 0; i
< commandslen
; i
++) {
164 tmp
.argv
= sdssplitargs(commandHelp
[i
].name
,&tmp
.argc
);
165 tmp
.full
= sdsnew(commandHelp
[i
].name
);
166 tmp
.type
= CLI_HELP_COMMAND
;
167 tmp
.org
= &commandHelp
[i
];
168 helpEntries
[pos
++] = tmp
;
172 /* Output command help to stdout. */
173 static void cliOutputCommandHelp(struct commandHelp
*help
, int group
) {
174 printf("\r\n \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\r\n", help
->name
, help
->params
);
175 printf(" \x1b[33msummary:\x1b[0m %s\r\n", help
->summary
);
176 printf(" \x1b[33msince:\x1b[0m %s\r\n", help
->since
);
178 printf(" \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups
[help
->group
]);
182 /* Print generic help. */
183 static void cliOutputGenericHelp() {
184 sds version
= cliVersion();
187 "Type: \"help @<group>\" to get a list of commands in <group>\r\n"
188 " \"help <command>\" for help on <command>\r\n"
189 " \"help <tab>\" to get a list of possible help topics\r\n"
190 " \"quit\" to exit\r\n",
196 /* Output all command help, filtering by group or command name. */
197 static void cliOutputHelp(int argc
, char **argv
) {
201 struct commandHelp
*help
;
204 cliOutputGenericHelp();
206 } else if (argc
> 0 && argv
[0][0] == '@') {
207 len
= sizeof(commandGroups
)/sizeof(char*);
208 for (i
= 0; i
< len
; i
++) {
209 if (strcasecmp(argv
[0]+1,commandGroups
[i
]) == 0) {
217 for (i
= 0; i
< helpEntriesLen
; i
++) {
218 entry
= &helpEntries
[i
];
219 if (entry
->type
!= CLI_HELP_COMMAND
) continue;
223 /* Compare all arguments */
224 if (argc
== entry
->argc
) {
225 for (j
= 0; j
< argc
; j
++) {
226 if (strcasecmp(argv
[j
],entry
->argv
[j
]) != 0) break;
229 cliOutputCommandHelp(help
,1);
233 if (group
== help
->group
) {
234 cliOutputCommandHelp(help
,0);
241 static void completionCallback(const char *buf
, linenoiseCompletions
*lc
) {
248 if (strncasecmp(buf
,"help ",5) == 0) {
250 while (isspace(buf
[startpos
])) startpos
++;
251 mask
= CLI_HELP_COMMAND
| CLI_HELP_GROUP
;
253 mask
= CLI_HELP_COMMAND
;
256 for (i
= 0; i
< helpEntriesLen
; i
++) {
257 if (!(helpEntries
[i
].type
& mask
)) continue;
259 matchlen
= strlen(buf
+startpos
);
260 if (strncasecmp(buf
+startpos
,helpEntries
[i
].full
,matchlen
) == 0) {
261 tmp
= sdsnewlen(buf
,startpos
);
262 tmp
= sdscat(tmp
,helpEntries
[i
].full
);
263 linenoiseAddCompletion(lc
,tmp
);
269 /*------------------------------------------------------------------------------
270 * Networking / parsing
271 *--------------------------------------------------------------------------- */
273 /* Send AUTH command to the server */
274 static int cliAuth() {
276 if (config
.auth
== NULL
) return REDIS_OK
;
278 reply
= redisCommand(context
,"AUTH %s",config
.auth
);
280 freeReplyObject(reply
);
286 /* Send SELECT dbnum to the server */
287 static int cliSelect() {
289 if (config
.dbnum
== 0) return REDIS_OK
;
291 reply
= redisCommand(context
,"SELECT %d",config
.dbnum
);
293 freeReplyObject(reply
);
299 /* Connect to the client. If force is not zero the connection is performed
300 * even if there is already a connected socket. */
301 static int cliConnect(int force
) {
302 if (context
== NULL
|| force
) {
306 if (config
.hostsocket
== NULL
) {
307 context
= redisConnect(config
.hostip
,config
.hostport
);
309 context
= redisConnectUnix(config
.hostsocket
);
313 fprintf(stderr
,"Could not connect to Redis at ");
314 if (config
.hostsocket
== NULL
)
315 fprintf(stderr
,"%s:%d: %s\n",config
.hostip
,config
.hostport
,context
->errstr
);
317 fprintf(stderr
,"%s: %s\n",config
.hostsocket
,context
->errstr
);
323 /* Do AUTH and select the right DB. */
324 if (cliAuth() != REDIS_OK
)
326 if (cliSelect() != REDIS_OK
)
332 static void cliPrintContextError() {
333 if (context
== NULL
) return;
334 fprintf(stderr
,"Error: %s\n",context
->errstr
);
337 static sds
cliFormatReplyTTY(redisReply
*r
, char *prefix
) {
338 sds out
= sdsempty();
340 case REDIS_REPLY_ERROR
:
341 out
= sdscatprintf(out
,"(error) %s\n", r
->str
);
343 case REDIS_REPLY_STATUS
:
344 out
= sdscat(out
,r
->str
);
345 out
= sdscat(out
,"\n");
347 case REDIS_REPLY_INTEGER
:
348 out
= sdscatprintf(out
,"(integer) %lld\n",r
->integer
);
350 case REDIS_REPLY_STRING
:
351 /* If you are producing output for the standard output we want
352 * a more interesting output with quoted characters and so forth */
353 out
= sdscatrepr(out
,r
->str
,r
->len
);
354 out
= sdscat(out
,"\n");
356 case REDIS_REPLY_NIL
:
357 out
= sdscat(out
,"(nil)\n");
359 case REDIS_REPLY_ARRAY
:
360 if (r
->elements
== 0) {
361 out
= sdscat(out
,"(empty list or set)\n");
363 unsigned int i
, idxlen
= 0;
369 /* Calculate chars needed to represent the largest index */
376 /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
377 memset(_prefixlen
,' ',idxlen
+2);
378 _prefixlen
[idxlen
+2] = '\0';
379 _prefix
= sdscat(sdsnew(prefix
),_prefixlen
);
381 /* Setup prefix format for every entry */
382 snprintf(_prefixfmt
,sizeof(_prefixfmt
),"%%s%%%dd) ",idxlen
);
384 for (i
= 0; i
< r
->elements
; i
++) {
385 /* Don't use the prefix for the first element, as the parent
386 * caller already prepended the index number. */
387 out
= sdscatprintf(out
,_prefixfmt
,i
== 0 ? "" : prefix
,i
+1);
389 /* Format the multi bulk entry */
390 tmp
= cliFormatReplyTTY(r
->element
[i
],_prefix
);
391 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
398 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
404 static sds
cliFormatReplyRaw(redisReply
*r
) {
405 sds out
= sdsempty(), tmp
;
409 case REDIS_REPLY_NIL
:
412 case REDIS_REPLY_ERROR
:
413 out
= sdscatlen(out
,r
->str
,r
->len
);
414 out
= sdscatlen(out
,"\n",1);
416 case REDIS_REPLY_STATUS
:
417 case REDIS_REPLY_STRING
:
418 out
= sdscatlen(out
,r
->str
,r
->len
);
420 case REDIS_REPLY_INTEGER
:
421 out
= sdscatprintf(out
,"%lld",r
->integer
);
423 case REDIS_REPLY_ARRAY
:
424 for (i
= 0; i
< r
->elements
; i
++) {
425 if (i
> 0) out
= sdscat(out
,config
.mb_delim
);
426 tmp
= cliFormatReplyRaw(r
->element
[i
]);
427 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
432 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
438 static int cliReadReply(int output_raw_strings
) {
444 if (redisGetReply(context
,&_reply
) != REDIS_OK
) {
447 if (config
.interactive
) {
448 /* Filter cases where we should reconnect */
449 if (context
->err
== REDIS_ERR_IO
&& errno
== ECONNRESET
)
451 if (context
->err
== REDIS_ERR_EOF
)
454 cliPrintContextError();
456 return REDIS_ERR
; /* avoid compiler warning */
459 reply
= (redisReply
*)_reply
;
461 /* Check if we need to connect to a different node and reissue the request. */
462 if (config
.cluster_mode
&& reply
->type
== REDIS_REPLY_ERROR
&&
463 (!strncmp(reply
->str
,"MOVED",5) || !strcmp(reply
->str
,"ASK")))
465 char *p
= reply
->str
, *s
;
469 /* Comments show the position of the pointer as:
471 * [S] for pointer 's'
472 * [P] for pointer 'p'
474 s
= strchr(p
,' '); /* MOVED[S]3999 127.0.0.1:6381 */
475 p
= strchr(s
+1,' '); /* MOVED[S]3999[P]127.0.0.1:6381 */
478 s
= strchr(p
+1,':'); /* MOVED 3999[P]127.0.0.1[S]6381 */
480 sdsfree(config
.hostip
);
481 config
.hostip
= sdsnew(p
+1);
482 config
.hostport
= atoi(s
+1);
483 if (config
.interactive
)
484 printf("-> Redirected to slot [%d] located at %s:%d\n",
485 slot
, config
.hostip
, config
.hostport
);
486 config
.cluster_reissue_command
= 1;
490 if (output_raw_strings
) {
491 out
= cliFormatReplyRaw(reply
);
493 if (config
.raw_output
) {
494 out
= cliFormatReplyRaw(reply
);
495 out
= sdscat(out
,"\n");
497 out
= cliFormatReplyTTY(reply
,"");
500 fwrite(out
,sdslen(out
),1,stdout
);
503 freeReplyObject(reply
);
507 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
508 char *command
= argv
[0];
512 if (!strcasecmp(command
,"help") || !strcasecmp(command
,"?")) {
513 cliOutputHelp(--argc
, ++argv
);
517 if (context
== NULL
) return REDIS_ERR
;
520 if (!strcasecmp(command
,"info") ||
521 (argc
== 2 && !strcasecmp(command
,"cluster") &&
522 (!strcasecmp(argv
[1],"nodes") ||
523 !strcasecmp(argv
[1],"info"))) ||
524 (argc
== 2 && !strcasecmp(command
,"client") &&
525 !strcasecmp(argv
[1],"list")))
531 if (!strcasecmp(command
,"shutdown")) config
.shutdown
= 1;
532 if (!strcasecmp(command
,"monitor")) config
.monitor_mode
= 1;
533 if (!strcasecmp(command
,"subscribe") ||
534 !strcasecmp(command
,"psubscribe")) config
.pubsub_mode
= 1;
536 /* Setup argument length */
537 argvlen
= malloc(argc
*sizeof(size_t));
538 for (j
= 0; j
< argc
; j
++)
539 argvlen
[j
] = sdslen(argv
[j
]);
542 redisAppendCommandArgv(context
,argc
,(const char**)argv
,argvlen
);
543 while (config
.monitor_mode
) {
544 if (cliReadReply(output_raw
) != REDIS_OK
) exit(1);
548 if (config
.pubsub_mode
) {
549 if (!config
.raw_output
)
550 printf("Reading messages... (press Ctrl-C to quit)\n");
552 if (cliReadReply(output_raw
) != REDIS_OK
) exit(1);
556 if (cliReadReply(output_raw
) != REDIS_OK
) {
560 /* Store database number when SELECT was successfully executed. */
561 if (!strcasecmp(command
,"select") && argc
== 2) {
562 config
.dbnum
= atoi(argv
[1]);
566 if (config
.interval
) usleep(config
.interval
);
567 fflush(stdout
); /* Make it grep friendly */
574 /*------------------------------------------------------------------------------
576 *--------------------------------------------------------------------------- */
578 static int parseOptions(int argc
, char **argv
) {
581 for (i
= 1; i
< argc
; i
++) {
582 int lastarg
= i
==argc
-1;
584 if (!strcmp(argv
[i
],"-h") && !lastarg
) {
585 sdsfree(config
.hostip
);
586 config
.hostip
= sdsnew(argv
[++i
]);
587 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
589 } else if (!strcmp(argv
[i
],"--help")) {
591 } else if (!strcmp(argv
[i
],"-x")) {
593 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
594 config
.hostport
= atoi(argv
[++i
]);
595 } else if (!strcmp(argv
[i
],"-s") && !lastarg
) {
596 config
.hostsocket
= argv
[++i
];
597 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
598 config
.repeat
= strtoll(argv
[++i
],NULL
,10);
599 } else if (!strcmp(argv
[i
],"-i") && !lastarg
) {
600 double seconds
= atof(argv
[++i
]);
601 config
.interval
= seconds
*1000000;
602 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
603 config
.dbnum
= atoi(argv
[++i
]);
604 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
605 config
.auth
= argv
[++i
];
606 } else if (!strcmp(argv
[i
],"--raw")) {
607 config
.raw_output
= 1;
608 } else if (!strcmp(argv
[i
],"--latency")) {
609 config
.latency_mode
= 1;
610 } else if (!strcmp(argv
[i
],"--slave")) {
611 config
.slave_mode
= 1;
612 } else if (!strcmp(argv
[i
],"--eval") && !lastarg
) {
613 config
.eval
= argv
[++i
];
614 } else if (!strcmp(argv
[i
],"-c")) {
615 config
.cluster_mode
= 1;
616 } else if (!strcmp(argv
[i
],"-d") && !lastarg
) {
617 sdsfree(config
.mb_delim
);
618 config
.mb_delim
= sdsnew(argv
[++i
]);
619 } else if (!strcmp(argv
[i
],"-v") || !strcmp(argv
[i
], "--version")) {
620 sds version
= cliVersion();
621 printf("redis-cli %s\n", version
);
631 static sds
readArgFromStdin(void) {
633 sds arg
= sdsempty();
636 int nread
= read(fileno(stdin
),buf
,1024);
638 if (nread
== 0) break;
639 else if (nread
== -1) {
640 perror("Reading from standard input");
643 arg
= sdscatlen(arg
,buf
,nread
);
648 static void usage() {
649 sds version
= cliVersion();
653 "Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n"
654 " -h <hostname> Server hostname (default: 127.0.0.1)\n"
655 " -p <port> Server port (default: 6379)\n"
656 " -s <socket> Server socket (overrides hostname and port)\n"
657 " -a <password> Password to use when connecting to the server\n"
658 " -r <repeat> Execute specified command N times\n"
659 " -i <interval> When -r is used, waits <interval> seconds per command.\n"
660 " It is possible to specify sub-second times like -i 0.1.\n"
661 " -n <db> Database number\n"
662 " -x Read last argument from STDIN\n"
663 " -d <delimiter> Multi-bulk delimiter in for raw formatting (default: \\n)\n"
664 " -c Enable cluster mode (follow -ASK and -MOVED redirections)\n"
665 " --raw Use raw formatting for replies (default when STDOUT is not a tty)\n"
666 " --latency Enter a special mode continuously sampling latency.\n"
667 " --slave Simulate a slave showing commands received from the master.\n"
668 " --eval <file> Send an EVAL command using the Lua script at <file>.\n"
669 " --help Output this help and exit\n"
670 " --version Output version and exit\n"
673 " cat /etc/passwd | redis-cli -x set mypasswd\n"
674 " redis-cli get mypasswd\n"
675 " redis-cli -r 100 lpush mylist x\n"
676 " redis-cli -r 100 -i 1 info | grep used_memory_human:\n"
677 " redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3\n"
678 " (Note: when using --eval the comma separates KEYS[] from ARGV[] items)\n"
680 "When no command is given, redis-cli starts in interactive mode.\n"
681 "Type \"help\" in interactive mode for information on available commands.\n"
688 /* Turn the plain C strings into Sds strings */
689 static char **convertToSds(int count
, char** args
) {
691 char **sds
= zmalloc(sizeof(char*)*count
);
693 for(j
= 0; j
< count
; j
++)
694 sds
[j
] = sdsnew(args
[j
]);
699 #define LINE_BUFLEN 4096
701 sds historyfile
= NULL
;
707 config
.interactive
= 1;
708 linenoiseSetCompletionCallback(completionCallback
);
710 /* Only use history when stdin is a tty. */
711 if (isatty(fileno(stdin
))) {
714 if (getenv("HOME") != NULL
) {
715 historyfile
= sdscatprintf(sdsempty(),"%s/.rediscli_history",getenv("HOME"));
716 linenoiseHistoryLoad(historyfile
);
721 while((line
= linenoise(context
? config
.prompt
: "not connected> ")) != NULL
) {
722 if (line
[0] != '\0') {
723 argv
= sdssplitargs(line
,&argc
);
724 if (history
) linenoiseHistoryAdd(line
);
725 if (historyfile
) linenoiseHistorySave(historyfile
);
728 printf("Invalid argument(s)\n");
731 } else if (argc
> 0) {
732 if (strcasecmp(argv
[0],"quit") == 0 ||
733 strcasecmp(argv
[0],"exit") == 0)
736 } else if (argc
== 3 && !strcasecmp(argv
[0],"connect")) {
737 sdsfree(config
.hostip
);
738 config
.hostip
= sdsnew(argv
[1]);
739 config
.hostport
= atoi(argv
[2]);
741 } else if (argc
== 1 && !strcasecmp(argv
[0],"clear")) {
742 linenoiseClearScreen();
744 long long start_time
= mstime(), elapsed
;
745 int repeat
, skipargs
= 0;
747 repeat
= atoi(argv
[0]);
748 if (argc
> 1 && repeat
) {
755 config
.cluster_reissue_command
= 0;
756 if (cliSendCommand(argc
-skipargs
,argv
+skipargs
,repeat
)
761 /* If we still cannot send the command print error.
762 * We'll try to reconnect the next time. */
763 if (cliSendCommand(argc
-skipargs
,argv
+skipargs
,repeat
)
765 cliPrintContextError();
767 /* Issue the command again if we got redirected in cluster mode */
768 if (config
.cluster_mode
&& config
.cluster_reissue_command
) {
774 elapsed
= mstime()-start_time
;
775 if (elapsed
>= 500) {
776 printf("(%.2fs)\n",(double)elapsed
/1000);
780 /* Free the argument vector */
781 while(argc
--) sdsfree(argv
[argc
]);
784 /* linenoise() returns malloc-ed lines like readline() */
790 static int noninteractive(int argc
, char **argv
) {
792 if (config
.stdinarg
) {
793 argv
= zrealloc(argv
, (argc
+1)*sizeof(char*));
794 argv
[argc
] = readArgFromStdin();
795 retval
= cliSendCommand(argc
+1, argv
, config
.repeat
);
797 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
798 retval
= cliSendCommand(argc
, argv
, config
.repeat
);
803 static int evalMode(int argc
, char **argv
) {
804 sds script
= sdsempty();
809 int j
, got_comma
= 0, keys
= 0;
811 /* Load the script from the file, as an sds string. */
812 fp
= fopen(config
.eval
,"r");
815 "Can't open file '%s': %s\n", config
.eval
, strerror(errno
));
818 while((nread
= fread(buf
,1,sizeof(buf
),fp
)) != 0) {
819 script
= sdscatlen(script
,buf
,nread
);
823 /* Create our argument vector */
824 argv2
= zmalloc(sizeof(sds
)*(argc
+3));
825 argv2
[0] = sdsnew("EVAL");
827 for (j
= 0; j
< argc
; j
++) {
828 if (!got_comma
&& argv
[j
][0] == ',' && argv
[j
][1] == 0) {
832 argv2
[j
+3-got_comma
] = sdsnew(argv
[j
]);
833 if (!got_comma
) keys
++;
835 argv2
[2] = sdscatprintf(sdsempty(),"%d",keys
);
838 return cliSendCommand(argc
+3-got_comma
, argv2
, config
.repeat
);
841 static void latencyMode(void) {
843 long long start
, latency
, min
, max
, tot
, count
= 0;
846 if (!context
) exit(1);
849 reply
= redisCommand(context
,"PING");
851 fprintf(stderr
,"\nI/O error\n");
854 latency
= mstime()-start
;
855 freeReplyObject(reply
);
858 min
= max
= tot
= latency
;
859 avg
= (double) latency
;
861 if (latency
< min
) min
= latency
;
862 if (latency
> max
) max
= latency
;
864 avg
= (double) tot
/count
;
866 printf("\x1b[0G\x1b[2Kmin: %lld, max: %lld, avg: %.2f (%lld samples)",
867 min
, max
, avg
, count
);
873 static void slaveMode(void) {
874 /* To start we need to send the SYNC command and return the payload.
875 * The hiredis client lib does not understand this part of the protocol
876 * and we don't want to mess with its buffers, so everything is performed
877 * using direct low-level I/O. */
878 int fd
= context
->fd
;
881 unsigned long long payload
;
883 /* Send the SYNC command. */
884 write(fd
,"SYNC\r\n",6);
886 /* Read $<payload>\r\n, making sure to read just up to "\n" */
889 nread
= read(fd
,p
,1);
891 fprintf(stderr
,"Error reading bulk length while SYNCing\n");
894 if (*p
== '\n') break;
898 payload
= strtoull(buf
+1,NULL
,10);
899 if (!config
.raw_output
)
900 printf("SYNC with master, discarding %lld bytes of bulk tranfer...\n",
903 /* Discard the payload. */
905 nread
= read(fd
,buf
,(payload
> sizeof(buf
)) ? sizeof(buf
) : payload
);
907 fprintf(stderr
,"Error reading RDB payload while SYNCing\n");
912 if (!config
.raw_output
) printf("SYNC done. Logging commands from master.\n");
914 /* Now we can use the hiredis to read the incoming protocol. */
915 while (cliReadReply(config
.raw_output
) == REDIS_OK
);
918 int main(int argc
, char **argv
) {
921 config
.hostip
= sdsnew("127.0.0.1");
922 config
.hostport
= 6379;
923 config
.hostsocket
= NULL
;
927 config
.interactive
= 0;
929 config
.monitor_mode
= 0;
930 config
.pubsub_mode
= 0;
931 config
.latency_mode
= 0;
932 config
.cluster_mode
= 0;
936 config
.raw_output
= !isatty(fileno(stdout
)) && (getenv("FAKETTY") == NULL
);
937 config
.mb_delim
= sdsnew("\n");
940 firstarg
= parseOptions(argc
,argv
);
944 /* Start in latency mode if appropriate */
945 if (config
.latency_mode
) {
950 /* Start in slave mode if appropriate */
951 if (config
.slave_mode
) {
956 /* Start interactive mode when no command is provided */
957 if (argc
== 0 && !config
.eval
) {
958 /* Note that in repl mode we don't abort on connection error.
959 * A new attempt will be performed for every command send. */
964 /* Otherwise, we have some arguments to execute */
965 if (cliConnect(0) != REDIS_OK
) exit(1);
967 return evalMode(argc
,argv
);
969 return noninteractive(argc
,convertToSds(argc
,argv
));