]> git.saurik.com Git - redis.git/blob - src/redis-cli.c
redis-cli pipe mode: handle EINTR properly as well so that SIGSTOP/SIGCONT are handle...
[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 #include "anet.h"
50 #include "ae.h"
51
52 #define REDIS_NOTUSED(V) ((void) V)
53
54 #define OUTPUT_STANDARD 0
55 #define OUTPUT_RAW 1
56 #define OUTPUT_CSV 2
57
58 static redisContext *context;
59 static struct config {
60 char *hostip;
61 int hostport;
62 char *hostsocket;
63 long repeat;
64 long interval;
65 int dbnum;
66 int interactive;
67 int shutdown;
68 int monitor_mode;
69 int pubsub_mode;
70 int latency_mode;
71 int cluster_mode;
72 int cluster_reissue_command;
73 int slave_mode;
74 int pipe_mode;
75 int bigkeys;
76 int stdinarg; /* get last arg from stdin. (-x option) */
77 char *auth;
78 int output; /* output mode, see OUTPUT_* defines */
79 sds mb_delim;
80 char prompt[128];
81 char *eval;
82 } config;
83
84 static void usage();
85 char *redisGitSHA1(void);
86 char *redisGitDirty(void);
87
88 /*------------------------------------------------------------------------------
89 * Utility functions
90 *--------------------------------------------------------------------------- */
91
92 static long long mstime(void) {
93 struct timeval tv;
94 long long mst;
95
96 gettimeofday(&tv, NULL);
97 mst = ((long)tv.tv_sec)*1000;
98 mst += tv.tv_usec/1000;
99 return mst;
100 }
101
102 static void cliRefreshPrompt(void) {
103 int len;
104
105 if (config.hostsocket != NULL)
106 len = snprintf(config.prompt,sizeof(config.prompt),"redis %s",
107 config.hostsocket);
108 else
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]",
114 config.dbnum);
115 snprintf(config.prompt+len,sizeof(config.prompt)-len,"> ");
116 }
117
118 /*------------------------------------------------------------------------------
119 * Help functions
120 *--------------------------------------------------------------------------- */
121
122 #define CLI_HELP_COMMAND 1
123 #define CLI_HELP_GROUP 2
124
125 typedef struct {
126 int type;
127 int argc;
128 sds *argv;
129 sds full;
130
131 /* Only used for help on commands */
132 struct commandHelp *org;
133 } helpEntry;
134
135 static helpEntry *helpEntries;
136 static int helpEntriesLen;
137
138 static sds cliVersion() {
139 sds version;
140 version = sdscatprintf(sdsempty(), "%s", REDIS_VERSION);
141
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, ")");
148 }
149 return version;
150 }
151
152 static void cliInitHelp() {
153 int commandslen = sizeof(commandHelp)/sizeof(struct commandHelp);
154 int groupslen = sizeof(commandGroups)/sizeof(char*);
155 int i, len, pos = 0;
156 helpEntry tmp;
157
158 helpEntriesLen = len = commandslen+groupslen;
159 helpEntries = malloc(sizeof(helpEntry)*len);
160
161 for (i = 0; i < groupslen; i++) {
162 tmp.argc = 1;
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;
167 tmp.org = NULL;
168 helpEntries[pos++] = tmp;
169 }
170
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;
177 }
178 }
179
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);
185 if (group) {
186 printf(" \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups[help->group]);
187 }
188 }
189
190 /* Print generic help. */
191 static void cliOutputGenericHelp() {
192 sds version = cliVersion();
193 printf(
194 "redis-cli %s\r\n"
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",
199 version
200 );
201 sdsfree(version);
202 }
203
204 /* Output all command help, filtering by group or command name. */
205 static void cliOutputHelp(int argc, char **argv) {
206 int i, j, len;
207 int group = -1;
208 helpEntry *entry;
209 struct commandHelp *help;
210
211 if (argc == 0) {
212 cliOutputGenericHelp();
213 return;
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) {
218 group = i;
219 break;
220 }
221 }
222 }
223
224 assert(argc > 0);
225 for (i = 0; i < helpEntriesLen; i++) {
226 entry = &helpEntries[i];
227 if (entry->type != CLI_HELP_COMMAND) continue;
228
229 help = entry->org;
230 if (group == -1) {
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;
235 }
236 if (j == argc) {
237 cliOutputCommandHelp(help,1);
238 }
239 }
240 } else {
241 if (group == help->group) {
242 cliOutputCommandHelp(help,0);
243 }
244 }
245 }
246 printf("\r\n");
247 }
248
249 static void completionCallback(const char *buf, linenoiseCompletions *lc) {
250 size_t startpos = 0;
251 int mask;
252 int i;
253 size_t matchlen;
254 sds tmp;
255
256 if (strncasecmp(buf,"help ",5) == 0) {
257 startpos = 5;
258 while (isspace(buf[startpos])) startpos++;
259 mask = CLI_HELP_COMMAND | CLI_HELP_GROUP;
260 } else {
261 mask = CLI_HELP_COMMAND;
262 }
263
264 for (i = 0; i < helpEntriesLen; i++) {
265 if (!(helpEntries[i].type & mask)) continue;
266
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);
272 sdsfree(tmp);
273 }
274 }
275 }
276
277 /*------------------------------------------------------------------------------
278 * Networking / parsing
279 *--------------------------------------------------------------------------- */
280
281 /* Send AUTH command to the server */
282 static int cliAuth() {
283 redisReply *reply;
284 if (config.auth == NULL) return REDIS_OK;
285
286 reply = redisCommand(context,"AUTH %s",config.auth);
287 if (reply != NULL) {
288 freeReplyObject(reply);
289 return REDIS_OK;
290 }
291 return REDIS_ERR;
292 }
293
294 /* Send SELECT dbnum to the server */
295 static int cliSelect() {
296 redisReply *reply;
297 if (config.dbnum == 0) return REDIS_OK;
298
299 reply = redisCommand(context,"SELECT %d",config.dbnum);
300 if (reply != NULL) {
301 freeReplyObject(reply);
302 return REDIS_OK;
303 }
304 return REDIS_ERR;
305 }
306
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) {
311 if (context != NULL)
312 redisFree(context);
313
314 if (config.hostsocket == NULL) {
315 context = redisConnect(config.hostip,config.hostport);
316 } else {
317 context = redisConnectUnix(config.hostsocket);
318 }
319
320 if (context->err) {
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);
324 else
325 fprintf(stderr,"%s: %s\n",config.hostsocket,context->errstr);
326 redisFree(context);
327 context = NULL;
328 return REDIS_ERR;
329 }
330
331 /* Do AUTH and select the right DB. */
332 if (cliAuth() != REDIS_OK)
333 return REDIS_ERR;
334 if (cliSelect() != REDIS_OK)
335 return REDIS_ERR;
336 }
337 return REDIS_OK;
338 }
339
340 static void cliPrintContextError() {
341 if (context == NULL) return;
342 fprintf(stderr,"Error: %s\n",context->errstr);
343 }
344
345 static sds cliFormatReplyTTY(redisReply *r, char *prefix) {
346 sds out = sdsempty();
347 switch (r->type) {
348 case REDIS_REPLY_ERROR:
349 out = sdscatprintf(out,"(error) %s\n", r->str);
350 break;
351 case REDIS_REPLY_STATUS:
352 out = sdscat(out,r->str);
353 out = sdscat(out,"\n");
354 break;
355 case REDIS_REPLY_INTEGER:
356 out = sdscatprintf(out,"(integer) %lld\n",r->integer);
357 break;
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");
363 break;
364 case REDIS_REPLY_NIL:
365 out = sdscat(out,"(nil)\n");
366 break;
367 case REDIS_REPLY_ARRAY:
368 if (r->elements == 0) {
369 out = sdscat(out,"(empty list or set)\n");
370 } else {
371 unsigned int i, idxlen = 0;
372 char _prefixlen[16];
373 char _prefixfmt[16];
374 sds _prefix;
375 sds tmp;
376
377 /* Calculate chars needed to represent the largest index */
378 i = r->elements;
379 do {
380 idxlen++;
381 i /= 10;
382 } while(i);
383
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);
388
389 /* Setup prefix format for every entry */
390 snprintf(_prefixfmt,sizeof(_prefixfmt),"%%s%%%dd) ",idxlen);
391
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);
396
397 /* Format the multi bulk entry */
398 tmp = cliFormatReplyTTY(r->element[i],_prefix);
399 out = sdscatlen(out,tmp,sdslen(tmp));
400 sdsfree(tmp);
401 }
402 sdsfree(_prefix);
403 }
404 break;
405 default:
406 fprintf(stderr,"Unknown reply type: %d\n", r->type);
407 exit(1);
408 }
409 return out;
410 }
411
412 static sds cliFormatReplyRaw(redisReply *r) {
413 sds out = sdsempty(), tmp;
414 size_t i;
415
416 switch (r->type) {
417 case REDIS_REPLY_NIL:
418 /* Nothing... */
419 break;
420 case REDIS_REPLY_ERROR:
421 out = sdscatlen(out,r->str,r->len);
422 out = sdscatlen(out,"\n",1);
423 break;
424 case REDIS_REPLY_STATUS:
425 case REDIS_REPLY_STRING:
426 out = sdscatlen(out,r->str,r->len);
427 break;
428 case REDIS_REPLY_INTEGER:
429 out = sdscatprintf(out,"%lld",r->integer);
430 break;
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));
436 sdsfree(tmp);
437 }
438 break;
439 default:
440 fprintf(stderr,"Unknown reply type: %d\n", r->type);
441 exit(1);
442 }
443 return out;
444 }
445
446 static sds cliFormatReplyCSV(redisReply *r) {
447 unsigned int i;
448
449 sds out = sdsempty();
450 switch (r->type) {
451 case REDIS_REPLY_ERROR:
452 out = sdscat(out,"ERROR,");
453 out = sdscatrepr(out,r->str,strlen(r->str));
454 break;
455 case REDIS_REPLY_STATUS:
456 out = sdscatrepr(out,r->str,r->len);
457 break;
458 case REDIS_REPLY_INTEGER:
459 out = sdscatprintf(out,"%lld",r->integer);
460 break;
461 case REDIS_REPLY_STRING:
462 out = sdscatrepr(out,r->str,r->len);
463 break;
464 case REDIS_REPLY_NIL:
465 out = sdscat(out,"NIL\n");
466 break;
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,",");
472 sdsfree(tmp);
473 }
474 break;
475 default:
476 fprintf(stderr,"Unknown reply type: %d\n", r->type);
477 exit(1);
478 }
479 return out;
480 }
481
482 static int cliReadReply(int output_raw_strings) {
483 void *_reply;
484 redisReply *reply;
485 sds out = NULL;
486 int output = 1;
487
488 if (redisGetReply(context,&_reply) != REDIS_OK) {
489 if (config.shutdown)
490 return REDIS_OK;
491 if (config.interactive) {
492 /* Filter cases where we should reconnect */
493 if (context->err == REDIS_ERR_IO && errno == ECONNRESET)
494 return REDIS_ERR;
495 if (context->err == REDIS_ERR_EOF)
496 return REDIS_ERR;
497 }
498 cliPrintContextError();
499 exit(1);
500 return REDIS_ERR; /* avoid compiler warning */
501 }
502
503 reply = (redisReply*)_reply;
504
505 /* Check if we need to connect to a different node and reissue the
506 * request. */
507 if (config.cluster_mode && reply->type == REDIS_REPLY_ERROR &&
508 (!strncmp(reply->str,"MOVED",5) || !strcmp(reply->str,"ASK")))
509 {
510 char *p = reply->str, *s;
511 int slot;
512
513 output = 0;
514 /* Comments show the position of the pointer as:
515 *
516 * [S] for pointer 's'
517 * [P] for pointer 'p'
518 */
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 */
521 *p = '\0';
522 slot = atoi(s+1);
523 s = strchr(p+1,':'); /* MOVED 3999[P]127.0.0.1[S]6381 */
524 *s = '\0';
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;
532 }
533
534 if (output) {
535 if (output_raw_strings) {
536 out = cliFormatReplyRaw(reply);
537 } else {
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");
546 }
547 }
548 fwrite(out,sdslen(out),1,stdout);
549 sdsfree(out);
550 }
551 freeReplyObject(reply);
552 return REDIS_OK;
553 }
554
555 static int cliSendCommand(int argc, char **argv, int repeat) {
556 char *command = argv[0];
557 size_t *argvlen;
558 int j, output_raw;
559
560 if (!strcasecmp(command,"help") || !strcasecmp(command,"?")) {
561 cliOutputHelp(--argc, ++argv);
562 return REDIS_OK;
563 }
564
565 if (context == NULL) return REDIS_ERR;
566
567 output_raw = 0;
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")))
574
575 {
576 output_raw = 1;
577 }
578
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;
583
584 /* Setup argument length */
585 argvlen = malloc(argc*sizeof(size_t));
586 for (j = 0; j < argc; j++)
587 argvlen[j] = sdslen(argv[j]);
588
589 while(repeat--) {
590 redisAppendCommandArgv(context,argc,(const char**)argv,argvlen);
591 while (config.monitor_mode) {
592 if (cliReadReply(output_raw) != REDIS_OK) exit(1);
593 fflush(stdout);
594 }
595
596 if (config.pubsub_mode) {
597 if (config.output != OUTPUT_RAW)
598 printf("Reading messages... (press Ctrl-C to quit)\n");
599 while (1) {
600 if (cliReadReply(output_raw) != REDIS_OK) exit(1);
601 }
602 }
603
604 if (cliReadReply(output_raw) != REDIS_OK) {
605 free(argvlen);
606 return REDIS_ERR;
607 } else {
608 /* Store database number when SELECT was successfully executed. */
609 if (!strcasecmp(command,"select") && argc == 2) {
610 config.dbnum = atoi(argv[1]);
611 cliRefreshPrompt();
612 }
613 }
614 if (config.interval) usleep(config.interval);
615 fflush(stdout); /* Make it grep friendly */
616 }
617
618 free(argvlen);
619 return REDIS_OK;
620 }
621
622 /*------------------------------------------------------------------------------
623 * User interface
624 *--------------------------------------------------------------------------- */
625
626 static int parseOptions(int argc, char **argv) {
627 int i;
628
629 for (i = 1; i < argc; i++) {
630 int lastarg = i==argc-1;
631
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) {
636 usage();
637 } else if (!strcmp(argv[i],"--help")) {
638 usage();
639 } else if (!strcmp(argv[i],"-x")) {
640 config.stdinarg = 1;
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")) {
665 config.bigkeys = 1;
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);
676 sdsfree(version);
677 exit(0);
678 } else {
679 break;
680 }
681 }
682 return i;
683 }
684
685 static sds readArgFromStdin(void) {
686 char buf[1024];
687 sds arg = sdsempty();
688
689 while(1) {
690 int nread = read(fileno(stdin),buf,1024);
691
692 if (nread == 0) break;
693 else if (nread == -1) {
694 perror("Reading from standard input");
695 exit(1);
696 }
697 arg = sdscatlen(arg,buf,nread);
698 }
699 return arg;
700 }
701
702 static void usage() {
703 sds version = cliVersion();
704 fprintf(stderr,
705 "redis-cli %s\n"
706 "\n"
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"
727 "\n"
728 "Examples:\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"
735 "\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"
738 "\n",
739 version);
740 sdsfree(version);
741 exit(1);
742 }
743
744 /* Turn the plain C strings into Sds strings */
745 static char **convertToSds(int count, char** args) {
746 int j;
747 char **sds = zmalloc(sizeof(char*)*count);
748
749 for(j = 0; j < count; j++)
750 sds[j] = sdsnew(args[j]);
751
752 return sds;
753 }
754
755 #define LINE_BUFLEN 4096
756 static void repl() {
757 sds historyfile = NULL;
758 int history = 0;
759 char *line;
760 int argc;
761 sds *argv;
762
763 config.interactive = 1;
764 linenoiseSetCompletionCallback(completionCallback);
765
766 /* Only use history when stdin is a tty. */
767 if (isatty(fileno(stdin))) {
768 history = 1;
769
770 if (getenv("HOME") != NULL) {
771 historyfile = sdscatprintf(sdsempty(),"%s/.rediscli_history",getenv("HOME"));
772 linenoiseHistoryLoad(historyfile);
773 }
774 }
775
776 cliRefreshPrompt();
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);
782
783 if (argv == NULL) {
784 printf("Invalid argument(s)\n");
785 free(line);
786 continue;
787 } else if (argc > 0) {
788 if (strcasecmp(argv[0],"quit") == 0 ||
789 strcasecmp(argv[0],"exit") == 0)
790 {
791 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]);
796 cliConnect(1);
797 } else if (argc == 1 && !strcasecmp(argv[0],"clear")) {
798 linenoiseClearScreen();
799 } else {
800 long long start_time = mstime(), elapsed;
801 int repeat, skipargs = 0;
802
803 repeat = atoi(argv[0]);
804 if (argc > 1 && repeat) {
805 skipargs = 1;
806 } else {
807 repeat = 1;
808 }
809
810 while (1) {
811 config.cluster_reissue_command = 0;
812 if (cliSendCommand(argc-skipargs,argv+skipargs,repeat)
813 != REDIS_OK)
814 {
815 cliConnect(1);
816
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)
820 != REDIS_OK)
821 cliPrintContextError();
822 }
823 /* Issue the command again if we got redirected in cluster mode */
824 if (config.cluster_mode && config.cluster_reissue_command) {
825 cliConnect(1);
826 } else {
827 break;
828 }
829 }
830 elapsed = mstime()-start_time;
831 if (elapsed >= 500) {
832 printf("(%.2fs)\n",(double)elapsed/1000);
833 }
834 }
835 }
836 /* Free the argument vector */
837 while(argc--) sdsfree(argv[argc]);
838 zfree(argv);
839 }
840 /* linenoise() returns malloc-ed lines like readline() */
841 free(line);
842 }
843 exit(0);
844 }
845
846 static int noninteractive(int argc, char **argv) {
847 int retval = 0;
848 if (config.stdinarg) {
849 argv = zrealloc(argv, (argc+1)*sizeof(char*));
850 argv[argc] = readArgFromStdin();
851 retval = cliSendCommand(argc+1, argv, config.repeat);
852 } else {
853 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
854 retval = cliSendCommand(argc, argv, config.repeat);
855 }
856 return retval;
857 }
858
859 static int evalMode(int argc, char **argv) {
860 sds script = sdsempty();
861 FILE *fp;
862 char buf[1024];
863 size_t nread;
864 char **argv2;
865 int j, got_comma = 0, keys = 0;
866
867 /* Load the script from the file, as an sds string. */
868 fp = fopen(config.eval,"r");
869 if (!fp) {
870 fprintf(stderr,
871 "Can't open file '%s': %s\n", config.eval, strerror(errno));
872 exit(1);
873 }
874 while((nread = fread(buf,1,sizeof(buf),fp)) != 0) {
875 script = sdscatlen(script,buf,nread);
876 }
877 fclose(fp);
878
879 /* Create our argument vector */
880 argv2 = zmalloc(sizeof(sds)*(argc+3));
881 argv2[0] = sdsnew("EVAL");
882 argv2[1] = script;
883 for (j = 0; j < argc; j++) {
884 if (!got_comma && argv[j][0] == ',' && argv[j][1] == 0) {
885 got_comma = 1;
886 continue;
887 }
888 argv2[j+3-got_comma] = sdsnew(argv[j]);
889 if (!got_comma) keys++;
890 }
891 argv2[2] = sdscatprintf(sdsempty(),"%d",keys);
892
893 /* Call it */
894 return cliSendCommand(argc+3-got_comma, argv2, config.repeat);
895 }
896
897 static void latencyMode(void) {
898 redisReply *reply;
899 long long start, latency, min = 0, max = 0, tot = 0, count = 0;
900 double avg;
901
902 if (!context) exit(1);
903 while(1) {
904 start = mstime();
905 reply = redisCommand(context,"PING");
906 if (reply == NULL) {
907 fprintf(stderr,"\nI/O error\n");
908 exit(1);
909 }
910 latency = mstime()-start;
911 freeReplyObject(reply);
912 count++;
913 if (count == 1) {
914 min = max = tot = latency;
915 avg = (double) latency;
916 } else {
917 if (latency < min) min = latency;
918 if (latency > max) max = latency;
919 tot += latency;
920 avg = (double) tot/count;
921 }
922 printf("\x1b[0G\x1b[2Kmin: %lld, max: %lld, avg: %.2f (%lld samples)",
923 min, max, avg, count);
924 fflush(stdout);
925 usleep(10000);
926 }
927 }
928
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;
935 char buf[1024], *p;
936 ssize_t nread;
937 unsigned long long payload;
938
939 /* Send the SYNC command. */
940 if (write(fd,"SYNC\r\n",6) != 6) {
941 fprintf(stderr,"Error writing to master\n");
942 exit(1);
943 }
944
945 /* Read $<payload>\r\n, making sure to read just up to "\n" */
946 p = buf;
947 while(1) {
948 nread = read(fd,p,1);
949 if (nread <= 0) {
950 fprintf(stderr,"Error reading bulk length while SYNCing\n");
951 exit(1);
952 }
953 if (*p == '\n') break;
954 p++;
955 }
956 *p = '\0';
957 payload = strtoull(buf+1,NULL,10);
958 fprintf(stderr,"SYNC with master, discarding %lld bytes of bulk tranfer...\n",
959 payload);
960
961 /* Discard the payload. */
962 while(payload) {
963 nread = read(fd,buf,(payload > sizeof(buf)) ? sizeof(buf) : payload);
964 if (nread <= 0) {
965 fprintf(stderr,"Error reading RDB payload while SYNCing\n");
966 exit(1);
967 }
968 payload -= nread;
969 }
970 fprintf(stderr,"SYNC done. Logging commands from master.\n");
971
972 /* Now we can use the hiredis to read the incoming protocol. */
973 config.output = OUTPUT_CSV;
974 while (cliReadReply(0) == REDIS_OK);
975 }
976
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();
983 redisReply *reply;
984 int eof = 0; /* True once we consumed all the standard input. */
985 int done = 0;
986 char magic[20]; /* Special reply we recognize. */
987
988 srand(time(NULL));
989
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",
993 aneterr);
994 exit(1);
995 }
996
997 /* Transfer raw protocol and read replies from the server at the same
998 * time. */
999 while(!done) {
1000 int mask = AE_READABLE;
1001
1002 if (!eof || obuf_len != 0) mask |= AE_WRITABLE;
1003 mask = aeWait(fd,mask,1000);
1004
1005 /* Handle the readable state: we can read replies from the server. */
1006 if (mask & AE_READABLE) {
1007 ssize_t nread;
1008
1009 /* Read from socket and feed the hiredis reader. */
1010 do {
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",
1014 strerror(errno));
1015 exit(1);
1016 }
1017 if (nread > 0) redisReaderFeed(reader,ibuf,nread);
1018 } while(nread > 0);
1019
1020 /* Consume replies. */
1021 do {
1022 if (redisReaderGetReply(reader,(void**)&reply) == REDIS_ERR) {
1023 fprintf(stderr, "Error reading replies from server\n");
1024 exit(1);
1025 }
1026 if (reply) {
1027 if (reply->type == REDIS_REPLY_ERROR) {
1028 fprintf(stderr,"%s\n", reply->str);
1029 errors++;
1030 } else if (eof && reply->type == REDIS_REPLY_STRING &&
1031 reply->len == 20) {
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");
1037 done = 1;
1038 replies--;
1039 }
1040 }
1041 replies++;
1042 freeReplyObject(reply);
1043 }
1044 } while(reply);
1045 }
1046
1047 /* Handle the writable state: we can send protocol to the server. */
1048 if (mask & AE_WRITABLE) {
1049 while(1) {
1050 /* Transfer current buffer to server. */
1051 if (obuf_len != 0) {
1052 ssize_t nwritten = write(fd,obuf+obuf_pos,obuf_len);
1053
1054 if (nwritten == -1) {
1055 if (errno != EAGAIN && errno != EINTR) {
1056 fprintf(stderr, "Error writing to the server: %s\n",
1057 strerror(errno));
1058 exit(1);
1059 } else {
1060 nwritten = 0;
1061 }
1062 }
1063 obuf_len -= nwritten;
1064 obuf_pos += nwritten;
1065 if (obuf_len != 0) break; /* Can't accept more data. */
1066 }
1067 /* If buffer is empty, load from stdin. */
1068 if (obuf_len == 0 && !eof) {
1069 ssize_t nread = read(STDIN_FILENO,obuf,sizeof(obuf));
1070
1071 if (nread == 0) {
1072 char echo[] =
1073 "*2\r\n$4\r\nECHO\r\n$20\r\n01234567890123456789\r\n";
1074 int j;
1075
1076 eof = 1;
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;
1085 obuf_pos = 0;
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",
1089 strerror(errno));
1090 exit(1);
1091 } else {
1092 obuf_len = nread;
1093 obuf_pos = 0;
1094 }
1095 }
1096 if (obuf_len == 0 && eof) break;
1097 }
1098 }
1099 }
1100 redisReaderFree(reader);
1101 printf("errors: %lld, replies: %lld\n", errors, replies);
1102 if (errors)
1103 exit(1);
1104 else
1105 exit(0);
1106 }
1107
1108 #define TYPE_STRING 0
1109 #define TYPE_LIST 1
1110 #define TYPE_SET 2
1111 #define TYPE_HASH 3
1112 #define TYPE_ZSET 4
1113
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"};
1119 int type;
1120
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");
1124 while(1) {
1125 /* Sample with RANDOMKEY */
1126 reply1 = redisCommand(context,"RANDOMKEY");
1127 if (reply1 == NULL) {
1128 fprintf(stderr,"\nI/O error\n");
1129 exit(1);
1130 } else if (reply1->type == REDIS_REPLY_ERROR) {
1131 fprintf(stderr, "RANDOMKEY error: %s\n",
1132 reply1->str);
1133 exit(1);
1134 }
1135 /* Get the key type */
1136 reply2 = redisCommand(context,"TYPE %s",reply1->str);
1137 assert(reply2 && reply2->type == REDIS_REPLY_STATUS);
1138 samples++;
1139
1140 /* Get the key "size" */
1141 if (!strcmp(reply2->str,"string")) {
1142 sizecmd = "STRLEN";
1143 type = TYPE_STRING;
1144 } else if (!strcmp(reply2->str,"list")) {
1145 sizecmd = "LLEN";
1146 type = TYPE_LIST;
1147 } else if (!strcmp(reply2->str,"set")) {
1148 sizecmd = "SCARD";
1149 type = TYPE_SET;
1150 } else if (!strcmp(reply2->str,"hash")) {
1151 sizecmd = "HLEN";
1152 type = TYPE_HASH;
1153 } else if (!strcmp(reply2->str,"zset")) {
1154 sizecmd = "ZCARD";
1155 type = TYPE_ZSET;
1156 } else if (!strcmp(reply2->str,"none")) {
1157 freeReplyObject(reply1);
1158 freeReplyObject(reply2);
1159 freeReplyObject(reply3);
1160 continue;
1161 } else {
1162 fprintf(stderr, "Unknown key type '%s' for key '%s'\n",
1163 reply2->str, reply1->str);
1164 exit(1);
1165 }
1166
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;
1174 }
1175 }
1176
1177 if ((samples % 1000000) == 0)
1178 printf("(%llu keys sampled)\n", samples);
1179
1180 if ((samples % 100) == 0 && config.interval)
1181 usleep(config.interval);
1182
1183 freeReplyObject(reply1);
1184 freeReplyObject(reply2);
1185 if (reply3) freeReplyObject(reply3);
1186 }
1187 }
1188
1189 int main(int argc, char **argv) {
1190 int firstarg;
1191
1192 config.hostip = sdsnew("127.0.0.1");
1193 config.hostport = 6379;
1194 config.hostsocket = NULL;
1195 config.repeat = 1;
1196 config.interval = 0;
1197 config.dbnum = 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;
1206 config.bigkeys = 0;
1207 config.stdinarg = 0;
1208 config.auth = NULL;
1209 config.eval = NULL;
1210 if (!isatty(fileno(stdout)) && (getenv("FAKETTY") == NULL))
1211 config.output = OUTPUT_RAW;
1212 else
1213 config.output = OUTPUT_STANDARD;
1214 config.mb_delim = sdsnew("\n");
1215 cliInitHelp();
1216
1217 firstarg = parseOptions(argc,argv);
1218 argc -= firstarg;
1219 argv += firstarg;
1220
1221 /* Latency mode */
1222 if (config.latency_mode) {
1223 cliConnect(0);
1224 latencyMode();
1225 }
1226
1227 /* Slave mode */
1228 if (config.slave_mode) {
1229 cliConnect(0);
1230 slaveMode();
1231 }
1232
1233 /* Pipe mode */
1234 if (config.pipe_mode) {
1235 cliConnect(0);
1236 pipeMode();
1237 }
1238
1239 /* Find big keys */
1240 if (config.bigkeys) {
1241 cliConnect(0);
1242 findBigKeys();
1243 }
1244
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. */
1249 cliConnect(0);
1250 repl();
1251 }
1252
1253 /* Otherwise, we have some arguments to execute */
1254 if (cliConnect(0) != REDIS_OK) exit(1);
1255 if (config.eval) {
1256 return evalMode(argc,argv);
1257 } else {
1258 return noninteractive(argc,convertToSds(argc,argv));
1259 }
1260 }