]>
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
;
73 int stdinarg
; /* get last arg from stdin. (-x option) */
75 int output
; /* output mode, see OUTPUT_* defines */
82 char *redisGitSHA1(void);
83 char *redisGitDirty(void);
85 /*------------------------------------------------------------------------------
87 *--------------------------------------------------------------------------- */
89 static long long mstime(void) {
93 gettimeofday(&tv
, NULL
);
94 mst
= ((long)tv
.tv_sec
)*1000;
95 mst
+= tv
.tv_usec
/1000;
99 static void cliRefreshPrompt(void) {
102 if (config
.hostsocket
!= NULL
)
103 len
= snprintf(config
.prompt
,sizeof(config
.prompt
),"redis %s",
106 len
= snprintf(config
.prompt
,sizeof(config
.prompt
),"redis %s:%d",
107 config
.hostip
, config
.hostport
);
108 /* Add [dbnum] if needed */
109 if (config
.dbnum
!= 0)
110 len
+= snprintf(config
.prompt
+len
,sizeof(config
.prompt
)-len
,"[%d]",
112 snprintf(config
.prompt
+len
,sizeof(config
.prompt
)-len
,"> ");
115 /*------------------------------------------------------------------------------
117 *--------------------------------------------------------------------------- */
119 #define CLI_HELP_COMMAND 1
120 #define CLI_HELP_GROUP 2
128 /* Only used for help on commands */
129 struct commandHelp
*org
;
132 static helpEntry
*helpEntries
;
133 static int helpEntriesLen
;
135 static sds
cliVersion() {
137 version
= sdscatprintf(sdsempty(), "%s", REDIS_VERSION
);
139 /* Add git commit and working tree status when available */
140 if (strtoll(redisGitSHA1(),NULL
,16)) {
141 version
= sdscatprintf(version
, " (git:%s", redisGitSHA1());
142 if (strtoll(redisGitDirty(),NULL
,10))
143 version
= sdscatprintf(version
, "-dirty");
144 version
= sdscat(version
, ")");
149 static void cliInitHelp() {
150 int commandslen
= sizeof(commandHelp
)/sizeof(struct commandHelp
);
151 int groupslen
= sizeof(commandGroups
)/sizeof(char*);
155 helpEntriesLen
= len
= commandslen
+groupslen
;
156 helpEntries
= malloc(sizeof(helpEntry
)*len
);
158 for (i
= 0; i
< groupslen
; i
++) {
160 tmp
.argv
= malloc(sizeof(sds
));
161 tmp
.argv
[0] = sdscatprintf(sdsempty(),"@%s",commandGroups
[i
]);
162 tmp
.full
= tmp
.argv
[0];
163 tmp
.type
= CLI_HELP_GROUP
;
165 helpEntries
[pos
++] = tmp
;
168 for (i
= 0; i
< commandslen
; i
++) {
169 tmp
.argv
= sdssplitargs(commandHelp
[i
].name
,&tmp
.argc
);
170 tmp
.full
= sdsnew(commandHelp
[i
].name
);
171 tmp
.type
= CLI_HELP_COMMAND
;
172 tmp
.org
= &commandHelp
[i
];
173 helpEntries
[pos
++] = tmp
;
177 /* Output command help to stdout. */
178 static void cliOutputCommandHelp(struct commandHelp
*help
, int group
) {
179 printf("\r\n \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\r\n", help
->name
, help
->params
);
180 printf(" \x1b[33msummary:\x1b[0m %s\r\n", help
->summary
);
181 printf(" \x1b[33msince:\x1b[0m %s\r\n", help
->since
);
183 printf(" \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups
[help
->group
]);
187 /* Print generic help. */
188 static void cliOutputGenericHelp() {
189 sds version
= cliVersion();
192 "Type: \"help @<group>\" to get a list of commands in <group>\r\n"
193 " \"help <command>\" for help on <command>\r\n"
194 " \"help <tab>\" to get a list of possible help topics\r\n"
195 " \"quit\" to exit\r\n",
201 /* Output all command help, filtering by group or command name. */
202 static void cliOutputHelp(int argc
, char **argv
) {
206 struct commandHelp
*help
;
209 cliOutputGenericHelp();
211 } else if (argc
> 0 && argv
[0][0] == '@') {
212 len
= sizeof(commandGroups
)/sizeof(char*);
213 for (i
= 0; i
< len
; i
++) {
214 if (strcasecmp(argv
[0]+1,commandGroups
[i
]) == 0) {
222 for (i
= 0; i
< helpEntriesLen
; i
++) {
223 entry
= &helpEntries
[i
];
224 if (entry
->type
!= CLI_HELP_COMMAND
) continue;
228 /* Compare all arguments */
229 if (argc
== entry
->argc
) {
230 for (j
= 0; j
< argc
; j
++) {
231 if (strcasecmp(argv
[j
],entry
->argv
[j
]) != 0) break;
234 cliOutputCommandHelp(help
,1);
238 if (group
== help
->group
) {
239 cliOutputCommandHelp(help
,0);
246 static void completionCallback(const char *buf
, linenoiseCompletions
*lc
) {
253 if (strncasecmp(buf
,"help ",5) == 0) {
255 while (isspace(buf
[startpos
])) startpos
++;
256 mask
= CLI_HELP_COMMAND
| CLI_HELP_GROUP
;
258 mask
= CLI_HELP_COMMAND
;
261 for (i
= 0; i
< helpEntriesLen
; i
++) {
262 if (!(helpEntries
[i
].type
& mask
)) continue;
264 matchlen
= strlen(buf
+startpos
);
265 if (strncasecmp(buf
+startpos
,helpEntries
[i
].full
,matchlen
) == 0) {
266 tmp
= sdsnewlen(buf
,startpos
);
267 tmp
= sdscat(tmp
,helpEntries
[i
].full
);
268 linenoiseAddCompletion(lc
,tmp
);
274 /*------------------------------------------------------------------------------
275 * Networking / parsing
276 *--------------------------------------------------------------------------- */
278 /* Send AUTH command to the server */
279 static int cliAuth() {
281 if (config
.auth
== NULL
) return REDIS_OK
;
283 reply
= redisCommand(context
,"AUTH %s",config
.auth
);
285 freeReplyObject(reply
);
291 /* Send SELECT dbnum to the server */
292 static int cliSelect() {
294 if (config
.dbnum
== 0) return REDIS_OK
;
296 reply
= redisCommand(context
,"SELECT %d",config
.dbnum
);
298 freeReplyObject(reply
);
304 /* Connect to the client. If force is not zero the connection is performed
305 * even if there is already a connected socket. */
306 static int cliConnect(int force
) {
307 if (context
== NULL
|| force
) {
311 if (config
.hostsocket
== NULL
) {
312 context
= redisConnect(config
.hostip
,config
.hostport
);
314 context
= redisConnectUnix(config
.hostsocket
);
318 fprintf(stderr
,"Could not connect to Redis at ");
319 if (config
.hostsocket
== NULL
)
320 fprintf(stderr
,"%s:%d: %s\n",config
.hostip
,config
.hostport
,context
->errstr
);
322 fprintf(stderr
,"%s: %s\n",config
.hostsocket
,context
->errstr
);
328 /* Do AUTH and select the right DB. */
329 if (cliAuth() != REDIS_OK
)
331 if (cliSelect() != REDIS_OK
)
337 static void cliPrintContextError() {
338 if (context
== NULL
) return;
339 fprintf(stderr
,"Error: %s\n",context
->errstr
);
342 static sds
cliFormatReplyTTY(redisReply
*r
, char *prefix
) {
343 sds out
= sdsempty();
345 case REDIS_REPLY_ERROR
:
346 out
= sdscatprintf(out
,"(error) %s\n", r
->str
);
348 case REDIS_REPLY_STATUS
:
349 out
= sdscat(out
,r
->str
);
350 out
= sdscat(out
,"\n");
352 case REDIS_REPLY_INTEGER
:
353 out
= sdscatprintf(out
,"(integer) %lld\n",r
->integer
);
355 case REDIS_REPLY_STRING
:
356 /* If you are producing output for the standard output we want
357 * a more interesting output with quoted characters and so forth */
358 out
= sdscatrepr(out
,r
->str
,r
->len
);
359 out
= sdscat(out
,"\n");
361 case REDIS_REPLY_NIL
:
362 out
= sdscat(out
,"(nil)\n");
364 case REDIS_REPLY_ARRAY
:
365 if (r
->elements
== 0) {
366 out
= sdscat(out
,"(empty list or set)\n");
368 unsigned int i
, idxlen
= 0;
374 /* Calculate chars needed to represent the largest index */
381 /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
382 memset(_prefixlen
,' ',idxlen
+2);
383 _prefixlen
[idxlen
+2] = '\0';
384 _prefix
= sdscat(sdsnew(prefix
),_prefixlen
);
386 /* Setup prefix format for every entry */
387 snprintf(_prefixfmt
,sizeof(_prefixfmt
),"%%s%%%dd) ",idxlen
);
389 for (i
= 0; i
< r
->elements
; i
++) {
390 /* Don't use the prefix for the first element, as the parent
391 * caller already prepended the index number. */
392 out
= sdscatprintf(out
,_prefixfmt
,i
== 0 ? "" : prefix
,i
+1);
394 /* Format the multi bulk entry */
395 tmp
= cliFormatReplyTTY(r
->element
[i
],_prefix
);
396 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
403 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
409 static sds
cliFormatReplyRaw(redisReply
*r
) {
410 sds out
= sdsempty(), tmp
;
414 case REDIS_REPLY_NIL
:
417 case REDIS_REPLY_ERROR
:
418 out
= sdscatlen(out
,r
->str
,r
->len
);
419 out
= sdscatlen(out
,"\n",1);
421 case REDIS_REPLY_STATUS
:
422 case REDIS_REPLY_STRING
:
423 out
= sdscatlen(out
,r
->str
,r
->len
);
425 case REDIS_REPLY_INTEGER
:
426 out
= sdscatprintf(out
,"%lld",r
->integer
);
428 case REDIS_REPLY_ARRAY
:
429 for (i
= 0; i
< r
->elements
; i
++) {
430 if (i
> 0) out
= sdscat(out
,config
.mb_delim
);
431 tmp
= cliFormatReplyRaw(r
->element
[i
]);
432 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
437 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
443 static sds
cliFormatReplyCSV(redisReply
*r
) {
446 sds out
= sdsempty();
448 case REDIS_REPLY_ERROR
:
449 out
= sdscat(out
,"ERROR,");
450 out
= sdscatrepr(out
,r
->str
,strlen(r
->str
));
452 case REDIS_REPLY_STATUS
:
453 out
= sdscatrepr(out
,r
->str
,r
->len
);
455 case REDIS_REPLY_INTEGER
:
456 out
= sdscatprintf(out
,"%lld",r
->integer
);
458 case REDIS_REPLY_STRING
:
459 out
= sdscatrepr(out
,r
->str
,r
->len
);
461 case REDIS_REPLY_NIL
:
462 out
= sdscat(out
,"NIL\n");
464 case REDIS_REPLY_ARRAY
:
465 for (i
= 0; i
< r
->elements
; i
++) {
466 sds tmp
= cliFormatReplyCSV(r
->element
[i
]);
467 out
= sdscatlen(out
,tmp
,sdslen(tmp
));
468 if (i
!= r
->elements
-1) out
= sdscat(out
,",");
473 fprintf(stderr
,"Unknown reply type: %d\n", r
->type
);
479 static int cliReadReply(int output_raw_strings
) {
485 if (redisGetReply(context
,&_reply
) != REDIS_OK
) {
488 if (config
.interactive
) {
489 /* Filter cases where we should reconnect */
490 if (context
->err
== REDIS_ERR_IO
&& errno
== ECONNRESET
)
492 if (context
->err
== REDIS_ERR_EOF
)
495 cliPrintContextError();
497 return REDIS_ERR
; /* avoid compiler warning */
500 reply
= (redisReply
*)_reply
;
502 /* Check if we need to connect to a different node and reissue the
504 if (config
.cluster_mode
&& reply
->type
== REDIS_REPLY_ERROR
&&
505 (!strncmp(reply
->str
,"MOVED",5) || !strcmp(reply
->str
,"ASK")))
507 char *p
= reply
->str
, *s
;
511 /* Comments show the position of the pointer as:
513 * [S] for pointer 's'
514 * [P] for pointer 'p'
516 s
= strchr(p
,' '); /* MOVED[S]3999 127.0.0.1:6381 */
517 p
= strchr(s
+1,' '); /* MOVED[S]3999[P]127.0.0.1:6381 */
520 s
= strchr(p
+1,':'); /* MOVED 3999[P]127.0.0.1[S]6381 */
522 sdsfree(config
.hostip
);
523 config
.hostip
= sdsnew(p
+1);
524 config
.hostport
= atoi(s
+1);
525 if (config
.interactive
)
526 printf("-> Redirected to slot [%d] located at %s:%d\n",
527 slot
, config
.hostip
, config
.hostport
);
528 config
.cluster_reissue_command
= 1;
532 if (output_raw_strings
) {
533 out
= cliFormatReplyRaw(reply
);
535 if (config
.output
== OUTPUT_RAW
) {
536 out
= cliFormatReplyRaw(reply
);
537 out
= sdscat(out
,"\n");
538 } else if (config
.output
== OUTPUT_STANDARD
) {
539 out
= cliFormatReplyTTY(reply
,"");
540 } else if (config
.output
== OUTPUT_CSV
) {
541 out
= cliFormatReplyCSV(reply
);
542 out
= sdscat(out
,"\n");
545 fwrite(out
,sdslen(out
),1,stdout
);
548 freeReplyObject(reply
);
552 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
553 char *command
= argv
[0];
557 if (!strcasecmp(command
,"help") || !strcasecmp(command
,"?")) {
558 cliOutputHelp(--argc
, ++argv
);
562 if (context
== NULL
) return REDIS_ERR
;
565 if (!strcasecmp(command
,"info") ||
566 (argc
== 2 && !strcasecmp(command
,"cluster") &&
567 (!strcasecmp(argv
[1],"nodes") ||
568 !strcasecmp(argv
[1],"info"))) ||
569 (argc
== 2 && !strcasecmp(command
,"client") &&
570 !strcasecmp(argv
[1],"list")))
576 if (!strcasecmp(command
,"shutdown")) config
.shutdown
= 1;
577 if (!strcasecmp(command
,"monitor")) config
.monitor_mode
= 1;
578 if (!strcasecmp(command
,"subscribe") ||
579 !strcasecmp(command
,"psubscribe")) config
.pubsub_mode
= 1;
581 /* Setup argument length */
582 argvlen
= malloc(argc
*sizeof(size_t));
583 for (j
= 0; j
< argc
; j
++)
584 argvlen
[j
] = sdslen(argv
[j
]);
587 redisAppendCommandArgv(context
,argc
,(const char**)argv
,argvlen
);
588 while (config
.monitor_mode
) {
589 if (cliReadReply(output_raw
) != REDIS_OK
) exit(1);
593 if (config
.pubsub_mode
) {
594 if (config
.output
!= OUTPUT_RAW
)
595 printf("Reading messages... (press Ctrl-C to quit)\n");
597 if (cliReadReply(output_raw
) != REDIS_OK
) exit(1);
601 if (cliReadReply(output_raw
) != REDIS_OK
) {
605 /* Store database number when SELECT was successfully executed. */
606 if (!strcasecmp(command
,"select") && argc
== 2) {
607 config
.dbnum
= atoi(argv
[1]);
611 if (config
.interval
) usleep(config
.interval
);
612 fflush(stdout
); /* Make it grep friendly */
619 /*------------------------------------------------------------------------------
621 *--------------------------------------------------------------------------- */
623 static int parseOptions(int argc
, char **argv
) {
626 for (i
= 1; i
< argc
; i
++) {
627 int lastarg
= i
==argc
-1;
629 if (!strcmp(argv
[i
],"-h") && !lastarg
) {
630 sdsfree(config
.hostip
);
631 config
.hostip
= sdsnew(argv
[++i
]);
632 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
634 } else if (!strcmp(argv
[i
],"--help")) {
636 } else if (!strcmp(argv
[i
],"-x")) {
638 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
639 config
.hostport
= atoi(argv
[++i
]);
640 } else if (!strcmp(argv
[i
],"-s") && !lastarg
) {
641 config
.hostsocket
= argv
[++i
];
642 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
643 config
.repeat
= strtoll(argv
[++i
],NULL
,10);
644 } else if (!strcmp(argv
[i
],"-i") && !lastarg
) {
645 double seconds
= atof(argv
[++i
]);
646 config
.interval
= seconds
*1000000;
647 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
648 config
.dbnum
= atoi(argv
[++i
]);
649 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
650 config
.auth
= argv
[++i
];
651 } else if (!strcmp(argv
[i
],"--raw")) {
652 config
.output
= OUTPUT_RAW
;
653 } else if (!strcmp(argv
[i
],"--csv")) {
654 config
.output
= OUTPUT_CSV
;
655 } else if (!strcmp(argv
[i
],"--latency")) {
656 config
.latency_mode
= 1;
657 } else if (!strcmp(argv
[i
],"--slave")) {
658 config
.slave_mode
= 1;
659 } else if (!strcmp(argv
[i
],"--bigkeys")) {
661 } else if (!strcmp(argv
[i
],"--eval") && !lastarg
) {
662 config
.eval
= argv
[++i
];
663 } else if (!strcmp(argv
[i
],"-c")) {
664 config
.cluster_mode
= 1;
665 } else if (!strcmp(argv
[i
],"-d") && !lastarg
) {
666 sdsfree(config
.mb_delim
);
667 config
.mb_delim
= sdsnew(argv
[++i
]);
668 } else if (!strcmp(argv
[i
],"-v") || !strcmp(argv
[i
], "--version")) {
669 sds version
= cliVersion();
670 printf("redis-cli %s\n", version
);
680 static sds
readArgFromStdin(void) {
682 sds arg
= sdsempty();
685 int nread
= read(fileno(stdin
),buf
,1024);
687 if (nread
== 0) break;
688 else if (nread
== -1) {
689 perror("Reading from standard input");
692 arg
= sdscatlen(arg
,buf
,nread
);
697 static void usage() {
698 sds version
= cliVersion();
702 "Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n"
703 " -h <hostname> Server hostname (default: 127.0.0.1)\n"
704 " -p <port> Server port (default: 6379)\n"
705 " -s <socket> Server socket (overrides hostname and port)\n"
706 " -a <password> Password to use when connecting to the server\n"
707 " -r <repeat> Execute specified command N times\n"
708 " -i <interval> When -r is used, waits <interval> seconds per command.\n"
709 " It is possible to specify sub-second times like -i 0.1.\n"
710 " -n <db> Database number\n"
711 " -x Read last argument from STDIN\n"
712 " -d <delimiter> Multi-bulk delimiter in for raw formatting (default: \\n)\n"
713 " -c Enable cluster mode (follow -ASK and -MOVED redirections)\n"
714 " --raw Use raw formatting for replies (default when STDOUT is not a tty)\n"
715 " --latency Enter a special mode continuously sampling latency.\n"
716 " --slave Simulate a slave showing commands received from the master.\n"
717 " --bigkeys Sample Redis keys looking for big keys.\n"
718 " --eval <file> Send an EVAL command using the Lua script at <file>.\n"
719 " --help Output this help and exit\n"
720 " --version Output version and exit\n"
723 " cat /etc/passwd | redis-cli -x set mypasswd\n"
724 " redis-cli get mypasswd\n"
725 " redis-cli -r 100 lpush mylist x\n"
726 " redis-cli -r 100 -i 1 info | grep used_memory_human:\n"
727 " redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3\n"
728 " (Note: when using --eval the comma separates KEYS[] from ARGV[] items)\n"
730 "When no command is given, redis-cli starts in interactive mode.\n"
731 "Type \"help\" in interactive mode for information on available commands.\n"
738 /* Turn the plain C strings into Sds strings */
739 static char **convertToSds(int count
, char** args
) {
741 char **sds
= zmalloc(sizeof(char*)*count
);
743 for(j
= 0; j
< count
; j
++)
744 sds
[j
] = sdsnew(args
[j
]);
749 #define LINE_BUFLEN 4096
751 sds historyfile
= NULL
;
757 config
.interactive
= 1;
758 linenoiseSetCompletionCallback(completionCallback
);
760 /* Only use history when stdin is a tty. */
761 if (isatty(fileno(stdin
))) {
764 if (getenv("HOME") != NULL
) {
765 historyfile
= sdscatprintf(sdsempty(),"%s/.rediscli_history",getenv("HOME"));
766 linenoiseHistoryLoad(historyfile
);
771 while((line
= linenoise(context
? config
.prompt
: "not connected> ")) != NULL
) {
772 if (line
[0] != '\0') {
773 argv
= sdssplitargs(line
,&argc
);
774 if (history
) linenoiseHistoryAdd(line
);
775 if (historyfile
) linenoiseHistorySave(historyfile
);
778 printf("Invalid argument(s)\n");
781 } else if (argc
> 0) {
782 if (strcasecmp(argv
[0],"quit") == 0 ||
783 strcasecmp(argv
[0],"exit") == 0)
786 } else if (argc
== 3 && !strcasecmp(argv
[0],"connect")) {
787 sdsfree(config
.hostip
);
788 config
.hostip
= sdsnew(argv
[1]);
789 config
.hostport
= atoi(argv
[2]);
791 } else if (argc
== 1 && !strcasecmp(argv
[0],"clear")) {
792 linenoiseClearScreen();
794 long long start_time
= mstime(), elapsed
;
795 int repeat
, skipargs
= 0;
797 repeat
= atoi(argv
[0]);
798 if (argc
> 1 && repeat
) {
805 config
.cluster_reissue_command
= 0;
806 if (cliSendCommand(argc
-skipargs
,argv
+skipargs
,repeat
)
811 /* If we still cannot send the command print error.
812 * We'll try to reconnect the next time. */
813 if (cliSendCommand(argc
-skipargs
,argv
+skipargs
,repeat
)
815 cliPrintContextError();
817 /* Issue the command again if we got redirected in cluster mode */
818 if (config
.cluster_mode
&& config
.cluster_reissue_command
) {
824 elapsed
= mstime()-start_time
;
825 if (elapsed
>= 500) {
826 printf("(%.2fs)\n",(double)elapsed
/1000);
830 /* Free the argument vector */
831 while(argc
--) sdsfree(argv
[argc
]);
834 /* linenoise() returns malloc-ed lines like readline() */
840 static int noninteractive(int argc
, char **argv
) {
842 if (config
.stdinarg
) {
843 argv
= zrealloc(argv
, (argc
+1)*sizeof(char*));
844 argv
[argc
] = readArgFromStdin();
845 retval
= cliSendCommand(argc
+1, argv
, config
.repeat
);
847 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
848 retval
= cliSendCommand(argc
, argv
, config
.repeat
);
853 static int evalMode(int argc
, char **argv
) {
854 sds script
= sdsempty();
859 int j
, got_comma
= 0, keys
= 0;
861 /* Load the script from the file, as an sds string. */
862 fp
= fopen(config
.eval
,"r");
865 "Can't open file '%s': %s\n", config
.eval
, strerror(errno
));
868 while((nread
= fread(buf
,1,sizeof(buf
),fp
)) != 0) {
869 script
= sdscatlen(script
,buf
,nread
);
873 /* Create our argument vector */
874 argv2
= zmalloc(sizeof(sds
)*(argc
+3));
875 argv2
[0] = sdsnew("EVAL");
877 for (j
= 0; j
< argc
; j
++) {
878 if (!got_comma
&& argv
[j
][0] == ',' && argv
[j
][1] == 0) {
882 argv2
[j
+3-got_comma
] = sdsnew(argv
[j
]);
883 if (!got_comma
) keys
++;
885 argv2
[2] = sdscatprintf(sdsempty(),"%d",keys
);
888 return cliSendCommand(argc
+3-got_comma
, argv2
, config
.repeat
);
891 static void latencyMode(void) {
893 long long start
, latency
, min
, max
, tot
, count
= 0;
896 if (!context
) exit(1);
899 reply
= redisCommand(context
,"PING");
901 fprintf(stderr
,"\nI/O error\n");
904 latency
= mstime()-start
;
905 freeReplyObject(reply
);
908 min
= max
= tot
= latency
;
909 avg
= (double) latency
;
911 if (latency
< min
) min
= latency
;
912 if (latency
> max
) max
= latency
;
914 avg
= (double) tot
/count
;
916 printf("\x1b[0G\x1b[2Kmin: %lld, max: %lld, avg: %.2f (%lld samples)",
917 min
, max
, avg
, count
);
923 static void slaveMode(void) {
924 /* To start we need to send the SYNC command and return the payload.
925 * The hiredis client lib does not understand this part of the protocol
926 * and we don't want to mess with its buffers, so everything is performed
927 * using direct low-level I/O. */
928 int fd
= context
->fd
;
931 unsigned long long payload
;
933 /* Send the SYNC command. */
934 if (write(fd
,"SYNC\r\n",6) != 6) {
935 fprintf(stderr
,"Error writing to master\n");
939 /* Read $<payload>\r\n, making sure to read just up to "\n" */
942 nread
= read(fd
,p
,1);
944 fprintf(stderr
,"Error reading bulk length while SYNCing\n");
947 if (*p
== '\n') break;
951 payload
= strtoull(buf
+1,NULL
,10);
952 fprintf(stderr
,"SYNC with master, discarding %lld bytes of bulk tranfer...\n",
955 /* Discard the payload. */
957 nread
= read(fd
,buf
,(payload
> sizeof(buf
)) ? sizeof(buf
) : payload
);
959 fprintf(stderr
,"Error reading RDB payload while SYNCing\n");
964 fprintf(stderr
,"SYNC done. Logging commands from master.\n");
966 /* Now we can use the hiredis to read the incoming protocol. */
967 config
.output
= OUTPUT_CSV
;
968 while (cliReadReply(0) == REDIS_OK
);
971 #define TYPE_STRING 0
977 static void findBigKeys(void) {
978 unsigned long long biggest
[5] = {0,0,0,0,0};
979 unsigned long long samples
= 0;
980 redisReply
*reply1
, *reply2
, *reply3
;
981 char *sizecmd
, *typename
[] = {"string","list","set","hash","zset"};
984 printf("\n# Press ctrl+c when you have had enough of it... :)\n");
985 printf("# You can use -i 0.1 to sleep 0.1 sec every 100 sampled keys\n");
986 printf("# in order to reduce server load (usually not needed).\n\n");
988 /* Sample with RANDOMKEY */
989 reply1
= redisCommand(context
,"RANDOMKEY");
990 if (reply1
== NULL
) {
991 fprintf(stderr
,"\nI/O error\n");
993 } else if (reply1
->type
== REDIS_REPLY_ERROR
) {
994 fprintf(stderr
, "RANDOMKEY error: %s\n",
998 /* Get the key type */
999 reply2
= redisCommand(context
,"TYPE %s",reply1
->str
);
1000 assert(reply2
&& reply2
->type
== REDIS_REPLY_STATUS
);
1003 /* Get the key "size" */
1004 if (!strcmp(reply2
->str
,"string")) {
1007 } else if (!strcmp(reply2
->str
,"list")) {
1010 } else if (!strcmp(reply2
->str
,"set")) {
1013 } else if (!strcmp(reply2
->str
,"hash")) {
1016 } else if (!strcmp(reply2
->str
,"zset")) {
1019 } else if (!strcmp(reply2
->str
,"none")) {
1020 freeReplyObject(reply1
);
1021 freeReplyObject(reply2
);
1022 freeReplyObject(reply3
);
1025 fprintf(stderr
, "Unknown key type '%s' for key '%s'\n",
1026 reply2
->str
, reply1
->str
);
1030 reply3
= redisCommand(context
,"%s %s", sizecmd
, reply1
->str
);
1031 if (reply3
&& reply3
->type
== REDIS_REPLY_INTEGER
) {
1032 if (biggest
[type
] < reply3
->integer
) {
1033 printf("[%6s] %s | biggest so far with size %llu\n",
1034 typename
[type
], reply1
->str
,
1035 (unsigned long long) reply3
->integer
);
1036 biggest
[type
] = reply3
->integer
;
1040 if ((samples
% 1000000) == 0)
1041 printf("(%llu keys sampled)\n", samples
);
1043 if ((samples
% 100) == 0 && config
.interval
)
1044 usleep(config
.interval
);
1046 freeReplyObject(reply1
);
1047 freeReplyObject(reply2
);
1048 if (reply3
) freeReplyObject(reply3
);
1052 int main(int argc
, char **argv
) {
1055 config
.hostip
= sdsnew("127.0.0.1");
1056 config
.hostport
= 6379;
1057 config
.hostsocket
= NULL
;
1059 config
.interval
= 0;
1061 config
.interactive
= 0;
1062 config
.shutdown
= 0;
1063 config
.monitor_mode
= 0;
1064 config
.pubsub_mode
= 0;
1065 config
.latency_mode
= 0;
1066 config
.cluster_mode
= 0;
1067 config
.slave_mode
= 0;
1069 config
.stdinarg
= 0;
1072 if (!isatty(fileno(stdout
)) && (getenv("FAKETTY") == NULL
))
1073 config
.output
= OUTPUT_RAW
;
1075 config
.output
= OUTPUT_STANDARD
;
1076 config
.mb_delim
= sdsnew("\n");
1079 firstarg
= parseOptions(argc
,argv
);
1083 /* Start in latency mode if appropriate */
1084 if (config
.latency_mode
) {
1089 /* Start in slave mode if appropriate */
1090 if (config
.slave_mode
) {
1096 if (config
.bigkeys
) {
1101 /* Start interactive mode when no command is provided */
1102 if (argc
== 0 && !config
.eval
) {
1103 /* Note that in repl mode we don't abort on connection error.
1104 * A new attempt will be performed for every command send. */
1109 /* Otherwise, we have some arguments to execute */
1110 if (cliConnect(0) != REDIS_OK
) exit(1);
1112 return evalMode(argc
,argv
);
1114 return noninteractive(argc
,convertToSds(argc
,argv
));