]> git.saurik.com Git - redis.git/blob - src/redis-cli.c
Version bumped to 2.9.5
[redis.git] / src / redis-cli.c
1 /* Redis CLI (command line interface)
2 *
3 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
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.
17 *
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.
29 */
30
31 #include "fmacros.h"
32 #include "version.h"
33
34 #include <stdio.h>
35 #include <string.h>
36 #include <stdlib.h>
37 #include <unistd.h>
38 #include <ctype.h>
39 #include <errno.h>
40 #include <sys/stat.h>
41 #include <sys/time.h>
42 #include <assert.h>
43
44 #include "hiredis.h"
45 #include "sds.h"
46 #include "zmalloc.h"
47 #include "linenoise.h"
48 #include "help.h"
49
50 #define REDIS_NOTUSED(V) ((void) V)
51
52 static redisContext *context;
53 static struct config {
54 char *hostip;
55 int hostport;
56 char *hostsocket;
57 long repeat;
58 long interval;
59 int dbnum;
60 int interactive;
61 int shutdown;
62 int monitor_mode;
63 int pubsub_mode;
64 int latency_mode;
65 int cluster_mode;
66 int cluster_reissue_command;
67 int stdinarg; /* get last arg from stdin. (-x option) */
68 char *auth;
69 int raw_output; /* output mode per command */
70 sds mb_delim;
71 char prompt[128];
72 char *eval;
73 } config;
74
75 static void usage();
76 char *redisGitSHA1(void);
77 char *redisGitDirty(void);
78
79 /*------------------------------------------------------------------------------
80 * Utility functions
81 *--------------------------------------------------------------------------- */
82
83 static long long mstime(void) {
84 struct timeval tv;
85 long long mst;
86
87 gettimeofday(&tv, NULL);
88 mst = ((long)tv.tv_sec)*1000;
89 mst += tv.tv_usec/1000;
90 return mst;
91 }
92
93 static void cliRefreshPrompt(void) {
94 int len;
95
96 if (config.hostsocket != NULL)
97 len = snprintf(config.prompt,sizeof(config.prompt),"redis %s",
98 config.hostsocket);
99 else
100 len = snprintf(config.prompt,sizeof(config.prompt),"redis %s:%d",
101 config.hostip, config.hostport);
102 /* Add [dbnum] if needed */
103 if (config.dbnum != 0)
104 len += snprintf(config.prompt+len,sizeof(config.prompt)-len,"[%d]",
105 config.dbnum);
106 snprintf(config.prompt+len,sizeof(config.prompt)-len,"> ");
107 }
108
109 /*------------------------------------------------------------------------------
110 * Help functions
111 *--------------------------------------------------------------------------- */
112
113 #define CLI_HELP_COMMAND 1
114 #define CLI_HELP_GROUP 2
115
116 typedef struct {
117 int type;
118 int argc;
119 sds *argv;
120 sds full;
121
122 /* Only used for help on commands */
123 struct commandHelp *org;
124 } helpEntry;
125
126 static helpEntry *helpEntries;
127 static int helpEntriesLen;
128
129 static sds cliVersion() {
130 sds version;
131 version = sdscatprintf(sdsempty(), "%s", REDIS_VERSION);
132
133 /* Add git commit and working tree status when available */
134 if (strtoll(redisGitSHA1(),NULL,16)) {
135 version = sdscatprintf(version, " (git:%s", redisGitSHA1());
136 if (strtoll(redisGitDirty(),NULL,10))
137 version = sdscatprintf(version, "-dirty");
138 version = sdscat(version, ")");
139 }
140 return version;
141 }
142
143 static void cliInitHelp() {
144 int commandslen = sizeof(commandHelp)/sizeof(struct commandHelp);
145 int groupslen = sizeof(commandGroups)/sizeof(char*);
146 int i, len, pos = 0;
147 helpEntry tmp;
148
149 helpEntriesLen = len = commandslen+groupslen;
150 helpEntries = malloc(sizeof(helpEntry)*len);
151
152 for (i = 0; i < groupslen; i++) {
153 tmp.argc = 1;
154 tmp.argv = malloc(sizeof(sds));
155 tmp.argv[0] = sdscatprintf(sdsempty(),"@%s",commandGroups[i]);
156 tmp.full = tmp.argv[0];
157 tmp.type = CLI_HELP_GROUP;
158 tmp.org = NULL;
159 helpEntries[pos++] = tmp;
160 }
161
162 for (i = 0; i < commandslen; i++) {
163 tmp.argv = sdssplitargs(commandHelp[i].name,&tmp.argc);
164 tmp.full = sdsnew(commandHelp[i].name);
165 tmp.type = CLI_HELP_COMMAND;
166 tmp.org = &commandHelp[i];
167 helpEntries[pos++] = tmp;
168 }
169 }
170
171 /* Output command help to stdout. */
172 static void cliOutputCommandHelp(struct commandHelp *help, int group) {
173 printf("\r\n \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\r\n", help->name, help->params);
174 printf(" \x1b[33msummary:\x1b[0m %s\r\n", help->summary);
175 printf(" \x1b[33msince:\x1b[0m %s\r\n", help->since);
176 if (group) {
177 printf(" \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups[help->group]);
178 }
179 }
180
181 /* Print generic help. */
182 static void cliOutputGenericHelp() {
183 sds version = cliVersion();
184 printf(
185 "redis-cli %s\r\n"
186 "Type: \"help @<group>\" to get a list of commands in <group>\r\n"
187 " \"help <command>\" for help on <command>\r\n"
188 " \"help <tab>\" to get a list of possible help topics\r\n"
189 " \"quit\" to exit\r\n",
190 version
191 );
192 sdsfree(version);
193 }
194
195 /* Output all command help, filtering by group or command name. */
196 static void cliOutputHelp(int argc, char **argv) {
197 int i, j, len;
198 int group = -1;
199 helpEntry *entry;
200 struct commandHelp *help;
201
202 if (argc == 0) {
203 cliOutputGenericHelp();
204 return;
205 } else if (argc > 0 && argv[0][0] == '@') {
206 len = sizeof(commandGroups)/sizeof(char*);
207 for (i = 0; i < len; i++) {
208 if (strcasecmp(argv[0]+1,commandGroups[i]) == 0) {
209 group = i;
210 break;
211 }
212 }
213 }
214
215 assert(argc > 0);
216 for (i = 0; i < helpEntriesLen; i++) {
217 entry = &helpEntries[i];
218 if (entry->type != CLI_HELP_COMMAND) continue;
219
220 help = entry->org;
221 if (group == -1) {
222 /* Compare all arguments */
223 if (argc == entry->argc) {
224 for (j = 0; j < argc; j++) {
225 if (strcasecmp(argv[j],entry->argv[j]) != 0) break;
226 }
227 if (j == argc) {
228 cliOutputCommandHelp(help,1);
229 }
230 }
231 } else {
232 if (group == help->group) {
233 cliOutputCommandHelp(help,0);
234 }
235 }
236 }
237 printf("\r\n");
238 }
239
240 static void completionCallback(const char *buf, linenoiseCompletions *lc) {
241 size_t startpos = 0;
242 int mask;
243 int i;
244 size_t matchlen;
245 sds tmp;
246
247 if (strncasecmp(buf,"help ",5) == 0) {
248 startpos = 5;
249 while (isspace(buf[startpos])) startpos++;
250 mask = CLI_HELP_COMMAND | CLI_HELP_GROUP;
251 } else {
252 mask = CLI_HELP_COMMAND;
253 }
254
255 for (i = 0; i < helpEntriesLen; i++) {
256 if (!(helpEntries[i].type & mask)) continue;
257
258 matchlen = strlen(buf+startpos);
259 if (strncasecmp(buf+startpos,helpEntries[i].full,matchlen) == 0) {
260 tmp = sdsnewlen(buf,startpos);
261 tmp = sdscat(tmp,helpEntries[i].full);
262 linenoiseAddCompletion(lc,tmp);
263 sdsfree(tmp);
264 }
265 }
266 }
267
268 /*------------------------------------------------------------------------------
269 * Networking / parsing
270 *--------------------------------------------------------------------------- */
271
272 /* Send AUTH command to the server */
273 static int cliAuth() {
274 redisReply *reply;
275 if (config.auth == NULL) return REDIS_OK;
276
277 reply = redisCommand(context,"AUTH %s",config.auth);
278 if (reply != NULL) {
279 freeReplyObject(reply);
280 return REDIS_OK;
281 }
282 return REDIS_ERR;
283 }
284
285 /* Send SELECT dbnum to the server */
286 static int cliSelect() {
287 redisReply *reply;
288 if (config.dbnum == 0) return REDIS_OK;
289
290 reply = redisCommand(context,"SELECT %d",config.dbnum);
291 if (reply != NULL) {
292 freeReplyObject(reply);
293 return REDIS_OK;
294 }
295 return REDIS_ERR;
296 }
297
298 /* Connect to the client. If force is not zero the connection is performed
299 * even if there is already a connected socket. */
300 static int cliConnect(int force) {
301 if (context == NULL || force) {
302 if (context != NULL)
303 redisFree(context);
304
305 if (config.hostsocket == NULL) {
306 context = redisConnect(config.hostip,config.hostport);
307 } else {
308 context = redisConnectUnix(config.hostsocket);
309 }
310
311 if (context->err) {
312 fprintf(stderr,"Could not connect to Redis at ");
313 if (config.hostsocket == NULL)
314 fprintf(stderr,"%s:%d: %s\n",config.hostip,config.hostport,context->errstr);
315 else
316 fprintf(stderr,"%s: %s\n",config.hostsocket,context->errstr);
317 redisFree(context);
318 context = NULL;
319 return REDIS_ERR;
320 }
321
322 /* Do AUTH and select the right DB. */
323 if (cliAuth() != REDIS_OK)
324 return REDIS_ERR;
325 if (cliSelect() != REDIS_OK)
326 return REDIS_ERR;
327 }
328 return REDIS_OK;
329 }
330
331 static void cliPrintContextError() {
332 if (context == NULL) return;
333 fprintf(stderr,"Error: %s\n",context->errstr);
334 }
335
336 static sds cliFormatReplyTTY(redisReply *r, char *prefix) {
337 sds out = sdsempty();
338 switch (r->type) {
339 case REDIS_REPLY_ERROR:
340 out = sdscatprintf(out,"(error) %s\n", r->str);
341 break;
342 case REDIS_REPLY_STATUS:
343 out = sdscat(out,r->str);
344 out = sdscat(out,"\n");
345 break;
346 case REDIS_REPLY_INTEGER:
347 out = sdscatprintf(out,"(integer) %lld\n",r->integer);
348 break;
349 case REDIS_REPLY_STRING:
350 /* If you are producing output for the standard output we want
351 * a more interesting output with quoted characters and so forth */
352 out = sdscatrepr(out,r->str,r->len);
353 out = sdscat(out,"\n");
354 break;
355 case REDIS_REPLY_NIL:
356 out = sdscat(out,"(nil)\n");
357 break;
358 case REDIS_REPLY_ARRAY:
359 if (r->elements == 0) {
360 out = sdscat(out,"(empty list or set)\n");
361 } else {
362 unsigned int i, idxlen = 0;
363 char _prefixlen[16];
364 char _prefixfmt[16];
365 sds _prefix;
366 sds tmp;
367
368 /* Calculate chars needed to represent the largest index */
369 i = r->elements;
370 do {
371 idxlen++;
372 i /= 10;
373 } while(i);
374
375 /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
376 memset(_prefixlen,' ',idxlen+2);
377 _prefixlen[idxlen+2] = '\0';
378 _prefix = sdscat(sdsnew(prefix),_prefixlen);
379
380 /* Setup prefix format for every entry */
381 snprintf(_prefixfmt,sizeof(_prefixfmt),"%%s%%%dd) ",idxlen);
382
383 for (i = 0; i < r->elements; i++) {
384 /* Don't use the prefix for the first element, as the parent
385 * caller already prepended the index number. */
386 out = sdscatprintf(out,_prefixfmt,i == 0 ? "" : prefix,i+1);
387
388 /* Format the multi bulk entry */
389 tmp = cliFormatReplyTTY(r->element[i],_prefix);
390 out = sdscatlen(out,tmp,sdslen(tmp));
391 sdsfree(tmp);
392 }
393 sdsfree(_prefix);
394 }
395 break;
396 default:
397 fprintf(stderr,"Unknown reply type: %d\n", r->type);
398 exit(1);
399 }
400 return out;
401 }
402
403 static sds cliFormatReplyRaw(redisReply *r) {
404 sds out = sdsempty(), tmp;
405 size_t i;
406
407 switch (r->type) {
408 case REDIS_REPLY_NIL:
409 /* Nothing... */
410 break;
411 case REDIS_REPLY_ERROR:
412 out = sdscatlen(out,r->str,r->len);
413 out = sdscatlen(out,"\n",1);
414 break;
415 case REDIS_REPLY_STATUS:
416 case REDIS_REPLY_STRING:
417 out = sdscatlen(out,r->str,r->len);
418 break;
419 case REDIS_REPLY_INTEGER:
420 out = sdscatprintf(out,"%lld",r->integer);
421 break;
422 case REDIS_REPLY_ARRAY:
423 for (i = 0; i < r->elements; i++) {
424 if (i > 0) out = sdscat(out,config.mb_delim);
425 tmp = cliFormatReplyRaw(r->element[i]);
426 out = sdscatlen(out,tmp,sdslen(tmp));
427 sdsfree(tmp);
428 }
429 break;
430 default:
431 fprintf(stderr,"Unknown reply type: %d\n", r->type);
432 exit(1);
433 }
434 return out;
435 }
436
437 static int cliReadReply(int output_raw_strings) {
438 void *_reply;
439 redisReply *reply;
440 sds out;
441 int output = 1;
442
443 if (redisGetReply(context,&_reply) != REDIS_OK) {
444 if (config.shutdown)
445 return REDIS_OK;
446 if (config.interactive) {
447 /* Filter cases where we should reconnect */
448 if (context->err == REDIS_ERR_IO && errno == ECONNRESET)
449 return REDIS_ERR;
450 if (context->err == REDIS_ERR_EOF)
451 return REDIS_ERR;
452 }
453 cliPrintContextError();
454 exit(1);
455 return REDIS_ERR; /* avoid compiler warning */
456 }
457
458 reply = (redisReply*)_reply;
459
460 /* Check if we need to connect to a different node and reissue the request. */
461 if (config.cluster_mode && reply->type == REDIS_REPLY_ERROR &&
462 (!strncmp(reply->str,"MOVED",5) || !strcmp(reply->str,"ASK")))
463 {
464 char *p = reply->str, *s;
465 int slot;
466
467 output = 0;
468 /* Comments show the position of the pointer as:
469 *
470 * [S] for pointer 's'
471 * [P] for pointer 'p'
472 */
473 s = strchr(p,' '); /* MOVED[S]3999 127.0.0.1:6381 */
474 p = strchr(s+1,' '); /* MOVED[S]3999[P]127.0.0.1:6381 */
475 *p = '\0';
476 slot = atoi(s+1);
477 s = strchr(p+1,':'); /* MOVED 3999[P]127.0.0.1[S]6381 */
478 *s = '\0';
479 sdsfree(config.hostip);
480 config.hostip = sdsnew(p+1);
481 config.hostport = atoi(s+1);
482 if (config.interactive)
483 printf("-> Redirected to slot [%d] located at %s:%d\n",
484 slot, config.hostip, config.hostport);
485 config.cluster_reissue_command = 1;
486 }
487
488 if (output) {
489 if (output_raw_strings) {
490 out = cliFormatReplyRaw(reply);
491 } else {
492 if (config.raw_output) {
493 out = cliFormatReplyRaw(reply);
494 out = sdscat(out,"\n");
495 } else {
496 out = cliFormatReplyTTY(reply,"");
497 }
498 }
499 fwrite(out,sdslen(out),1,stdout);
500 sdsfree(out);
501 }
502 freeReplyObject(reply);
503 return REDIS_OK;
504 }
505
506 static int cliSendCommand(int argc, char **argv, int repeat) {
507 char *command = argv[0];
508 size_t *argvlen;
509 int j, output_raw;
510
511 if (!strcasecmp(command,"help") || !strcasecmp(command,"?")) {
512 cliOutputHelp(--argc, ++argv);
513 return REDIS_OK;
514 }
515
516 if (context == NULL) return REDIS_ERR;
517
518 output_raw = 0;
519 if (!strcasecmp(command,"info") ||
520 (argc == 2 && !strcasecmp(command,"cluster") &&
521 (!strcasecmp(argv[1],"nodes") ||
522 !strcasecmp(argv[1],"info"))) ||
523 (argc == 2 && !strcasecmp(command,"client") &&
524 !strcasecmp(argv[1],"list")))
525
526 {
527 output_raw = 1;
528 }
529
530 if (!strcasecmp(command,"shutdown")) config.shutdown = 1;
531 if (!strcasecmp(command,"monitor")) config.monitor_mode = 1;
532 if (!strcasecmp(command,"subscribe") ||
533 !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1;
534
535 /* Setup argument length */
536 argvlen = malloc(argc*sizeof(size_t));
537 for (j = 0; j < argc; j++)
538 argvlen[j] = sdslen(argv[j]);
539
540 while(repeat--) {
541 redisAppendCommandArgv(context,argc,(const char**)argv,argvlen);
542 while (config.monitor_mode) {
543 if (cliReadReply(output_raw) != REDIS_OK) exit(1);
544 fflush(stdout);
545 }
546
547 if (config.pubsub_mode) {
548 if (!config.raw_output)
549 printf("Reading messages... (press Ctrl-C to quit)\n");
550 while (1) {
551 if (cliReadReply(output_raw) != REDIS_OK) exit(1);
552 }
553 }
554
555 if (cliReadReply(output_raw) != REDIS_OK) {
556 free(argvlen);
557 return REDIS_ERR;
558 } else {
559 /* Store database number when SELECT was successfully executed. */
560 if (!strcasecmp(command,"select") && argc == 2) {
561 config.dbnum = atoi(argv[1]);
562 cliRefreshPrompt();
563 }
564 }
565 if (config.interval) usleep(config.interval);
566 fflush(stdout); /* Make it grep friendly */
567 }
568
569 free(argvlen);
570 return REDIS_OK;
571 }
572
573 /*------------------------------------------------------------------------------
574 * User interface
575 *--------------------------------------------------------------------------- */
576
577 static int parseOptions(int argc, char **argv) {
578 int i;
579
580 for (i = 1; i < argc; i++) {
581 int lastarg = i==argc-1;
582
583 if (!strcmp(argv[i],"-h") && !lastarg) {
584 sdsfree(config.hostip);
585 config.hostip = sdsnew(argv[++i]);
586 } else if (!strcmp(argv[i],"-h") && lastarg) {
587 usage();
588 } else if (!strcmp(argv[i],"--help")) {
589 usage();
590 } else if (!strcmp(argv[i],"-x")) {
591 config.stdinarg = 1;
592 } else if (!strcmp(argv[i],"-p") && !lastarg) {
593 config.hostport = atoi(argv[++i]);
594 } else if (!strcmp(argv[i],"-s") && !lastarg) {
595 config.hostsocket = argv[++i];
596 } else if (!strcmp(argv[i],"-r") && !lastarg) {
597 config.repeat = strtoll(argv[++i],NULL,10);
598 } else if (!strcmp(argv[i],"-i") && !lastarg) {
599 double seconds = atof(argv[++i]);
600 config.interval = seconds*1000000;
601 } else if (!strcmp(argv[i],"-n") && !lastarg) {
602 config.dbnum = atoi(argv[++i]);
603 } else if (!strcmp(argv[i],"-a") && !lastarg) {
604 config.auth = argv[++i];
605 } else if (!strcmp(argv[i],"--raw")) {
606 config.raw_output = 1;
607 } else if (!strcmp(argv[i],"--latency")) {
608 config.latency_mode = 1;
609 } else if (!strcmp(argv[i],"--eval") && !lastarg) {
610 config.eval = argv[++i];
611 } else if (!strcmp(argv[i],"-c")) {
612 config.cluster_mode = 1;
613 } else if (!strcmp(argv[i],"-d") && !lastarg) {
614 sdsfree(config.mb_delim);
615 config.mb_delim = sdsnew(argv[++i]);
616 } else if (!strcmp(argv[i],"-v") || !strcmp(argv[i], "--version")) {
617 sds version = cliVersion();
618 printf("redis-cli %s\n", version);
619 sdsfree(version);
620 exit(0);
621 } else {
622 break;
623 }
624 }
625 return i;
626 }
627
628 static sds readArgFromStdin(void) {
629 char buf[1024];
630 sds arg = sdsempty();
631
632 while(1) {
633 int nread = read(fileno(stdin),buf,1024);
634
635 if (nread == 0) break;
636 else if (nread == -1) {
637 perror("Reading from standard input");
638 exit(1);
639 }
640 arg = sdscatlen(arg,buf,nread);
641 }
642 return arg;
643 }
644
645 static void usage() {
646 sds version = cliVersion();
647 fprintf(stderr,
648 "redis-cli %s\n"
649 "\n"
650 "Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n"
651 " -h <hostname> Server hostname (default: 127.0.0.1)\n"
652 " -p <port> Server port (default: 6379)\n"
653 " -s <socket> Server socket (overrides hostname and port)\n"
654 " -a <password> Password to use when connecting to the server\n"
655 " -r <repeat> Execute specified command N times\n"
656 " -i <interval> When -r is used, waits <interval> seconds per command.\n"
657 " It is possible to specify sub-second times like -i 0.1.\n"
658 " -n <db> Database number\n"
659 " -x Read last argument from STDIN\n"
660 " -d <delimiter> Multi-bulk delimiter in for raw formatting (default: \\n)\n"
661 " -c Enable cluster mode (follow -ASK and -MOVED redirections)\n"
662 " --raw Use raw formatting for replies (default when STDOUT is not a tty)\n"
663 " --latency Enter a special mode continuously sampling latency.\n"
664 " --eval <file> Send an EVAL command using the Lua script at <file>.\n"
665 " --help Output this help and exit\n"
666 " --version Output version and exit\n"
667 "\n"
668 "Examples:\n"
669 " cat /etc/passwd | redis-cli -x set mypasswd\n"
670 " redis-cli get mypasswd\n"
671 " redis-cli -r 100 lpush mylist x\n"
672 " redis-cli -r 100 -i 1 info | grep used_memory_human:\n"
673 " redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3\n"
674 " (Note: when using --eval the comma separates KEYS[] from ARGV[] items)\n"
675 "\n"
676 "When no command is given, redis-cli starts in interactive mode.\n"
677 "Type \"help\" in interactive mode for information on available commands.\n"
678 "\n",
679 version);
680 sdsfree(version);
681 exit(1);
682 }
683
684 /* Turn the plain C strings into Sds strings */
685 static char **convertToSds(int count, char** args) {
686 int j;
687 char **sds = zmalloc(sizeof(char*)*count);
688
689 for(j = 0; j < count; j++)
690 sds[j] = sdsnew(args[j]);
691
692 return sds;
693 }
694
695 #define LINE_BUFLEN 4096
696 static void repl() {
697 sds historyfile = NULL;
698 int history = 0;
699 char *line;
700 int argc;
701 sds *argv;
702
703 config.interactive = 1;
704 linenoiseSetCompletionCallback(completionCallback);
705
706 /* Only use history when stdin is a tty. */
707 if (isatty(fileno(stdin))) {
708 history = 1;
709
710 if (getenv("HOME") != NULL) {
711 historyfile = sdscatprintf(sdsempty(),"%s/.rediscli_history",getenv("HOME"));
712 linenoiseHistoryLoad(historyfile);
713 }
714 }
715
716 cliRefreshPrompt();
717 while((line = linenoise(context ? config.prompt : "not connected> ")) != NULL) {
718 if (line[0] != '\0') {
719 argv = sdssplitargs(line,&argc);
720 if (history) linenoiseHistoryAdd(line);
721 if (historyfile) linenoiseHistorySave(historyfile);
722
723 if (argv == NULL) {
724 printf("Invalid argument(s)\n");
725 free(line);
726 continue;
727 } else if (argc > 0) {
728 if (strcasecmp(argv[0],"quit") == 0 ||
729 strcasecmp(argv[0],"exit") == 0)
730 {
731 exit(0);
732 } else if (argc == 3 && !strcasecmp(argv[0],"connect")) {
733 sdsfree(config.hostip);
734 config.hostip = sdsnew(argv[1]);
735 config.hostport = atoi(argv[2]);
736 cliConnect(1);
737 } else if (argc == 1 && !strcasecmp(argv[0],"clear")) {
738 linenoiseClearScreen();
739 } else {
740 long long start_time = mstime(), elapsed;
741 int repeat, skipargs = 0;
742
743 repeat = atoi(argv[0]);
744 if (argc > 1 && repeat) {
745 skipargs = 1;
746 } else {
747 repeat = 1;
748 }
749
750 while (1) {
751 config.cluster_reissue_command = 0;
752 if (cliSendCommand(argc-skipargs,argv+skipargs,repeat)
753 != REDIS_OK)
754 {
755 cliConnect(1);
756
757 /* If we still cannot send the command print error.
758 * We'll try to reconnect the next time. */
759 if (cliSendCommand(argc-skipargs,argv+skipargs,repeat)
760 != REDIS_OK)
761 cliPrintContextError();
762 }
763 /* Issue the command again if we got redirected in cluster mode */
764 if (config.cluster_mode && config.cluster_reissue_command) {
765 cliConnect(1);
766 } else {
767 break;
768 }
769 }
770 elapsed = mstime()-start_time;
771 if (elapsed >= 500) {
772 printf("(%.2fs)\n",(double)elapsed/1000);
773 }
774 }
775 }
776 /* Free the argument vector */
777 while(argc--) sdsfree(argv[argc]);
778 zfree(argv);
779 }
780 /* linenoise() returns malloc-ed lines like readline() */
781 free(line);
782 }
783 exit(0);
784 }
785
786 static int noninteractive(int argc, char **argv) {
787 int retval = 0;
788 if (config.stdinarg) {
789 argv = zrealloc(argv, (argc+1)*sizeof(char*));
790 argv[argc] = readArgFromStdin();
791 retval = cliSendCommand(argc+1, argv, config.repeat);
792 } else {
793 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
794 retval = cliSendCommand(argc, argv, config.repeat);
795 }
796 return retval;
797 }
798
799 static int evalMode(int argc, char **argv) {
800 sds script = sdsempty();
801 FILE *fp;
802 char buf[1024];
803 size_t nread;
804 char **argv2;
805 int j, got_comma = 0, keys = 0;
806
807 /* Load the script from the file, as an sds string. */
808 fp = fopen(config.eval,"r");
809 if (!fp) {
810 fprintf(stderr,
811 "Can't open file '%s': %s\n", config.eval, strerror(errno));
812 exit(1);
813 }
814 while((nread = fread(buf,1,sizeof(buf),fp)) != 0) {
815 script = sdscatlen(script,buf,nread);
816 }
817 fclose(fp);
818
819 /* Create our argument vector */
820 argv2 = zmalloc(sizeof(sds)*(argc+3));
821 argv2[0] = sdsnew("EVAL");
822 argv2[1] = script;
823 for (j = 0; j < argc; j++) {
824 if (!got_comma && argv[j][0] == ',' && argv[j][1] == 0) {
825 got_comma = 1;
826 continue;
827 }
828 argv2[j+3-got_comma] = sdsnew(argv[j]);
829 if (!got_comma) keys++;
830 }
831 argv2[2] = sdscatprintf(sdsempty(),"%d",keys);
832
833 /* Call it */
834 return cliSendCommand(argc+3-got_comma, argv2, config.repeat);
835 }
836
837 static void latencyMode(void) {
838 redisReply *reply;
839 long long start, latency, min, max, tot, count = 0;
840 double avg;
841
842 if (!context) exit(1);
843 while(1) {
844 start = mstime();
845 reply = redisCommand(context,"PING");
846 if (reply == NULL) {
847 fprintf(stderr,"\nI/O error\n");
848 exit(1);
849 }
850 latency = mstime()-start;
851 freeReplyObject(reply);
852 count++;
853 if (count == 1) {
854 min = max = tot = latency;
855 avg = (double) latency;
856 } else {
857 if (latency < min) min = latency;
858 if (latency > max) max = latency;
859 tot += latency;
860 avg = (double) tot/count;
861 }
862 printf("\x1b[0G\x1b[2Kmin: %lld, max: %lld, avg: %.2f (%lld samples)",
863 min, max, avg, count);
864 fflush(stdout);
865 usleep(10000);
866 }
867 }
868
869 int main(int argc, char **argv) {
870 int firstarg;
871
872 config.hostip = sdsnew("127.0.0.1");
873 config.hostport = 6379;
874 config.hostsocket = NULL;
875 config.repeat = 1;
876 config.interval = 0;
877 config.dbnum = 0;
878 config.interactive = 0;
879 config.shutdown = 0;
880 config.monitor_mode = 0;
881 config.pubsub_mode = 0;
882 config.latency_mode = 0;
883 config.cluster_mode = 0;
884 config.stdinarg = 0;
885 config.auth = NULL;
886 config.eval = NULL;
887 config.raw_output = !isatty(fileno(stdout)) && (getenv("FAKETTY") == NULL);
888 config.mb_delim = sdsnew("\n");
889 cliInitHelp();
890
891 firstarg = parseOptions(argc,argv);
892 argc -= firstarg;
893 argv += firstarg;
894
895 /* Start in latency mode if appropriate */
896 if (config.latency_mode) {
897 cliConnect(0);
898 latencyMode();
899 }
900
901 /* Start interactive mode when no command is provided */
902 if (argc == 0 && !config.eval) {
903 /* Note that in repl mode we don't abort on connection error.
904 * A new attempt will be performed for every command send. */
905 cliConnect(0);
906 repl();
907 }
908
909 /* Otherwise, we have some arguments to execute */
910 if (cliConnect(0) != REDIS_OK) exit(1);
911 if (config.eval) {
912 return evalMode(argc,argv);
913 } else {
914 return noninteractive(argc,convertToSds(argc,argv));
915 }
916 }