]>
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"
52 #define REDIS_NOTUSED(V) ((void) V)
54 #define OUTPUT_STANDARD 0
58 static redisContext
*context
;
59 static struct config
{
72 int cluster_reissue_command
;
76 int stdinarg
; /* get last arg from stdin. (-x option) */
78 int output
; /* output mode, see OUTPUT_* defines */
85 char *redisGitSHA1(void);
86 char *redisGitDirty(void);
88 /*------------------------------------------------------------------------------
90 *--------------------------------------------------------------------------- */
92 static long long mstime(void) {
96 gettimeofday(&tv
, NULL
);
97 mst
= ((long)tv
.tv_sec
)*1000;
98 mst
+= tv
.tv_usec
/1000;
102 static void cliRefreshPrompt(void) {
105 if (config
.hostsocket
!= NULL
)
106 len
= snprintf(config
.prompt
,sizeof(config
.prompt
),"redis %s",
109 len
= snprintf(config
.prompt
,sizeof(config
.prompt
),"redis %s:%d",
110 config
.hostip
, config
.hostport
);
111 /* Add [dbnum] if needed */
112 if (config
.dbnum
!= 0)
113 len
+= snprintf(config
.prompt
+len
,sizeof(config
.prompt
)-len
,"[%d]",
115 snprintf(config
.prompt
+len
,sizeof(config
.prompt
)-len
,"> ");
118 /*------------------------------------------------------------------------------
120 *--------------------------------------------------------------------------- */
122 #define CLI_HELP_COMMAND 1
123 #define CLI_HELP_GROUP 2
131 /* Only used for help on commands */
132 struct commandHelp
*org
;
135 static helpEntry
*helpEntries
;
136 static int helpEntriesLen
;
138 static sds
cliVersion() {
140 version
= sdscatprintf(sdsempty(), "%s", REDIS_VERSION
);
142 /* Add git commit and working tree status when available */
143 if (strtoll(redisGitSHA1(),NULL
,16)) {
144 version
= sdscatprintf(version
, " (git:%s", redisGitSHA1());
145 if (strtoll(redisGitDirty(),NULL
,10))
146 version
= sdscatprintf(version
, "-dirty");
147 version
= sdscat(version
, ")");
152 static void cliInitHelp() {
153 int commandslen
= sizeof(commandHelp
)/sizeof(struct commandHelp
);
154 int groupslen
= sizeof(commandGroups
)/sizeof(char*);
158 helpEntriesLen
= len
= commandslen
+groupslen
;
159 helpEntries
= malloc(sizeof(helpEntry
)*len
);
161 for (i
= 0; i
< groupslen
; i
++) {
163 tmp
.argv
= malloc(sizeof(sds
));
164 tmp
.argv
[0] = sdscatprintf(sdsempty(),"@%s",commandGroups
[i
]);
165 tmp
.full
= tmp
.argv
[0];
166 tmp
.type
= CLI_HELP_GROUP
;
168 helpEntries
[pos
++] = tmp
;
171 for (i
= 0; i
< commandslen
; i
++) {
172 tmp
.argv
= sdssplitargs(commandHelp
[i
].name
,&tmp
.argc
);
173 tmp
.full
= sdsnew(commandHelp
[i
].name
);
174 tmp
.type
= CLI_HELP_COMMAND
;
175 tmp
.org
= &commandHelp
[i
];
176 helpEntries
[pos
++] = tmp
;
180 /* Output command help to stdout. */
181 static void cliOutputCommandHelp(struct commandHelp
*help
, int group
) {
182 printf("\r\n \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\r\n", help
->name
, help
->params
);
183 printf(" \x1b[33msummary:\x1b[0m %s\r\n", help
->summary
);
184 printf(" \x1b[33msince:\x1b[0m %s\r\n", help
->since
);
186 printf(" \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups
[help
->group
]);
190 /* Print generic help. */
191 static void cliOutputGenericHelp() {
192 sds version
= cliVersion();
195 "Type: \"help @<group>\" to get a list of commands in <group>\r\n"
196 " \"help <command>\" for help on <command>\r\n"
197 " \"help <tab>\" to get a list of possible help topics\r\n"
198 " \"quit\" to exit\r\n",
204 /* Output all command help, filtering by group or command name. */
205 static void cliOutputHelp(int argc
, char **argv
) {
209 struct commandHelp
*help
;
212 cliOutputGenericHelp();
214 } else if (argc
> 0 && argv
[0][0] == '@') {
215 len
= sizeof(commandGroups
)/sizeof(char*);
216 for (i
= 0; i
< len
; i
++) {
217 if (strcasecmp(argv
[0]+1,commandGroups
[i
]) == 0) {
225 for (i
= 0; i
< helpEntriesLen
; i
++) {
226 entry
= &helpEntries
[i
];
227 if (entry
->type
!= CLI_HELP_COMMAND
) continue;
231 /* Compare all arguments */
232 if (argc
== entry
->argc
) {
233 for (j
= 0; j
< argc
; j
++) {
234 if (strcasecmp(argv
[j
],entry
->argv
[j
]) != 0) break;
237 cliOutputCommandHelp(help
,1);
241 if (group
== help
->group
) {
242 cliOutputCommandHelp(help
,0);
249 static void completionCallback(const char *buf
, linenoiseCompletions
*lc
) {
256 if (strncasecmp(buf
,"help ",5) == 0) {
258 while (isspace(buf
[startpos
])) startpos
++;
259 mask
= CLI_HELP_COMMAND
| CLI_HELP_GROUP
;
261 mask
= CLI_HELP_COMMAND
;
264 for (i
= 0; i
< helpEntriesLen
; i
++) {
265 if (!(helpEntries
[i
].type
& mask
)) continue;
267 matchlen
= strlen(buf
+startpos
);
268 if (strncasecmp(buf
+startpos
,helpEntries
[i
].full
,matchlen
) == 0) {
269 tmp
= sdsnewlen(buf
,startpos
);
270 tmp
= sdscat(tmp
,helpEntries
[i
].full
);
271 linenoiseAddCompletion(lc
,tmp
);
277 /*------------------------------------------------------------------------------
278 * Networking / parsing
279 *--------------------------------------------------------------------------- */
281 /* Send AUTH command to the server */
282 static int cliAuth() {
284 if (config
.auth
== NULL
) return REDIS_OK
;
286 reply
= redisCommand(context
,"AUTH %s",config
.auth
);
288 freeReplyObject(reply
);
294 /* Send SELECT dbnum to the server */
295 static int cliSelect() {
297 if (config
.dbnum
== 0) return REDIS_OK
;
299 reply
= redisCommand(context
,"SELECT %d",config
.dbnum
);
301 freeReplyObject(reply
);
307 /* Connect to the client. If force is not zero the connection is performed
308 * even if there is already a connected socket. */
309 static int cliConnect(int force
) {
310 if (context
== NULL
|| force
) {
314 if (config
.hostsocket
== NULL
) {
315 context
= redisConnect(config
.hostip
,config
.hostport
);
317 context
= redisConnectUnix(config
.hostsocket
);
321 fprintf(stderr
,"Could not connect to Redis at ");
322 if (config
.hostsocket
== NULL
)
323 fprintf(stderr
,"%s:%d: %s\n",config
.hostip
,config
.hostport
,context
->errstr
);
325 fprintf(stderr
,"%s: %s\n",config
.hostsocket
,context
->errstr
);
331 /* Do AUTH and select the right DB. */
332 if (cliAuth() != REDIS_OK
)
334 if (cliSelect() != REDIS_OK
)
340 static void cliPrintContextError() {
341 if (context
== NULL
) return;
342 fprintf(stderr
,"Error: %s\n",context
->errstr
);
345 static sds
cliFormatReplyTTY(redisReply
*r
, char *prefix
) {
346 sds out
= sdsempty();
348 case REDIS_REPLY_ERROR
:
349 out
= sdscatprintf(out
,"(error) %s\n", r
->str
);
351 case REDIS_REPLY_STATUS
:
352 out
= sdscat(out
,r
->str
);
353 out
= sdscat(out
,"\n");
355 case REDIS_REPLY_INTEGER
:
356 out
= sdscatprintf(out
,"(integer) %lld\n",r
->integer
);
358 case REDIS_REPLY_STRING
:
359 /* If you are producing output for the standard output we want
360 * a more interesting output with quoted characters and so forth */
361 out
= sdscatrepr(out
,r
->str
,r
->len
);
362 out
= sdscat(out
,"\n");
364 case REDIS_REPLY_NIL
:
365 out
= sdscat(out
,"(nil)\n");
367 case REDIS_REPLY_ARRAY
:
368 if (r
->elements
== 0) {
369 out
= sdscat(out
,"(empty list or set)\n");
371 unsigned int i
, idxlen
= 0;
377 /* Calculate chars needed to represent the largest index */
384 /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
385 memset(_prefixlen
,' ',idxlen
+2);
386 _prefixlen
[idxlen
+2] = '\0';
387 _prefix
= sdscat(sdsnew(prefix
),_prefixlen
);
389 /* Setup prefix format for every entry */
390 snprintf(_prefixfmt
,sizeof(_prefixfmt
),"%%s%%%dd) ",idxlen
);
392 for (i
= 0; i
< r
->elements
; i
++) {
393 /* Don't use the prefix for the first element, as the parent
394 * caller already prepended the index number. */
395 out
= sdscatprintf(out
,_prefixfmt
,i
== 0 ? "" : prefix
,i
+1);
397 /* Format the multi bulk entry */
398 tmp
= cliFormatReplyTTY(r
->element
[i
],_prefix
);
399 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
406 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
412 static sds
cliFormatReplyRaw(redisReply
*r
) {
413 sds out
= sdsempty(), tmp
;
417 case REDIS_REPLY_NIL
:
420 case REDIS_REPLY_ERROR
:
421 out
= sdscatlen(out
,r
->str
,r
->len
);
422 out
= sdscatlen(out
,"\n",1);
424 case REDIS_REPLY_STATUS
:
425 case REDIS_REPLY_STRING
:
426 out
= sdscatlen(out
,r
->str
,r
->len
);
428 case REDIS_REPLY_INTEGER
:
429 out
= sdscatprintf(out
,"%lld",r
->integer
);
431 case REDIS_REPLY_ARRAY
:
432 for (i
= 0; i
< r
->elements
; i
++) {
433 if (i
> 0) out
= sdscat(out
,config
.mb_delim
);
434 tmp
= cliFormatReplyRaw(r
->element
[i
]);
435 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
440 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
446 static sds
cliFormatReplyCSV(redisReply
*r
) {
449 sds out
= sdsempty();
451 case REDIS_REPLY_ERROR
:
452 out
= sdscat(out
,"ERROR,");
453 out
= sdscatrepr(out
,r
->str
,strlen(r
->str
));
455 case REDIS_REPLY_STATUS
:
456 out
= sdscatrepr(out
,r
->str
,r
->len
);
458 case REDIS_REPLY_INTEGER
:
459 out
= sdscatprintf(out
,"%lld",r
->integer
);
461 case REDIS_REPLY_STRING
:
462 out
= sdscatrepr(out
,r
->str
,r
->len
);
464 case REDIS_REPLY_NIL
:
465 out
= sdscat(out
,"NIL\n");
467 case REDIS_REPLY_ARRAY
:
468 for (i
= 0; i
< r
->elements
; i
++) {
469 sds tmp
= cliFormatReplyCSV(r
->element
[i
]);
470 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
471 if (i
!= r
->elements
-1) out
= sdscat(out
,",");
476 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
482 static int cliReadReply(int output_raw_strings
) {
488 if (redisGetReply(context
,&_reply
) != REDIS_OK
) {
491 if (config
.interactive
) {
492 /* Filter cases where we should reconnect */
493 if (context
->err
== REDIS_ERR_IO
&& errno
== ECONNRESET
)
495 if (context
->err
== REDIS_ERR_EOF
)
498 cliPrintContextError();
500 return REDIS_ERR
; /* avoid compiler warning */
503 reply
= (redisReply
*)_reply
;
505 /* Check if we need to connect to a different node and reissue the
507 if (config
.cluster_mode
&& reply
->type
== REDIS_REPLY_ERROR
&&
508 (!strncmp(reply
->str
,"MOVED",5) || !strcmp(reply
->str
,"ASK")))
510 char *p
= reply
->str
, *s
;
514 /* Comments show the position of the pointer as:
516 * [S] for pointer 's'
517 * [P] for pointer 'p'
519 s
= strchr(p
,' '); /* MOVED[S]3999 127.0.0.1:6381 */
520 p
= strchr(s
+1,' '); /* MOVED[S]3999[P]127.0.0.1:6381 */
523 s
= strchr(p
+1,':'); /* MOVED 3999[P]127.0.0.1[S]6381 */
525 sdsfree(config
.hostip
);
526 config
.hostip
= sdsnew(p
+1);
527 config
.hostport
= atoi(s
+1);
528 if (config
.interactive
)
529 printf("-> Redirected to slot [%d] located at %s:%d\n",
530 slot
, config
.hostip
, config
.hostport
);
531 config
.cluster_reissue_command
= 1;
535 if (output_raw_strings
) {
536 out
= cliFormatReplyRaw(reply
);
538 if (config
.output
== OUTPUT_RAW
) {
539 out
= cliFormatReplyRaw(reply
);
540 out
= sdscat(out
,"\n");
541 } else if (config
.output
== OUTPUT_STANDARD
) {
542 out
= cliFormatReplyTTY(reply
,"");
543 } else if (config
.output
== OUTPUT_CSV
) {
544 out
= cliFormatReplyCSV(reply
);
545 out
= sdscat(out
,"\n");
548 fwrite(out
,sdslen(out
),1,stdout
);
551 freeReplyObject(reply
);
555 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
556 char *command
= argv
[0];
560 if (!strcasecmp(command
,"help") || !strcasecmp(command
,"?")) {
561 cliOutputHelp(--argc
, ++argv
);
565 if (context
== NULL
) return REDIS_ERR
;
568 if (!strcasecmp(command
,"info") ||
569 (argc
== 2 && !strcasecmp(command
,"cluster") &&
570 (!strcasecmp(argv
[1],"nodes") ||
571 !strcasecmp(argv
[1],"info"))) ||
572 (argc
== 2 && !strcasecmp(command
,"client") &&
573 !strcasecmp(argv
[1],"list")))
579 if (!strcasecmp(command
,"shutdown")) config
.shutdown
= 1;
580 if (!strcasecmp(command
,"monitor")) config
.monitor_mode
= 1;
581 if (!strcasecmp(command
,"subscribe") ||
582 !strcasecmp(command
,"psubscribe")) config
.pubsub_mode
= 1;
584 /* Setup argument length */
585 argvlen
= malloc(argc
*sizeof(size_t));
586 for (j
= 0; j
< argc
; j
++)
587 argvlen
[j
] = sdslen(argv
[j
]);
590 redisAppendCommandArgv(context
,argc
,(const char**)argv
,argvlen
);
591 while (config
.monitor_mode
) {
592 if (cliReadReply(output_raw
) != REDIS_OK
) exit(1);
596 if (config
.pubsub_mode
) {
597 if (config
.output
!= OUTPUT_RAW
)
598 printf("Reading messages... (press Ctrl-C to quit)\n");
600 if (cliReadReply(output_raw
) != REDIS_OK
) exit(1);
604 if (cliReadReply(output_raw
) != REDIS_OK
) {
608 /* Store database number when SELECT was successfully executed. */
609 if (!strcasecmp(command
,"select") && argc
== 2) {
610 config
.dbnum
= atoi(argv
[1]);
614 if (config
.interval
) usleep(config
.interval
);
615 fflush(stdout
); /* Make it grep friendly */
622 /*------------------------------------------------------------------------------
624 *--------------------------------------------------------------------------- */
626 static int parseOptions(int argc
, char **argv
) {
629 for (i
= 1; i
< argc
; i
++) {
630 int lastarg
= i
==argc
-1;
632 if (!strcmp(argv
[i
],"-h") && !lastarg
) {
633 sdsfree(config
.hostip
);
634 config
.hostip
= sdsnew(argv
[++i
]);
635 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
637 } else if (!strcmp(argv
[i
],"--help")) {
639 } else if (!strcmp(argv
[i
],"-x")) {
641 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
642 config
.hostport
= atoi(argv
[++i
]);
643 } else if (!strcmp(argv
[i
],"-s") && !lastarg
) {
644 config
.hostsocket
= argv
[++i
];
645 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
646 config
.repeat
= strtoll(argv
[++i
],NULL
,10);
647 } else if (!strcmp(argv
[i
],"-i") && !lastarg
) {
648 double seconds
= atof(argv
[++i
]);
649 config
.interval
= seconds
*1000000;
650 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
651 config
.dbnum
= atoi(argv
[++i
]);
652 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
653 config
.auth
= argv
[++i
];
654 } else if (!strcmp(argv
[i
],"--raw")) {
655 config
.output
= OUTPUT_RAW
;
656 } else if (!strcmp(argv
[i
],"--csv")) {
657 config
.output
= OUTPUT_CSV
;
658 } else if (!strcmp(argv
[i
],"--latency")) {
659 config
.latency_mode
= 1;
660 } else if (!strcmp(argv
[i
],"--slave")) {
661 config
.slave_mode
= 1;
662 } else if (!strcmp(argv
[i
],"--pipe")) {
663 config
.pipe_mode
= 1;
664 } else if (!strcmp(argv
[i
],"--bigkeys")) {
666 } else if (!strcmp(argv
[i
],"--eval") && !lastarg
) {
667 config
.eval
= argv
[++i
];
668 } else if (!strcmp(argv
[i
],"-c")) {
669 config
.cluster_mode
= 1;
670 } else if (!strcmp(argv
[i
],"-d") && !lastarg
) {
671 sdsfree(config
.mb_delim
);
672 config
.mb_delim
= sdsnew(argv
[++i
]);
673 } else if (!strcmp(argv
[i
],"-v") || !strcmp(argv
[i
], "--version")) {
674 sds version
= cliVersion();
675 printf("redis-cli %s\n", version
);
685 static sds
readArgFromStdin(void) {
687 sds arg
= sdsempty();
690 int nread
= read(fileno(stdin
),buf
,1024);
692 if (nread
== 0) break;
693 else if (nread
== -1) {
694 perror("Reading from standard input");
697 arg
= sdscatlen(arg
,buf
,nread
);
702 static void usage() {
703 sds version
= cliVersion();
707 "Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n"
708 " -h <hostname> Server hostname (default: 127.0.0.1)\n"
709 " -p <port> Server port (default: 6379)\n"
710 " -s <socket> Server socket (overrides hostname and port)\n"
711 " -a <password> Password to use when connecting to the server\n"
712 " -r <repeat> Execute specified command N times\n"
713 " -i <interval> When -r is used, waits <interval> seconds per command.\n"
714 " It is possible to specify sub-second times like -i 0.1.\n"
715 " -n <db> Database number\n"
716 " -x Read last argument from STDIN\n"
717 " -d <delimiter> Multi-bulk delimiter in for raw formatting (default: \\n)\n"
718 " -c Enable cluster mode (follow -ASK and -MOVED redirections)\n"
719 " --raw Use raw formatting for replies (default when STDOUT is not a tty)\n"
720 " --latency Enter a special mode continuously sampling latency.\n"
721 " --slave Simulate a slave showing commands received from the master.\n"
722 " --pipe Transfer raw Redis protocol from stdin to server.\n"
723 " --bigkeys Sample Redis keys looking for big keys.\n"
724 " --eval <file> Send an EVAL command using the Lua script at <file>.\n"
725 " --help Output this help and exit\n"
726 " --version Output version and exit\n"
729 " cat /etc/passwd | redis-cli -x set mypasswd\n"
730 " redis-cli get mypasswd\n"
731 " redis-cli -r 100 lpush mylist x\n"
732 " redis-cli -r 100 -i 1 info | grep used_memory_human:\n"
733 " redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3\n"
734 " (Note: when using --eval the comma separates KEYS[] from ARGV[] items)\n"
736 "When no command is given, redis-cli starts in interactive mode.\n"
737 "Type \"help\" in interactive mode for information on available commands.\n"
744 /* Turn the plain C strings into Sds strings */
745 static char **convertToSds(int count
, char** args
) {
747 char **sds
= zmalloc(sizeof(char*)*count
);
749 for(j
= 0; j
< count
; j
++)
750 sds
[j
] = sdsnew(args
[j
]);
755 #define LINE_BUFLEN 4096
757 sds historyfile
= NULL
;
763 config
.interactive
= 1;
764 linenoiseSetCompletionCallback(completionCallback
);
766 /* Only use history when stdin is a tty. */
767 if (isatty(fileno(stdin
))) {
770 if (getenv("HOME") != NULL
) {
771 historyfile
= sdscatprintf(sdsempty(),"%s/.rediscli_history",getenv("HOME"));
772 linenoiseHistoryLoad(historyfile
);
777 while((line
= linenoise(context
? config
.prompt
: "not connected> ")) != NULL
) {
778 if (line
[0] != '\0') {
779 argv
= sdssplitargs(line
,&argc
);
780 if (history
) linenoiseHistoryAdd(line
);
781 if (historyfile
) linenoiseHistorySave(historyfile
);
784 printf("Invalid argument(s)\n");
787 } else if (argc
> 0) {
788 if (strcasecmp(argv
[0],"quit") == 0 ||
789 strcasecmp(argv
[0],"exit") == 0)
792 } else if (argc
== 3 && !strcasecmp(argv
[0],"connect")) {
793 sdsfree(config
.hostip
);
794 config
.hostip
= sdsnew(argv
[1]);
795 config
.hostport
= atoi(argv
[2]);
797 } else if (argc
== 1 && !strcasecmp(argv
[0],"clear")) {
798 linenoiseClearScreen();
800 long long start_time
= mstime(), elapsed
;
801 int repeat
, skipargs
= 0;
803 repeat
= atoi(argv
[0]);
804 if (argc
> 1 && repeat
) {
811 config
.cluster_reissue_command
= 0;
812 if (cliSendCommand(argc
-skipargs
,argv
+skipargs
,repeat
)
817 /* If we still cannot send the command print error.
818 * We'll try to reconnect the next time. */
819 if (cliSendCommand(argc
-skipargs
,argv
+skipargs
,repeat
)
821 cliPrintContextError();
823 /* Issue the command again if we got redirected in cluster mode */
824 if (config
.cluster_mode
&& config
.cluster_reissue_command
) {
830 elapsed
= mstime()-start_time
;
831 if (elapsed
>= 500) {
832 printf("(%.2fs)\n",(double)elapsed
/1000);
836 /* Free the argument vector */
837 while(argc
--) sdsfree(argv
[argc
]);
840 /* linenoise() returns malloc-ed lines like readline() */
846 static int noninteractive(int argc
, char **argv
) {
848 if (config
.stdinarg
) {
849 argv
= zrealloc(argv
, (argc
+1)*sizeof(char*));
850 argv
[argc
] = readArgFromStdin();
851 retval
= cliSendCommand(argc
+1, argv
, config
.repeat
);
853 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
854 retval
= cliSendCommand(argc
, argv
, config
.repeat
);
859 static int evalMode(int argc
, char **argv
) {
860 sds script
= sdsempty();
865 int j
, got_comma
= 0, keys
= 0;
867 /* Load the script from the file, as an sds string. */
868 fp
= fopen(config
.eval
,"r");
871 "Can't open file '%s': %s\n", config
.eval
, strerror(errno
));
874 while((nread
= fread(buf
,1,sizeof(buf
),fp
)) != 0) {
875 script
= sdscatlen(script
,buf
,nread
);
879 /* Create our argument vector */
880 argv2
= zmalloc(sizeof(sds
)*(argc
+3));
881 argv2
[0] = sdsnew("EVAL");
883 for (j
= 0; j
< argc
; j
++) {
884 if (!got_comma
&& argv
[j
][0] == ',' && argv
[j
][1] == 0) {
888 argv2
[j
+3-got_comma
] = sdsnew(argv
[j
]);
889 if (!got_comma
) keys
++;
891 argv2
[2] = sdscatprintf(sdsempty(),"%d",keys
);
894 return cliSendCommand(argc
+3-got_comma
, argv2
, config
.repeat
);
897 static void latencyMode(void) {
899 long long start
, latency
, min
= 0, max
= 0, tot
= 0, count
= 0;
902 if (!context
) exit(1);
905 reply
= redisCommand(context
,"PING");
907 fprintf(stderr
,"\nI/O error\n");
910 latency
= mstime()-start
;
911 freeReplyObject(reply
);
914 min
= max
= tot
= latency
;
915 avg
= (double) latency
;
917 if (latency
< min
) min
= latency
;
918 if (latency
> max
) max
= latency
;
920 avg
= (double) tot
/count
;
922 printf("\x1b[0G\x1b[2Kmin: %lld, max: %lld, avg: %.2f (%lld samples)",
923 min
, max
, avg
, count
);
929 static void slaveMode(void) {
930 /* To start we need to send the SYNC command and return the payload.
931 * The hiredis client lib does not understand this part of the protocol
932 * and we don't want to mess with its buffers, so everything is performed
933 * using direct low-level I/O. */
934 int fd
= context
->fd
;
937 unsigned long long payload
;
939 /* Send the SYNC command. */
940 if (write(fd
,"SYNC\r\n",6) != 6) {
941 fprintf(stderr
,"Error writing to master\n");
945 /* Read $<payload>\r\n, making sure to read just up to "\n" */
948 nread
= read(fd
,p
,1);
950 fprintf(stderr
,"Error reading bulk length while SYNCing\n");
953 if (*p
== '\n') break;
957 payload
= strtoull(buf
+1,NULL
,10);
958 fprintf(stderr
,"SYNC with master, discarding %lld bytes of bulk tranfer...\n",
961 /* Discard the payload. */
963 nread
= read(fd
,buf
,(payload
> sizeof(buf
)) ? sizeof(buf
) : payload
);
965 fprintf(stderr
,"Error reading RDB payload while SYNCing\n");
970 fprintf(stderr
,"SYNC done. Logging commands from master.\n");
972 /* Now we can use the hiredis to read the incoming protocol. */
973 config
.output
= OUTPUT_CSV
;
974 while (cliReadReply(0) == REDIS_OK
);
977 static void pipeMode(void) {
978 int fd
= context
->fd
;
979 long long errors
= 0, replies
= 0, obuf_len
= 0, obuf_pos
= 0;
980 char ibuf
[1024*16], obuf
[1024*16]; /* Input and output buffers */
981 char aneterr
[ANET_ERR_LEN
];
982 redisReader
*reader
= redisReaderCreate();
984 int eof
= 0; /* True once we consumed all the standard input. */
986 char magic
[20]; /* Special reply we recognize. */
990 /* Use non blocking I/O. */
991 if (anetNonBlock(aneterr
,fd
) == ANET_ERR
) {
992 fprintf(stderr
, "Can't set the socket in non blocking mode: %s\n",
997 /* Transfer raw protocol and read replies from the server at the same
1000 int mask
= AE_READABLE
;
1002 if (!eof
|| obuf_len
!= 0) mask
|= AE_WRITABLE
;
1003 mask
= aeWait(fd
,mask
,1000);
1005 /* Handle the readable state: we can read replies from the server. */
1006 if (mask
& AE_READABLE
) {
1009 /* Read from socket and feed the hiredis reader. */
1011 nread
= read(fd
,ibuf
,sizeof(ibuf
));
1012 if (nread
== -1 && errno
!= EAGAIN
&& errno
!= EINTR
) {
1013 fprintf(stderr
, "Error reading from the server: %s\n",
1017 if (nread
> 0) redisReaderFeed(reader
,ibuf
,nread
);
1020 /* Consume replies. */
1022 if (redisReaderGetReply(reader
,(void**)&reply
) == REDIS_ERR
) {
1023 fprintf(stderr
, "Error reading replies from server\n");
1027 if (reply
->type
== REDIS_REPLY_ERROR
) {
1028 fprintf(stderr
,"%s\n", reply
->str
);
1030 } else if (eof
&& reply
->type
== REDIS_REPLY_STRING
&&
1032 /* Check if this is the reply to our final ECHO
1033 * command. If so everything was received
1034 * from the server. */
1035 if (memcmp(reply
->str
,magic
,20) == 0) {
1036 printf("Last reply received from server.\n");
1042 freeReplyObject(reply
);
1047 /* Handle the writable state: we can send protocol to the server. */
1048 if (mask
& AE_WRITABLE
) {
1050 /* Transfer current buffer to server. */
1051 if (obuf_len
!= 0) {
1052 ssize_t nwritten
= write(fd
,obuf
+obuf_pos
,obuf_len
);
1054 if (nwritten
== -1) {
1055 if (errno
!= EAGAIN
&& errno
!= EINTR
) {
1056 fprintf(stderr
, "Error writing to the server: %s\n",
1063 obuf_len
-= nwritten
;
1064 obuf_pos
+= nwritten
;
1065 if (obuf_len
!= 0) break; /* Can't accept more data. */
1067 /* If buffer is empty, load from stdin. */
1068 if (obuf_len
== 0 && !eof
) {
1069 ssize_t nread
= read(STDIN_FILENO
,obuf
,sizeof(obuf
));
1073 "*2\r\n$4\r\nECHO\r\n$20\r\n01234567890123456789\r\n";
1077 /* Everything transfered, so we queue a special
1078 * ECHO command that we can match in the replies
1079 * to make sure everything was read from the server. */
1080 for (j
= 0; j
< 20; j
++)
1081 magic
[j
] = rand() & 0xff;
1082 memcpy(echo
+19,magic
,20);
1083 memcpy(obuf
,echo
,sizeof(echo
)-1);
1084 obuf_len
= sizeof(echo
)-1;
1086 printf("All data transferred. Waiting for the last reply...\n");
1087 } else if (nread
== -1) {
1088 fprintf(stderr
, "Error reading from stdin: %s\n",
1096 if (obuf_len
== 0 && eof
) break;
1100 redisReaderFree(reader
);
1101 printf("errors: %lld, replies: %lld\n", errors
, replies
);
1108 #define TYPE_STRING 0
1114 static void findBigKeys(void) {
1115 unsigned long long biggest
[5] = {0,0,0,0,0};
1116 unsigned long long samples
= 0;
1117 redisReply
*reply1
, *reply2
, *reply3
= NULL
;
1118 char *sizecmd
, *typename
[] = {"string","list","set","hash","zset"};
1121 printf("\n# Press ctrl+c when you have had enough of it... :)\n");
1122 printf("# You can use -i 0.1 to sleep 0.1 sec every 100 sampled keys\n");
1123 printf("# in order to reduce server load (usually not needed).\n\n");
1125 /* Sample with RANDOMKEY */
1126 reply1
= redisCommand(context
,"RANDOMKEY");
1127 if (reply1
== NULL
) {
1128 fprintf(stderr
,"\nI/O error\n");
1130 } else if (reply1
->type
== REDIS_REPLY_ERROR
) {
1131 fprintf(stderr
, "RANDOMKEY error: %s\n",
1135 /* Get the key type */
1136 reply2
= redisCommand(context
,"TYPE %s",reply1
->str
);
1137 assert(reply2
&& reply2
->type
== REDIS_REPLY_STATUS
);
1140 /* Get the key "size" */
1141 if (!strcmp(reply2
->str
,"string")) {
1144 } else if (!strcmp(reply2
->str
,"list")) {
1147 } else if (!strcmp(reply2
->str
,"set")) {
1150 } else if (!strcmp(reply2
->str
,"hash")) {
1153 } else if (!strcmp(reply2
->str
,"zset")) {
1156 } else if (!strcmp(reply2
->str
,"none")) {
1157 freeReplyObject(reply1
);
1158 freeReplyObject(reply2
);
1159 freeReplyObject(reply3
);
1162 fprintf(stderr
, "Unknown key type '%s' for key '%s'\n",
1163 reply2
->str
, reply1
->str
);
1167 reply3
= redisCommand(context
,"%s %s", sizecmd
, reply1
->str
);
1168 if (reply3
&& reply3
->type
== REDIS_REPLY_INTEGER
) {
1169 if (biggest
[type
] < reply3
->integer
) {
1170 printf("[%6s] %s | biggest so far with size %llu\n",
1171 typename
[type
], reply1
->str
,
1172 (unsigned long long) reply3
->integer
);
1173 biggest
[type
] = reply3
->integer
;
1177 if ((samples
% 1000000) == 0)
1178 printf("(%llu keys sampled)\n", samples
);
1180 if ((samples
% 100) == 0 && config
.interval
)
1181 usleep(config
.interval
);
1183 freeReplyObject(reply1
);
1184 freeReplyObject(reply2
);
1185 if (reply3
) freeReplyObject(reply3
);
1189 int main(int argc
, char **argv
) {
1192 config
.hostip
= sdsnew("127.0.0.1");
1193 config
.hostport
= 6379;
1194 config
.hostsocket
= NULL
;
1196 config
.interval
= 0;
1198 config
.interactive
= 0;
1199 config
.shutdown
= 0;
1200 config
.monitor_mode
= 0;
1201 config
.pubsub_mode
= 0;
1202 config
.latency_mode
= 0;
1203 config
.cluster_mode
= 0;
1204 config
.slave_mode
= 0;
1205 config
.pipe_mode
= 0;
1207 config
.stdinarg
= 0;
1210 if (!isatty(fileno(stdout
)) && (getenv("FAKETTY") == NULL
))
1211 config
.output
= OUTPUT_RAW
;
1213 config
.output
= OUTPUT_STANDARD
;
1214 config
.mb_delim
= sdsnew("\n");
1217 firstarg
= parseOptions(argc
,argv
);
1222 if (config
.latency_mode
) {
1228 if (config
.slave_mode
) {
1234 if (config
.pipe_mode
) {
1240 if (config
.bigkeys
) {
1245 /* Start interactive mode when no command is provided */
1246 if (argc
== 0 && !config
.eval
) {
1247 /* Note that in repl mode we don't abort on connection error.
1248 * A new attempt will be performed for every command send. */
1253 /* Otherwise, we have some arguments to execute */
1254 if (cliConnect(0) != REDIS_OK
) exit(1);
1256 return evalMode(argc
,argv
);
1258 return noninteractive(argc
,convertToSds(argc
,argv
));