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