xref: /redis-3.2.3/src/redis-cli.c (revision 28343966)
1 /* Redis CLI (command line interface)
2  *
3  * Copyright (c) 2009-2012, 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 <signal.h>
38 #include <unistd.h>
39 #include <time.h>
40 #include <ctype.h>
41 #include <errno.h>
42 #include <sys/stat.h>
43 #include <sys/time.h>
44 #include <assert.h>
45 #include <fcntl.h>
46 #include <limits.h>
47 
48 #include "hiredis.h"
49 #include "sds.h"
50 #include "zmalloc.h"
51 #include "linenoise.h"
52 #include "help.h"
53 #include "anet.h"
54 #include "ae.h"
55 
56 #define REDIS_NOTUSED(V) ((void) V)
57 
58 #define OUTPUT_STANDARD 0
59 #define OUTPUT_RAW 1
60 #define OUTPUT_CSV 2
61 #define REDIS_CLI_KEEPALIVE_INTERVAL 15 /* seconds */
62 #define REDIS_CLI_DEFAULT_PIPE_TIMEOUT 30 /* seconds */
63 
64 static redisContext *context;
65 static struct config {
66     char *hostip;
67     int hostport;
68     char *hostsocket;
69     long repeat;
70     long interval;
71     int dbnum;
72     int interactive;
73     int shutdown;
74     int monitor_mode;
75     int pubsub_mode;
76     int latency_mode;
77     int latency_history;
78     int cluster_mode;
79     int cluster_reissue_command;
80     int slave_mode;
81     int pipe_mode;
82     int pipe_timeout;
83     int getrdb_mode;
84     int stat_mode;
85     int scan_mode;
86     int intrinsic_latency_mode;
87     int intrinsic_latency_duration;
88     char *pattern;
89     char *rdb_filename;
90     int bigkeys;
91     int stdinarg; /* get last arg from stdin. (-x option) */
92     char *auth;
93     int output; /* output mode, see OUTPUT_* defines */
94     sds mb_delim;
95     char prompt[128];
96     char *eval;
97     int last_cmd_type;
98 } config;
99 
100 static volatile sig_atomic_t force_cancel_loop = 0;
101 static void usage(void);
102 static void slaveMode(void);
103 char *redisGitSHA1(void);
104 char *redisGitDirty(void);
105 
106 /*------------------------------------------------------------------------------
107  * Utility functions
108  *--------------------------------------------------------------------------- */
109 
110 static long long ustime(void) {
111     struct timeval tv;
112     long long ust;
113 
114     gettimeofday(&tv, NULL);
115     ust = ((long long)tv.tv_sec)*1000000;
116     ust += tv.tv_usec;
117     return ust;
118 }
119 
120 static long long mstime(void) {
121     return ustime()/1000;
122 }
123 
124 static void cliRefreshPrompt(void) {
125     int len;
126 
127     if (config.hostsocket != NULL)
128         len = snprintf(config.prompt,sizeof(config.prompt),"redis %s",
129                        config.hostsocket);
130     else
131         len = snprintf(config.prompt,sizeof(config.prompt),
132                        strchr(config.hostip,':') ? "[%s]:%d" : "%s:%d",
133                        config.hostip, config.hostport);
134     /* Add [dbnum] if needed */
135     if (config.dbnum != 0 && config.last_cmd_type != REDIS_REPLY_ERROR)
136         len += snprintf(config.prompt+len,sizeof(config.prompt)-len,"[%d]",
137             config.dbnum);
138     snprintf(config.prompt+len,sizeof(config.prompt)-len,"> ");
139 }
140 
141 /*------------------------------------------------------------------------------
142  * Help functions
143  *--------------------------------------------------------------------------- */
144 
145 #define CLI_HELP_COMMAND 1
146 #define CLI_HELP_GROUP 2
147 
148 typedef struct {
149     int type;
150     int argc;
151     sds *argv;
152     sds full;
153 
154     /* Only used for help on commands */
155     struct commandHelp *org;
156 } helpEntry;
157 
158 static helpEntry *helpEntries;
159 static int helpEntriesLen;
160 
161 static sds cliVersion(void) {
162     sds version;
163     version = sdscatprintf(sdsempty(), "%s", REDIS_VERSION);
164 
165     /* Add git commit and working tree status when available */
166     if (strtoll(redisGitSHA1(),NULL,16)) {
167         version = sdscatprintf(version, " (git:%s", redisGitSHA1());
168         if (strtoll(redisGitDirty(),NULL,10))
169             version = sdscatprintf(version, "-dirty");
170         version = sdscat(version, ")");
171     }
172     return version;
173 }
174 
175 static void cliInitHelp(void) {
176     int commandslen = sizeof(commandHelp)/sizeof(struct commandHelp);
177     int groupslen = sizeof(commandGroups)/sizeof(char*);
178     int i, len, pos = 0;
179     helpEntry tmp;
180 
181     helpEntriesLen = len = commandslen+groupslen;
182     helpEntries = malloc(sizeof(helpEntry)*len);
183 
184     for (i = 0; i < groupslen; i++) {
185         tmp.argc = 1;
186         tmp.argv = malloc(sizeof(sds));
187         tmp.argv[0] = sdscatprintf(sdsempty(),"@%s",commandGroups[i]);
188         tmp.full = tmp.argv[0];
189         tmp.type = CLI_HELP_GROUP;
190         tmp.org = NULL;
191         helpEntries[pos++] = tmp;
192     }
193 
194     for (i = 0; i < commandslen; i++) {
195         tmp.argv = sdssplitargs(commandHelp[i].name,&tmp.argc);
196         tmp.full = sdsnew(commandHelp[i].name);
197         tmp.type = CLI_HELP_COMMAND;
198         tmp.org = &commandHelp[i];
199         helpEntries[pos++] = tmp;
200     }
201 }
202 
203 /* Output command help to stdout. */
204 static void cliOutputCommandHelp(struct commandHelp *help, int group) {
205     printf("\r\n  \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\r\n", help->name, help->params);
206     printf("  \x1b[33msummary:\x1b[0m %s\r\n", help->summary);
207     printf("  \x1b[33msince:\x1b[0m %s\r\n", help->since);
208     if (group) {
209         printf("  \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups[help->group]);
210     }
211 }
212 
213 /* Print generic help. */
214 static void cliOutputGenericHelp(void) {
215     sds version = cliVersion();
216     printf(
217         "redis-cli %s\r\n"
218         "Type: \"help @<group>\" to get a list of commands in <group>\r\n"
219         "      \"help <command>\" for help on <command>\r\n"
220         "      \"help <tab>\" to get a list of possible help topics\r\n"
221         "      \"quit\" to exit\r\n",
222         version
223     );
224     sdsfree(version);
225 }
226 
227 /* Output all command help, filtering by group or command name. */
228 static void cliOutputHelp(int argc, char **argv) {
229     int i, j, len;
230     int group = -1;
231     helpEntry *entry;
232     struct commandHelp *help;
233 
234     if (argc == 0) {
235         cliOutputGenericHelp();
236         return;
237     } else if (argc > 0 && argv[0][0] == '@') {
238         len = sizeof(commandGroups)/sizeof(char*);
239         for (i = 0; i < len; i++) {
240             if (strcasecmp(argv[0]+1,commandGroups[i]) == 0) {
241                 group = i;
242                 break;
243             }
244         }
245     }
246 
247     assert(argc > 0);
248     for (i = 0; i < helpEntriesLen; i++) {
249         entry = &helpEntries[i];
250         if (entry->type != CLI_HELP_COMMAND) continue;
251 
252         help = entry->org;
253         if (group == -1) {
254             /* Compare all arguments */
255             if (argc == entry->argc) {
256                 for (j = 0; j < argc; j++) {
257                     if (strcasecmp(argv[j],entry->argv[j]) != 0) break;
258                 }
259                 if (j == argc) {
260                     cliOutputCommandHelp(help,1);
261                 }
262             }
263         } else {
264             if (group == help->group) {
265                 cliOutputCommandHelp(help,0);
266             }
267         }
268     }
269     printf("\r\n");
270 }
271 
272 static void completionCallback(const char *buf, linenoiseCompletions *lc) {
273     size_t startpos = 0;
274     int mask;
275     int i;
276     size_t matchlen;
277     sds tmp;
278 
279     if (strncasecmp(buf,"help ",5) == 0) {
280         startpos = 5;
281         while (isspace(buf[startpos])) startpos++;
282         mask = CLI_HELP_COMMAND | CLI_HELP_GROUP;
283     } else {
284         mask = CLI_HELP_COMMAND;
285     }
286 
287     for (i = 0; i < helpEntriesLen; i++) {
288         if (!(helpEntries[i].type & mask)) continue;
289 
290         matchlen = strlen(buf+startpos);
291         if (strncasecmp(buf+startpos,helpEntries[i].full,matchlen) == 0) {
292             tmp = sdsnewlen(buf,startpos);
293             tmp = sdscat(tmp,helpEntries[i].full);
294             linenoiseAddCompletion(lc,tmp);
295             sdsfree(tmp);
296         }
297     }
298 }
299 
300 /*------------------------------------------------------------------------------
301  * Networking / parsing
302  *--------------------------------------------------------------------------- */
303 
304 /* Send AUTH command to the server */
305 static int cliAuth() {
306     redisReply *reply;
307     if (config.auth == NULL) return REDIS_OK;
308 
309     reply = redisCommand(context,"AUTH %s",config.auth);
310     if (reply != NULL) {
311         freeReplyObject(reply);
312         return REDIS_OK;
313     }
314     return REDIS_ERR;
315 }
316 
317 /* Send SELECT dbnum to the server */
318 static int cliSelect() {
319     redisReply *reply;
320     if (config.dbnum == 0) return REDIS_OK;
321 
322     reply = redisCommand(context,"SELECT %d",config.dbnum);
323     if (reply != NULL) {
324         int result = REDIS_OK;
325         if (reply->type == REDIS_REPLY_ERROR) result = REDIS_ERR;
326         freeReplyObject(reply);
327         return result;
328     }
329     return REDIS_ERR;
330 }
331 
332 /* Connect to the server. If force is not zero the connection is performed
333  * even if there is already a connected socket. */
334 static int cliConnect(int force) {
335     if (context == NULL || force) {
336         if (context != NULL)
337             redisFree(context);
338 
339         if (config.hostsocket == NULL) {
340             context = redisConnect(config.hostip,config.hostport);
341         } else {
342             context = redisConnectUnix(config.hostsocket);
343         }
344 
345         if (context->err) {
346             fprintf(stderr,"Could not connect to Redis at ");
347             if (config.hostsocket == NULL)
348                 fprintf(stderr,"%s:%d: %s\n",config.hostip,config.hostport,context->errstr);
349             else
350                 fprintf(stderr,"%s: %s\n",config.hostsocket,context->errstr);
351             redisFree(context);
352             context = NULL;
353             return REDIS_ERR;
354         }
355 
356         /* Set aggressive KEEP_ALIVE socket option in the Redis context socket
357          * in order to prevent timeouts caused by the execution of long
358          * commands. At the same time this improves the detection of real
359          * errors. */
360         anetKeepAlive(NULL, context->fd, REDIS_CLI_KEEPALIVE_INTERVAL);
361 
362         /* Do AUTH and select the right DB. */
363         if (cliAuth() != REDIS_OK)
364             return REDIS_ERR;
365         if (cliSelect() != REDIS_OK)
366             return REDIS_ERR;
367     }
368     return REDIS_OK;
369 }
370 
371 static void cliPrintContextError(void) {
372     if (context == NULL) return;
373     fprintf(stderr,"Error: %s\n",context->errstr);
374 }
375 
376 static sds cliFormatReplyTTY(redisReply *r, char *prefix) {
377     sds out = sdsempty();
378     switch (r->type) {
379     case REDIS_REPLY_ERROR:
380         out = sdscatprintf(out,"(error) %s\n", r->str);
381     break;
382     case REDIS_REPLY_STATUS:
383         out = sdscat(out,r->str);
384         out = sdscat(out,"\n");
385     break;
386     case REDIS_REPLY_INTEGER:
387         out = sdscatprintf(out,"(integer) %lld\n",r->integer);
388     break;
389     case REDIS_REPLY_STRING:
390         /* If you are producing output for the standard output we want
391         * a more interesting output with quoted characters and so forth */
392         out = sdscatrepr(out,r->str,r->len);
393         out = sdscat(out,"\n");
394     break;
395     case REDIS_REPLY_NIL:
396         out = sdscat(out,"(nil)\n");
397     break;
398     case REDIS_REPLY_ARRAY:
399         if (r->elements == 0) {
400             out = sdscat(out,"(empty list or set)\n");
401         } else {
402             unsigned int i, idxlen = 0;
403             char _prefixlen[16];
404             char _prefixfmt[16];
405             sds _prefix;
406             sds tmp;
407 
408             /* Calculate chars needed to represent the largest index */
409             i = r->elements;
410             do {
411                 idxlen++;
412                 i /= 10;
413             } while(i);
414 
415             /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
416             memset(_prefixlen,' ',idxlen+2);
417             _prefixlen[idxlen+2] = '\0';
418             _prefix = sdscat(sdsnew(prefix),_prefixlen);
419 
420             /* Setup prefix format for every entry */
421             snprintf(_prefixfmt,sizeof(_prefixfmt),"%%s%%%dd) ",idxlen);
422 
423             for (i = 0; i < r->elements; i++) {
424                 /* Don't use the prefix for the first element, as the parent
425                  * caller already prepended the index number. */
426                 out = sdscatprintf(out,_prefixfmt,i == 0 ? "" : prefix,i+1);
427 
428                 /* Format the multi bulk entry */
429                 tmp = cliFormatReplyTTY(r->element[i],_prefix);
430                 out = sdscatlen(out,tmp,sdslen(tmp));
431                 sdsfree(tmp);
432             }
433             sdsfree(_prefix);
434         }
435     break;
436     default:
437         fprintf(stderr,"Unknown reply type: %d\n", r->type);
438         exit(1);
439     }
440     return out;
441 }
442 
443 static sds cliFormatReplyRaw(redisReply *r) {
444     sds out = sdsempty(), tmp;
445     size_t i;
446 
447     switch (r->type) {
448     case REDIS_REPLY_NIL:
449         /* Nothing... */
450         break;
451     case REDIS_REPLY_ERROR:
452         out = sdscatlen(out,r->str,r->len);
453         out = sdscatlen(out,"\n",1);
454         break;
455     case REDIS_REPLY_STATUS:
456     case REDIS_REPLY_STRING:
457         out = sdscatlen(out,r->str,r->len);
458         break;
459     case REDIS_REPLY_INTEGER:
460         out = sdscatprintf(out,"%lld",r->integer);
461         break;
462     case REDIS_REPLY_ARRAY:
463         for (i = 0; i < r->elements; i++) {
464             if (i > 0) out = sdscat(out,config.mb_delim);
465             tmp = cliFormatReplyRaw(r->element[i]);
466             out = sdscatlen(out,tmp,sdslen(tmp));
467             sdsfree(tmp);
468         }
469         break;
470     default:
471         fprintf(stderr,"Unknown reply type: %d\n", r->type);
472         exit(1);
473     }
474     return out;
475 }
476 
477 static sds cliFormatReplyCSV(redisReply *r) {
478     unsigned int i;
479 
480     sds out = sdsempty();
481     switch (r->type) {
482     case REDIS_REPLY_ERROR:
483         out = sdscat(out,"ERROR,");
484         out = sdscatrepr(out,r->str,strlen(r->str));
485     break;
486     case REDIS_REPLY_STATUS:
487         out = sdscatrepr(out,r->str,r->len);
488     break;
489     case REDIS_REPLY_INTEGER:
490         out = sdscatprintf(out,"%lld",r->integer);
491     break;
492     case REDIS_REPLY_STRING:
493         out = sdscatrepr(out,r->str,r->len);
494     break;
495     case REDIS_REPLY_NIL:
496         out = sdscat(out,"NIL\n");
497     break;
498     case REDIS_REPLY_ARRAY:
499         for (i = 0; i < r->elements; i++) {
500             sds tmp = cliFormatReplyCSV(r->element[i]);
501             out = sdscatlen(out,tmp,sdslen(tmp));
502             if (i != r->elements-1) out = sdscat(out,",");
503             sdsfree(tmp);
504         }
505     break;
506     default:
507         fprintf(stderr,"Unknown reply type: %d\n", r->type);
508         exit(1);
509     }
510     return out;
511 }
512 
513 static int cliReadReply(int output_raw_strings) {
514     void *_reply;
515     redisReply *reply;
516     sds out = NULL;
517     int output = 1;
518 
519     if (redisGetReply(context,&_reply) != REDIS_OK) {
520         if (config.shutdown) {
521             redisFree(context);
522             context = NULL;
523             return REDIS_OK;
524         }
525         if (config.interactive) {
526             /* Filter cases where we should reconnect */
527             if (context->err == REDIS_ERR_IO && errno == ECONNRESET)
528                 return REDIS_ERR;
529             if (context->err == REDIS_ERR_EOF)
530                 return REDIS_ERR;
531         }
532         cliPrintContextError();
533         exit(1);
534         return REDIS_ERR; /* avoid compiler warning */
535     }
536 
537     reply = (redisReply*)_reply;
538 
539     config.last_cmd_type = reply->type;
540 
541     /* Check if we need to connect to a different node and reissue the
542      * request. */
543     if (config.cluster_mode && reply->type == REDIS_REPLY_ERROR &&
544         (!strncmp(reply->str,"MOVED",5) || !strcmp(reply->str,"ASK")))
545     {
546         char *p = reply->str, *s;
547         int slot;
548 
549         output = 0;
550         /* Comments show the position of the pointer as:
551          *
552          * [S] for pointer 's'
553          * [P] for pointer 'p'
554          */
555         s = strchr(p,' ');      /* MOVED[S]3999 127.0.0.1:6381 */
556         p = strchr(s+1,' ');    /* MOVED[S]3999[P]127.0.0.1:6381 */
557         *p = '\0';
558         slot = atoi(s+1);
559         s = strchr(p+1,':');    /* MOVED 3999[P]127.0.0.1[S]6381 */
560         *s = '\0';
561         sdsfree(config.hostip);
562         config.hostip = sdsnew(p+1);
563         config.hostport = atoi(s+1);
564         if (config.interactive)
565             printf("-> Redirected to slot [%d] located at %s:%d\n",
566                 slot, config.hostip, config.hostport);
567         config.cluster_reissue_command = 1;
568         cliRefreshPrompt();
569     }
570 
571     if (output) {
572         if (output_raw_strings) {
573             out = cliFormatReplyRaw(reply);
574         } else {
575             if (config.output == OUTPUT_RAW) {
576                 out = cliFormatReplyRaw(reply);
577                 out = sdscat(out,"\n");
578             } else if (config.output == OUTPUT_STANDARD) {
579                 out = cliFormatReplyTTY(reply,"");
580             } else if (config.output == OUTPUT_CSV) {
581                 out = cliFormatReplyCSV(reply);
582                 out = sdscat(out,"\n");
583             }
584         }
585         fwrite(out,sdslen(out),1,stdout);
586         sdsfree(out);
587     }
588     freeReplyObject(reply);
589     return REDIS_OK;
590 }
591 
592 static int cliSendCommand(int argc, char **argv, int repeat) {
593     char *command = argv[0];
594     size_t *argvlen;
595     int j, output_raw;
596 
597     if (!strcasecmp(command,"help") || !strcasecmp(command,"?")) {
598         cliOutputHelp(--argc, ++argv);
599         return REDIS_OK;
600     }
601 
602     if (context == NULL) return REDIS_ERR;
603 
604     output_raw = 0;
605     if (!strcasecmp(command,"info") ||
606         (argc == 2 && !strcasecmp(command,"cluster") &&
607                       (!strcasecmp(argv[1],"nodes") ||
608                        !strcasecmp(argv[1],"info"))) ||
609         (argc == 2 && !strcasecmp(command,"client") &&
610                        !strcasecmp(argv[1],"list")) ||
611         (argc == 3 && !strcasecmp(command,"latency") &&
612                        !strcasecmp(argv[1],"graph")) ||
613         (argc == 2 && !strcasecmp(command,"latency") &&
614                        !strcasecmp(argv[1],"doctor")))
615     {
616         output_raw = 1;
617     }
618 
619     if (!strcasecmp(command,"shutdown")) config.shutdown = 1;
620     if (!strcasecmp(command,"monitor")) config.monitor_mode = 1;
621     if (!strcasecmp(command,"subscribe") ||
622         !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1;
623     if (!strcasecmp(command,"sync") ||
624         !strcasecmp(command,"psync")) config.slave_mode = 1;
625 
626     /* Setup argument length */
627     argvlen = malloc(argc*sizeof(size_t));
628     for (j = 0; j < argc; j++)
629         argvlen[j] = sdslen(argv[j]);
630 
631     while(repeat--) {
632         redisAppendCommandArgv(context,argc,(const char**)argv,argvlen);
633         while (config.monitor_mode) {
634             if (cliReadReply(output_raw) != REDIS_OK) exit(1);
635             fflush(stdout);
636         }
637 
638         if (config.pubsub_mode) {
639             if (config.output != OUTPUT_RAW)
640                 printf("Reading messages... (press Ctrl-C to quit)\n");
641             while (1) {
642                 if (cliReadReply(output_raw) != REDIS_OK) exit(1);
643             }
644         }
645 
646         if (config.slave_mode) {
647             printf("Entering slave output mode...  (press Ctrl-C to quit)\n");
648             slaveMode();
649             config.slave_mode = 0;
650             free(argvlen);
651             return REDIS_ERR;  /* Error = slaveMode lost connection to master */
652         }
653 
654         if (cliReadReply(output_raw) != REDIS_OK) {
655             free(argvlen);
656             return REDIS_ERR;
657         } else {
658             /* Store database number when SELECT was successfully executed. */
659             if (!strcasecmp(command,"select") && argc == 2) {
660                 config.dbnum = atoi(argv[1]);
661                 cliRefreshPrompt();
662             } else if (!strcasecmp(command,"auth") && argc == 2) {
663                 cliSelect();
664             }
665         }
666         if (config.interval) usleep(config.interval);
667         fflush(stdout); /* Make it grep friendly */
668     }
669 
670     free(argvlen);
671     return REDIS_OK;
672 }
673 
674 /* Send the INFO command, reconnecting the link if needed. */
675 static redisReply *reconnectingInfo(void) {
676     redisContext *c = context;
677     redisReply *reply = NULL;
678     int tries = 0;
679 
680     assert(!c->err);
681     while(reply == NULL) {
682         while (c->err & (REDIS_ERR_IO | REDIS_ERR_EOF)) {
683             printf("Reconnecting (%d)...\r", ++tries);
684             fflush(stdout);
685 
686             redisFree(c);
687             c = redisConnect(config.hostip,config.hostport);
688             usleep(1000000);
689         }
690 
691         reply = redisCommand(c,"INFO");
692         if (c->err && !(c->err & (REDIS_ERR_IO | REDIS_ERR_EOF))) {
693             fprintf(stderr, "Error: %s\n", c->errstr);
694             exit(1);
695         } else if (tries > 0) {
696             printf("\n");
697         }
698     }
699 
700     context = c;
701     return reply;
702 }
703 
704 /*------------------------------------------------------------------------------
705  * User interface
706  *--------------------------------------------------------------------------- */
707 
708 static int parseOptions(int argc, char **argv) {
709     int i;
710 
711     for (i = 1; i < argc; i++) {
712         int lastarg = i==argc-1;
713 
714         if (!strcmp(argv[i],"-h") && !lastarg) {
715             sdsfree(config.hostip);
716             config.hostip = sdsnew(argv[++i]);
717         } else if (!strcmp(argv[i],"-h") && lastarg) {
718             usage();
719         } else if (!strcmp(argv[i],"--help")) {
720             usage();
721         } else if (!strcmp(argv[i],"-x")) {
722             config.stdinarg = 1;
723         } else if (!strcmp(argv[i],"-p") && !lastarg) {
724             config.hostport = atoi(argv[++i]);
725         } else if (!strcmp(argv[i],"-s") && !lastarg) {
726             config.hostsocket = argv[++i];
727         } else if (!strcmp(argv[i],"-r") && !lastarg) {
728             config.repeat = strtoll(argv[++i],NULL,10);
729         } else if (!strcmp(argv[i],"-i") && !lastarg) {
730             double seconds = atof(argv[++i]);
731             config.interval = seconds*1000000;
732         } else if (!strcmp(argv[i],"-n") && !lastarg) {
733             config.dbnum = atoi(argv[++i]);
734         } else if (!strcmp(argv[i],"-a") && !lastarg) {
735             config.auth = argv[++i];
736         } else if (!strcmp(argv[i],"--raw")) {
737             config.output = OUTPUT_RAW;
738         } else if (!strcmp(argv[i],"--no-raw")) {
739             config.output = OUTPUT_STANDARD;
740         } else if (!strcmp(argv[i],"--csv")) {
741             config.output = OUTPUT_CSV;
742         } else if (!strcmp(argv[i],"--latency")) {
743             config.latency_mode = 1;
744         } else if (!strcmp(argv[i],"--latency-history")) {
745             config.latency_mode = 1;
746             config.latency_history = 1;
747         } else if (!strcmp(argv[i],"--slave")) {
748             config.slave_mode = 1;
749         } else if (!strcmp(argv[i],"--stat")) {
750             config.stat_mode = 1;
751         } else if (!strcmp(argv[i],"--scan")) {
752             config.scan_mode = 1;
753         } else if (!strcmp(argv[i],"--pattern") && !lastarg) {
754             config.pattern = argv[++i];
755         } else if (!strcmp(argv[i],"--intrinsic-latency") && !lastarg) {
756             config.intrinsic_latency_mode = 1;
757             config.intrinsic_latency_duration = atoi(argv[++i]);
758         } else if (!strcmp(argv[i],"--rdb") && !lastarg) {
759             config.getrdb_mode = 1;
760             config.rdb_filename = argv[++i];
761         } else if (!strcmp(argv[i],"--pipe")) {
762             config.pipe_mode = 1;
763         } else if (!strcmp(argv[i],"--pipe-timeout") && !lastarg) {
764             config.pipe_timeout = atoi(argv[++i]);
765         } else if (!strcmp(argv[i],"--bigkeys")) {
766             config.bigkeys = 1;
767         } else if (!strcmp(argv[i],"--eval") && !lastarg) {
768             config.eval = argv[++i];
769         } else if (!strcmp(argv[i],"-c")) {
770             config.cluster_mode = 1;
771         } else if (!strcmp(argv[i],"-d") && !lastarg) {
772             sdsfree(config.mb_delim);
773             config.mb_delim = sdsnew(argv[++i]);
774         } else if (!strcmp(argv[i],"-v") || !strcmp(argv[i], "--version")) {
775             sds version = cliVersion();
776             printf("redis-cli %s\n", version);
777             sdsfree(version);
778             exit(0);
779         } else {
780             if (argv[i][0] == '-') {
781                 fprintf(stderr,
782                     "Unrecognized option or bad number of args for: '%s'\n",
783                     argv[i]);
784                 exit(1);
785             } else {
786                 /* Likely the command name, stop here. */
787                 break;
788             }
789         }
790     }
791     return i;
792 }
793 
794 static sds readArgFromStdin(void) {
795     char buf[1024];
796     sds arg = sdsempty();
797 
798     while(1) {
799         int nread = read(fileno(stdin),buf,1024);
800 
801         if (nread == 0) break;
802         else if (nread == -1) {
803             perror("Reading from standard input");
804             exit(1);
805         }
806         arg = sdscatlen(arg,buf,nread);
807     }
808     return arg;
809 }
810 
811 static void usage(void) {
812     sds version = cliVersion();
813     fprintf(stderr,
814 "redis-cli %s\n"
815 "\n"
816 "Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n"
817 "  -h <hostname>      Server hostname (default: 127.0.0.1).\n"
818 "  -p <port>          Server port (default: 6379).\n"
819 "  -s <socket>        Server socket (overrides hostname and port).\n"
820 "  -a <password>      Password to use when connecting to the server.\n"
821 "  -r <repeat>        Execute specified command N times.\n"
822 "  -i <interval>      When -r is used, waits <interval> seconds per command.\n"
823 "                     It is possible to specify sub-second times like -i 0.1.\n"
824 "  -n <db>            Database number.\n"
825 "  -x                 Read last argument from STDIN.\n"
826 "  -d <delimiter>     Multi-bulk delimiter in for raw formatting (default: \\n).\n"
827 "  -c                 Enable cluster mode (follow -ASK and -MOVED redirections).\n"
828 "  --raw              Use raw formatting for replies (default when STDOUT is\n"
829 "                     not a tty).\n"
830 "  --no-raw           Force formatted output even when STDOUT is not a tty.\n"
831 "  --csv              Output in CSV format.\n"
832 "  --latency          Enter a special mode continuously sampling latency.\n"
833 "  --latency-history  Like --latency but tracking latency changes over time.\n"
834 "                     Default time interval is 15 sec. Change it using -i.\n"
835 "  --slave            Simulate a slave showing commands received from the master.\n"
836 "  --rdb <filename>   Transfer an RDB dump from remote server to local file.\n"
837 "  --pipe             Transfer raw Redis protocol from stdin to server.\n"
838 "  --pipe-timeout <n> In --pipe mode, abort with error if after sending all data.\n"
839 "                     no reply is received within <n> seconds.\n"
840 "                     Default timeout: %d. Use 0 to wait forever.\n"
841 "  --bigkeys          Sample Redis keys looking for big keys.\n"
842 "  --scan             List all keys using the SCAN command.\n"
843 "  --pattern <pat>    Useful with --scan to specify a SCAN pattern.\n"
844 "  --intrinsic-latency <sec> Run a test to measure intrinsic system latency.\n"
845 "                     The test will run for the specified amount of seconds.\n"
846 "  --eval <file>      Send an EVAL command using the Lua script at <file>.\n"
847 "  --help             Output this help and exit.\n"
848 "  --version          Output version and exit.\n"
849 "\n"
850 "Examples:\n"
851 "  cat /etc/passwd | redis-cli -x set mypasswd\n"
852 "  redis-cli get mypasswd\n"
853 "  redis-cli -r 100 lpush mylist x\n"
854 "  redis-cli -r 100 -i 1 info | grep used_memory_human:\n"
855 "  redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3\n"
856 "  redis-cli --scan --pattern '*:12345*'\n"
857 "\n"
858 "  (Note: when using --eval the comma separates KEYS[] from ARGV[] items)\n"
859 "\n"
860 "When no command is given, redis-cli starts in interactive mode.\n"
861 "Type \"help\" in interactive mode for information on available commands.\n"
862 "\n",
863         version, REDIS_CLI_DEFAULT_PIPE_TIMEOUT);
864     sdsfree(version);
865     exit(1);
866 }
867 
868 /* Turn the plain C strings into Sds strings */
869 static char **convertToSds(int count, char** args) {
870   int j;
871   char **sds = zmalloc(sizeof(char*)*count);
872 
873   for(j = 0; j < count; j++)
874     sds[j] = sdsnew(args[j]);
875 
876   return sds;
877 }
878 
879 static void repl(void) {
880     sds historyfile = NULL;
881     int history = 0;
882     char *line;
883     int argc;
884     sds *argv;
885 
886     config.interactive = 1;
887     linenoiseSetMultiLine(1);
888     linenoiseSetCompletionCallback(completionCallback);
889 
890     /* Only use history when stdin is a tty. */
891     if (isatty(fileno(stdin))) {
892         history = 1;
893 
894         if (getenv("HOME") != NULL) {
895             historyfile = sdscatprintf(sdsempty(),"%s/.rediscli_history",getenv("HOME"));
896             linenoiseHistoryLoad(historyfile);
897         }
898     }
899 
900     cliRefreshPrompt();
901     while((line = linenoise(context ? config.prompt : "not connected> ")) != NULL) {
902         if (line[0] != '\0') {
903             argv = sdssplitargs(line,&argc);
904             if (history) linenoiseHistoryAdd(line);
905             if (historyfile) linenoiseHistorySave(historyfile);
906 
907             if (argv == NULL) {
908                 printf("Invalid argument(s)\n");
909                 free(line);
910                 continue;
911             } else if (argc > 0) {
912                 if (strcasecmp(argv[0],"quit") == 0 ||
913                     strcasecmp(argv[0],"exit") == 0)
914                 {
915                     exit(0);
916                 } else if (argc == 3 && !strcasecmp(argv[0],"connect")) {
917                     sdsfree(config.hostip);
918                     config.hostip = sdsnew(argv[1]);
919                     config.hostport = atoi(argv[2]);
920                     cliRefreshPrompt();
921                     cliConnect(1);
922                 } else if (argc == 1 && !strcasecmp(argv[0],"clear")) {
923                     linenoiseClearScreen();
924                 } else {
925                     long long start_time = mstime(), elapsed;
926                     int repeat, skipargs = 0;
927 
928                     repeat = atoi(argv[0]);
929                     if (argc > 1 && repeat) {
930                         skipargs = 1;
931                     } else {
932                         repeat = 1;
933                     }
934 
935                     while (1) {
936                         config.cluster_reissue_command = 0;
937                         if (cliSendCommand(argc-skipargs,argv+skipargs,repeat)
938                             != REDIS_OK)
939                         {
940                             cliConnect(1);
941 
942                             /* If we still cannot send the command print error.
943                              * We'll try to reconnect the next time. */
944                             if (cliSendCommand(argc-skipargs,argv+skipargs,repeat)
945                                 != REDIS_OK)
946                                 cliPrintContextError();
947                         }
948                         /* Issue the command again if we got redirected in cluster mode */
949                         if (config.cluster_mode && config.cluster_reissue_command) {
950                             cliConnect(1);
951                         } else {
952                             break;
953                         }
954                     }
955                     elapsed = mstime()-start_time;
956                     if (elapsed >= 500) {
957                         printf("(%.2fs)\n",(double)elapsed/1000);
958                     }
959                 }
960             }
961             /* Free the argument vector */
962             sdsfreesplitres(argv,argc);
963         }
964         /* linenoise() returns malloc-ed lines like readline() */
965         free(line);
966     }
967     exit(0);
968 }
969 
970 static int noninteractive(int argc, char **argv) {
971     int retval = 0;
972     if (config.stdinarg) {
973         argv = zrealloc(argv, (argc+1)*sizeof(char*));
974         argv[argc] = readArgFromStdin();
975         retval = cliSendCommand(argc+1, argv, config.repeat);
976     } else {
977         /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
978         retval = cliSendCommand(argc, argv, config.repeat);
979     }
980     return retval;
981 }
982 
983 /*------------------------------------------------------------------------------
984  * Eval mode
985  *--------------------------------------------------------------------------- */
986 
987 static int evalMode(int argc, char **argv) {
988     sds script = sdsempty();
989     FILE *fp;
990     char buf[1024];
991     size_t nread;
992     char **argv2;
993     int j, got_comma = 0, keys = 0;
994 
995     /* Load the script from the file, as an sds string. */
996     fp = fopen(config.eval,"r");
997     if (!fp) {
998         fprintf(stderr,
999             "Can't open file '%s': %s\n", config.eval, strerror(errno));
1000         exit(1);
1001     }
1002     while((nread = fread(buf,1,sizeof(buf),fp)) != 0) {
1003         script = sdscatlen(script,buf,nread);
1004     }
1005     fclose(fp);
1006 
1007     /* Create our argument vector */
1008     argv2 = zmalloc(sizeof(sds)*(argc+3));
1009     argv2[0] = sdsnew("EVAL");
1010     argv2[1] = script;
1011     for (j = 0; j < argc; j++) {
1012         if (!got_comma && argv[j][0] == ',' && argv[j][1] == 0) {
1013             got_comma = 1;
1014             continue;
1015         }
1016         argv2[j+3-got_comma] = sdsnew(argv[j]);
1017         if (!got_comma) keys++;
1018     }
1019     argv2[2] = sdscatprintf(sdsempty(),"%d",keys);
1020 
1021     /* Call it */
1022     return cliSendCommand(argc+3-got_comma, argv2, config.repeat);
1023 }
1024 
1025 /*------------------------------------------------------------------------------
1026  * Latency and latency history modes
1027  *--------------------------------------------------------------------------- */
1028 
1029 #define LATENCY_SAMPLE_RATE 10 /* milliseconds. */
1030 #define LATENCY_HISTORY_DEFAULT_INTERVAL 15000 /* milliseconds. */
1031 static void latencyMode(void) {
1032     redisReply *reply;
1033     long long start, latency, min = 0, max = 0, tot = 0, count = 0;
1034     long long history_interval =
1035         config.interval ? config.interval/1000 :
1036                           LATENCY_HISTORY_DEFAULT_INTERVAL;
1037     double avg;
1038     long long history_start = mstime();
1039 
1040     if (!context) exit(1);
1041     while(1) {
1042         start = mstime();
1043         reply = redisCommand(context,"PING");
1044         if (reply == NULL) {
1045             fprintf(stderr,"\nI/O error\n");
1046             exit(1);
1047         }
1048         latency = mstime()-start;
1049         freeReplyObject(reply);
1050         count++;
1051         if (count == 1) {
1052             min = max = tot = latency;
1053             avg = (double) latency;
1054         } else {
1055             if (latency < min) min = latency;
1056             if (latency > max) max = latency;
1057             tot += latency;
1058             avg = (double) tot/count;
1059         }
1060         printf("\x1b[0G\x1b[2Kmin: %lld, max: %lld, avg: %.2f (%lld samples)",
1061             min, max, avg, count);
1062         fflush(stdout);
1063         if (config.latency_history && mstime()-history_start > history_interval)
1064         {
1065             printf(" -- %.2f seconds range\n", (float)(mstime()-history_start)/1000);
1066             history_start = mstime();
1067             min = max = tot = count = 0;
1068         }
1069         usleep(LATENCY_SAMPLE_RATE * 1000);
1070     }
1071 }
1072 
1073 /*------------------------------------------------------------------------------
1074  * Slave mode
1075  *--------------------------------------------------------------------------- */
1076 
1077 /* Sends SYNC and reads the number of bytes in the payload. Used both by
1078  * slaveMode() and getRDB(). */
1079 unsigned long long sendSync(int fd) {
1080     /* To start we need to send the SYNC command and return the payload.
1081      * The hiredis client lib does not understand this part of the protocol
1082      * and we don't want to mess with its buffers, so everything is performed
1083      * using direct low-level I/O. */
1084     char buf[4096], *p;
1085     ssize_t nread;
1086 
1087     /* Send the SYNC command. */
1088     if (write(fd,"SYNC\r\n",6) != 6) {
1089         fprintf(stderr,"Error writing to master\n");
1090         exit(1);
1091     }
1092 
1093     /* Read $<payload>\r\n, making sure to read just up to "\n" */
1094     p = buf;
1095     while(1) {
1096         nread = read(fd,p,1);
1097         if (nread <= 0) {
1098             fprintf(stderr,"Error reading bulk length while SYNCing\n");
1099             exit(1);
1100         }
1101         if (*p == '\n' && p != buf) break;
1102         if (*p != '\n') p++;
1103     }
1104     *p = '\0';
1105     if (buf[0] == '-') {
1106         printf("SYNC with master failed: %s\n", buf);
1107         exit(1);
1108     }
1109     return strtoull(buf+1,NULL,10);
1110 }
1111 
1112 static void slaveMode(void) {
1113     int fd = context->fd;
1114     unsigned long long payload = sendSync(fd);
1115     char buf[1024];
1116     int original_output = config.output;
1117 
1118     fprintf(stderr,"SYNC with master, discarding %llu "
1119                    "bytes of bulk transfer...\n", payload);
1120 
1121     /* Discard the payload. */
1122     while(payload) {
1123         ssize_t nread;
1124 
1125         nread = read(fd,buf,(payload > sizeof(buf)) ? sizeof(buf) : payload);
1126         if (nread <= 0) {
1127             fprintf(stderr,"Error reading RDB payload while SYNCing\n");
1128             exit(1);
1129         }
1130         payload -= nread;
1131     }
1132     fprintf(stderr,"SYNC done. Logging commands from master.\n");
1133 
1134     /* Now we can use hiredis to read the incoming protocol. */
1135     config.output = OUTPUT_CSV;
1136     while (cliReadReply(0) == REDIS_OK);
1137     config.output = original_output;
1138 }
1139 
1140 /*------------------------------------------------------------------------------
1141  * RDB transfer mode
1142  *--------------------------------------------------------------------------- */
1143 
1144 /* This function implements --rdb, so it uses the replication protocol in order
1145  * to fetch the RDB file from a remote server. */
1146 static void getRDB(void) {
1147     int s = context->fd;
1148     int fd;
1149     unsigned long long payload = sendSync(s);
1150     char buf[4096];
1151 
1152     fprintf(stderr,"SYNC sent to master, writing %llu bytes to '%s'\n",
1153         payload, config.rdb_filename);
1154 
1155     /* Write to file. */
1156     if (!strcmp(config.rdb_filename,"-")) {
1157         fd = STDOUT_FILENO;
1158     } else {
1159         fd = open(config.rdb_filename, O_CREAT|O_WRONLY, 0644);
1160         if (fd == -1) {
1161             fprintf(stderr, "Error opening '%s': %s\n", config.rdb_filename,
1162                 strerror(errno));
1163             exit(1);
1164         }
1165     }
1166 
1167     while(payload) {
1168         ssize_t nread, nwritten;
1169 
1170         nread = read(s,buf,(payload > sizeof(buf)) ? sizeof(buf) : payload);
1171         if (nread <= 0) {
1172             fprintf(stderr,"I/O Error reading RDB payload from socket\n");
1173             exit(1);
1174         }
1175         nwritten = write(fd, buf, nread);
1176         if (nwritten != nread) {
1177             fprintf(stderr,"Error writing data to file: %s\n",
1178                 strerror(errno));
1179             exit(1);
1180         }
1181         payload -= nread;
1182     }
1183     close(s); /* Close the file descriptor ASAP as fsync() may take time. */
1184     fsync(fd);
1185     fprintf(stderr,"Transfer finished with success.\n");
1186     exit(0);
1187 }
1188 
1189 /*------------------------------------------------------------------------------
1190  * Bulk import (pipe) mode
1191  *--------------------------------------------------------------------------- */
1192 
1193 static void pipeMode(void) {
1194     int fd = context->fd;
1195     long long errors = 0, replies = 0, obuf_len = 0, obuf_pos = 0;
1196     char ibuf[1024*16], obuf[1024*16]; /* Input and output buffers */
1197     char aneterr[ANET_ERR_LEN];
1198     redisReader *reader = redisReaderCreate();
1199     redisReply *reply;
1200     int eof = 0; /* True once we consumed all the standard input. */
1201     int done = 0;
1202     char magic[20]; /* Special reply we recognize. */
1203     time_t last_read_time = time(NULL);
1204 
1205     srand(time(NULL));
1206 
1207     /* Use non blocking I/O. */
1208     if (anetNonBlock(aneterr,fd) == ANET_ERR) {
1209         fprintf(stderr, "Can't set the socket in non blocking mode: %s\n",
1210             aneterr);
1211         exit(1);
1212     }
1213 
1214     /* Transfer raw protocol and read replies from the server at the same
1215      * time. */
1216     while(!done) {
1217         int mask = AE_READABLE;
1218 
1219         if (!eof || obuf_len != 0) mask |= AE_WRITABLE;
1220         mask = aeWait(fd,mask,1000);
1221 
1222         /* Handle the readable state: we can read replies from the server. */
1223         if (mask & AE_READABLE) {
1224             ssize_t nread;
1225 
1226             /* Read from socket and feed the hiredis reader. */
1227             do {
1228                 nread = read(fd,ibuf,sizeof(ibuf));
1229                 if (nread == -1 && errno != EAGAIN && errno != EINTR) {
1230                     fprintf(stderr, "Error reading from the server: %s\n",
1231                         strerror(errno));
1232                     exit(1);
1233                 }
1234                 if (nread > 0) {
1235                     redisReaderFeed(reader,ibuf,nread);
1236                     last_read_time = time(NULL);
1237                 }
1238             } while(nread > 0);
1239 
1240             /* Consume replies. */
1241             do {
1242                 if (redisReaderGetReply(reader,(void**)&reply) == REDIS_ERR) {
1243                     fprintf(stderr, "Error reading replies from server\n");
1244                     exit(1);
1245                 }
1246                 if (reply) {
1247                     if (reply->type == REDIS_REPLY_ERROR) {
1248                         fprintf(stderr,"%s\n", reply->str);
1249                         errors++;
1250                     } else if (eof && reply->type == REDIS_REPLY_STRING &&
1251                                       reply->len == 20) {
1252                         /* Check if this is the reply to our final ECHO
1253                          * command. If so everything was received
1254                          * from the server. */
1255                         if (memcmp(reply->str,magic,20) == 0) {
1256                             printf("Last reply received from server.\n");
1257                             done = 1;
1258                             replies--;
1259                         }
1260                     }
1261                     replies++;
1262                     freeReplyObject(reply);
1263                 }
1264             } while(reply);
1265         }
1266 
1267         /* Handle the writable state: we can send protocol to the server. */
1268         if (mask & AE_WRITABLE) {
1269             while(1) {
1270                 /* Transfer current buffer to server. */
1271                 if (obuf_len != 0) {
1272                     ssize_t nwritten = write(fd,obuf+obuf_pos,obuf_len);
1273 
1274                     if (nwritten == -1) {
1275                         if (errno != EAGAIN && errno != EINTR) {
1276                             fprintf(stderr, "Error writing to the server: %s\n",
1277                                 strerror(errno));
1278                             exit(1);
1279                         } else {
1280                             nwritten = 0;
1281                         }
1282                     }
1283                     obuf_len -= nwritten;
1284                     obuf_pos += nwritten;
1285                     if (obuf_len != 0) break; /* Can't accept more data. */
1286                 }
1287                 /* If buffer is empty, load from stdin. */
1288                 if (obuf_len == 0 && !eof) {
1289                     ssize_t nread = read(STDIN_FILENO,obuf,sizeof(obuf));
1290 
1291                     if (nread == 0) {
1292                         /* The ECHO sequence starts with a "\r\n" so that if there
1293                          * is garbage in the protocol we read from stdin, the ECHO
1294                          * will likely still be properly formatted.
1295                          * CRLF is ignored by Redis, so it has no effects. */
1296                         char echo[] =
1297                         "\r\n*2\r\n$4\r\nECHO\r\n$20\r\n01234567890123456789\r\n";
1298                         int j;
1299 
1300                         eof = 1;
1301                         /* Everything transferred, so we queue a special
1302                          * ECHO command that we can match in the replies
1303                          * to make sure everything was read from the server. */
1304                         for (j = 0; j < 20; j++)
1305                             magic[j] = rand() & 0xff;
1306                         memcpy(echo+21,magic,20);
1307                         memcpy(obuf,echo,sizeof(echo)-1);
1308                         obuf_len = sizeof(echo)-1;
1309                         obuf_pos = 0;
1310                         printf("All data transferred. Waiting for the last reply...\n");
1311                     } else if (nread == -1) {
1312                         fprintf(stderr, "Error reading from stdin: %s\n",
1313                             strerror(errno));
1314                         exit(1);
1315                     } else {
1316                         obuf_len = nread;
1317                         obuf_pos = 0;
1318                     }
1319                 }
1320                 if (obuf_len == 0 && eof) break;
1321             }
1322         }
1323 
1324         /* Handle timeout, that is, we reached EOF, and we are not getting
1325          * replies from the server for a few seconds, nor the final ECHO is
1326          * received. */
1327         if (eof && config.pipe_timeout > 0 &&
1328             time(NULL)-last_read_time > config.pipe_timeout)
1329         {
1330             fprintf(stderr,"No replies for %d seconds: exiting.\n",
1331                 config.pipe_timeout);
1332             errors++;
1333             break;
1334         }
1335     }
1336     redisReaderFree(reader);
1337     printf("errors: %lld, replies: %lld\n", errors, replies);
1338     if (errors)
1339         exit(1);
1340     else
1341         exit(0);
1342 }
1343 
1344 /*------------------------------------------------------------------------------
1345  * Find big keys
1346  *--------------------------------------------------------------------------- */
1347 
1348 #define TYPE_STRING 0
1349 #define TYPE_LIST   1
1350 #define TYPE_SET    2
1351 #define TYPE_HASH   3
1352 #define TYPE_ZSET   4
1353 #define TYPE_NONE   5
1354 
1355 static redisReply *sendScan(unsigned long long *it) {
1356     redisReply *reply = redisCommand(context, "SCAN %llu", *it);
1357 
1358     /* Handle any error conditions */
1359     if(reply == NULL) {
1360         fprintf(stderr, "\nI/O error\n");
1361         exit(1);
1362     } else if(reply->type == REDIS_REPLY_ERROR) {
1363         fprintf(stderr, "SCAN error: %s\n", reply->str);
1364         exit(1);
1365     } else if(reply->type != REDIS_REPLY_ARRAY) {
1366         fprintf(stderr, "Non ARRAY response from SCAN!\n");
1367         exit(1);
1368     } else if(reply->elements != 2) {
1369         fprintf(stderr, "Invalid element count from SCAN!\n");
1370         exit(1);
1371     }
1372 
1373     /* Validate our types are correct */
1374     assert(reply->element[0]->type == REDIS_REPLY_STRING);
1375     assert(reply->element[1]->type == REDIS_REPLY_ARRAY);
1376 
1377     /* Update iterator */
1378     *it = atoi(reply->element[0]->str);
1379 
1380     return reply;
1381 }
1382 
1383 static int getDbSize(void) {
1384     redisReply *reply;
1385     int size;
1386 
1387     reply = redisCommand(context, "DBSIZE");
1388 
1389     if(reply == NULL || reply->type != REDIS_REPLY_INTEGER) {
1390         fprintf(stderr, "Couldn't determine DBSIZE!\n");
1391         exit(1);
1392     }
1393 
1394     /* Grab the number of keys and free our reply */
1395     size = reply->integer;
1396     freeReplyObject(reply);
1397 
1398     return size;
1399 }
1400 
1401 static int toIntType(char *key, char *type) {
1402     if(!strcmp(type, "string")) {
1403         return TYPE_STRING;
1404     } else if(!strcmp(type, "list")) {
1405         return TYPE_LIST;
1406     } else if(!strcmp(type, "set")) {
1407         return TYPE_SET;
1408     } else if(!strcmp(type, "hash")) {
1409         return TYPE_HASH;
1410     } else if(!strcmp(type, "zset")) {
1411         return TYPE_ZSET;
1412     } else if(!strcmp(type, "none")) {
1413         return TYPE_NONE;
1414     } else {
1415         fprintf(stderr, "Unknown type '%s' for key '%s'\n", type, key);
1416         exit(1);
1417     }
1418 }
1419 
1420 static void getKeyTypes(redisReply *keys, int *types) {
1421     redisReply *reply;
1422     unsigned int i;
1423 
1424     /* Pipeline TYPE commands */
1425     for(i=0;i<keys->elements;i++) {
1426         redisAppendCommand(context, "TYPE %s", keys->element[i]->str);
1427     }
1428 
1429     /* Retrieve types */
1430     for(i=0;i<keys->elements;i++) {
1431         if(redisGetReply(context, (void**)&reply)!=REDIS_OK) {
1432             fprintf(stderr, "Error getting type for key '%s' (%d: %s)\n",
1433                 keys->element[i]->str, context->err, context->errstr);
1434             exit(1);
1435         } else if(reply->type != REDIS_REPLY_STATUS) {
1436             fprintf(stderr, "Invalid reply type (%d) for TYPE on key '%s'!\n",
1437                 reply->type, keys->element[i]->str);
1438             exit(1);
1439         }
1440 
1441         types[i] = toIntType(keys->element[i]->str, reply->str);
1442         freeReplyObject(reply);
1443     }
1444 }
1445 
1446 static void getKeySizes(redisReply *keys, int *types,
1447                         unsigned long long *sizes)
1448 {
1449     redisReply *reply;
1450     char *sizecmds[] = {"STRLEN","LLEN","SCARD","HLEN","ZCARD"};
1451     unsigned int i;
1452 
1453     /* Pipeline size commands */
1454     for(i=0;i<keys->elements;i++) {
1455         /* Skip keys that were deleted */
1456         if(types[i]==TYPE_NONE)
1457             continue;
1458 
1459         redisAppendCommand(context, "%s %s", sizecmds[types[i]],
1460             keys->element[i]->str);
1461     }
1462 
1463     /* Retreive sizes */
1464     for(i=0;i<keys->elements;i++) {
1465         /* Skip keys that dissapeared between SCAN and TYPE */
1466         if(types[i] == TYPE_NONE) {
1467             sizes[i] = 0;
1468             continue;
1469         }
1470 
1471         /* Retreive size */
1472         if(redisGetReply(context, (void**)&reply)!=REDIS_OK) {
1473             fprintf(stderr, "Error getting size for key '%s' (%d: %s)\n",
1474                 keys->element[i]->str, context->err, context->errstr);
1475             exit(1);
1476         } else if(reply->type != REDIS_REPLY_INTEGER) {
1477             /* Theoretically the key could have been removed and
1478              * added as a different type between TYPE and SIZE */
1479             fprintf(stderr,
1480                 "Warning:  %s on '%s' failed (may have changed type)\n",
1481                  sizecmds[types[i]], keys->element[i]->str);
1482             sizes[i] = 0;
1483         } else {
1484             sizes[i] = reply->integer;
1485         }
1486 
1487         freeReplyObject(reply);
1488     }
1489 }
1490 
1491 static void findBigKeys(void) {
1492     unsigned long long biggest[5] = {0}, counts[5] = {0}, totalsize[5] = {0};
1493     unsigned long long sampled = 0, total_keys, totlen=0, *sizes=NULL, it=0;
1494     sds maxkeys[5] = {0};
1495     char *typename[] = {"string","list","set","hash","zset"};
1496     char *typeunit[] = {"bytes","items","members","fields","members"};
1497     redisReply *reply, *keys;
1498     unsigned int arrsize=0, i;
1499     int type, *types=NULL;
1500     double pct;
1501 
1502     /* Total keys pre scanning */
1503     total_keys = getDbSize();
1504 
1505     /* Status message */
1506     printf("\n# Scanning the entire keyspace to find biggest keys as well as\n");
1507     printf("# average sizes per key type.  You can use -i 0.1 to sleep 0.1 sec\n");
1508     printf("# per 100 SCAN commands (not usually needed).\n\n");
1509 
1510     /* New up sds strings to keep track of overall biggest per type */
1511     for(i=0;i<TYPE_NONE; i++) {
1512         maxkeys[i] = sdsempty();
1513         if(!maxkeys[i]) {
1514             fprintf(stderr, "Failed to allocate memory for largest key names!");
1515             exit(1);
1516         }
1517     }
1518 
1519     /* SCAN loop */
1520     do {
1521         /* Calculate approximate percentage completion */
1522         pct = 100 * (double)sampled/total_keys;
1523 
1524         /* Grab some keys and point to the keys array */
1525         reply = sendScan(&it);
1526         keys  = reply->element[1];
1527 
1528         /* Reallocate our type and size array if we need to */
1529         if(keys->elements > arrsize) {
1530             types = zrealloc(types, sizeof(int)*keys->elements);
1531             sizes = zrealloc(sizes, sizeof(unsigned long long)*keys->elements);
1532 
1533             if(!types || !sizes) {
1534                 fprintf(stderr, "Failed to allocate storage for keys!\n");
1535                 exit(1);
1536             }
1537 
1538             arrsize = keys->elements;
1539         }
1540 
1541         /* Retreive types and then sizes */
1542         getKeyTypes(keys, types);
1543         getKeySizes(keys, types, sizes);
1544 
1545         /* Now update our stats */
1546         for(i=0;i<keys->elements;i++) {
1547             if((type = types[i]) == TYPE_NONE)
1548                 continue;
1549 
1550             totalsize[type] += sizes[i];
1551             counts[type]++;
1552             totlen += keys->element[i]->len;
1553             sampled++;
1554 
1555             if(biggest[type]<sizes[i]) {
1556                 printf(
1557                    "[%05.2f%%] Biggest %-6s found so far '%s' with %llu %s\n",
1558                    pct, typename[type], keys->element[i]->str, sizes[i],
1559                    typeunit[type]);
1560 
1561                 /* Keep track of biggest key name for this type */
1562                 maxkeys[type] = sdscpy(maxkeys[type], keys->element[i]->str);
1563                 if(!maxkeys[type]) {
1564                     fprintf(stderr, "Failed to allocate memory for key!\n");
1565                     exit(1);
1566                 }
1567 
1568                 /* Keep track of the biggest size for this type */
1569                 biggest[type] = sizes[i];
1570             }
1571 
1572             /* Update overall progress */
1573             if(sampled % 1000000 == 0) {
1574                 printf("[%05.2f%%] Sampled %llu keys so far\n", pct, sampled);
1575             }
1576         }
1577 
1578         /* Sleep if we've been directed to do so */
1579         if(sampled && (sampled %100) == 0 && config.interval) {
1580             usleep(config.interval);
1581         }
1582 
1583         freeReplyObject(reply);
1584     } while(it != 0);
1585 
1586     if(types) zfree(types);
1587     if(sizes) zfree(sizes);
1588 
1589     /* We're done */
1590     printf("\n-------- summary -------\n\n");
1591 
1592     printf("Sampled %llu keys in the keyspace!\n", sampled);
1593     printf("Total key length in bytes is %llu (avg len %.2f)\n\n",
1594        totlen, totlen ? (double)totlen/sampled : 0);
1595 
1596     /* Output the biggest keys we found, for types we did find */
1597     for(i=0;i<TYPE_NONE;i++) {
1598         if(sdslen(maxkeys[i])>0) {
1599             printf("Biggest %6s found '%s' has %llu %s\n", typename[i], maxkeys[i],
1600                biggest[i], typeunit[i]);
1601         }
1602     }
1603 
1604     printf("\n");
1605 
1606     for(i=0;i<TYPE_NONE;i++) {
1607         printf("%llu %ss with %llu %s (%05.2f%% of keys, avg size %.2f)\n",
1608            counts[i], typename[i], totalsize[i], typeunit[i],
1609            sampled ? 100 * (double)counts[i]/sampled : 0,
1610            counts[i] ? (double)totalsize[i]/counts[i] : 0);
1611     }
1612 
1613     /* Free sds strings containing max keys */
1614     for(i=0;i<TYPE_NONE;i++) {
1615         sdsfree(maxkeys[i]);
1616     }
1617 
1618     /* Success! */
1619     exit(0);
1620 }
1621 
1622 /*------------------------------------------------------------------------------
1623  * Stats mode
1624  *--------------------------------------------------------------------------- */
1625 
1626 /* Return the specified INFO field from the INFO command output "info".
1627  * A new buffer is allocated for the result, that needs to be free'd.
1628  * If the field is not found NULL is returned. */
1629 static char *getInfoField(char *info, char *field) {
1630     char *p = strstr(info,field);
1631     char *n1, *n2;
1632     char *result;
1633 
1634     if (!p) return NULL;
1635     p += strlen(field)+1;
1636     n1 = strchr(p,'\r');
1637     n2 = strchr(p,',');
1638     if (n2 && n2 < n1) n1 = n2;
1639     result = malloc(sizeof(char)*(n1-p)+1);
1640     memcpy(result,p,(n1-p));
1641     result[n1-p] = '\0';
1642     return result;
1643 }
1644 
1645 /* Like the above function but automatically convert the result into
1646  * a long. On error (missing field) LONG_MIN is returned. */
1647 static long getLongInfoField(char *info, char *field) {
1648     char *value = getInfoField(info,field);
1649     long l;
1650 
1651     if (!value) return LONG_MIN;
1652     l = strtol(value,NULL,10);
1653     free(value);
1654     return l;
1655 }
1656 
1657 /* Convert number of bytes into a human readable string of the form:
1658  * 100B, 2G, 100M, 4K, and so forth. */
1659 void bytesToHuman(char *s, long long n) {
1660     double d;
1661 
1662     if (n < 0) {
1663         *s = '-';
1664         s++;
1665         n = -n;
1666     }
1667     if (n < 1024) {
1668         /* Bytes */
1669         sprintf(s,"%lluB",n);
1670         return;
1671     } else if (n < (1024*1024)) {
1672         d = (double)n/(1024);
1673         sprintf(s,"%.2fK",d);
1674     } else if (n < (1024LL*1024*1024)) {
1675         d = (double)n/(1024*1024);
1676         sprintf(s,"%.2fM",d);
1677     } else if (n < (1024LL*1024*1024*1024)) {
1678         d = (double)n/(1024LL*1024*1024);
1679         sprintf(s,"%.2fG",d);
1680     }
1681 }
1682 
1683 static void statMode(void) {
1684     redisReply *reply;
1685     long aux, requests = 0;
1686     int i = 0;
1687 
1688     while(1) {
1689         char buf[64];
1690         int j;
1691 
1692         reply = reconnectingInfo();
1693         if (reply->type == REDIS_REPLY_ERROR) {
1694             printf("ERROR: %s\n", reply->str);
1695             exit(1);
1696         }
1697 
1698         if ((i++ % 20) == 0) {
1699             printf(
1700 "------- data ------ --------------------- load -------------------- - child -\n"
1701 "keys       mem      clients blocked requests            connections          \n");
1702         }
1703 
1704         /* Keys */
1705         aux = 0;
1706         for (j = 0; j < 20; j++) {
1707             long k;
1708 
1709             sprintf(buf,"db%d:keys",j);
1710             k = getLongInfoField(reply->str,buf);
1711             if (k == LONG_MIN) continue;
1712             aux += k;
1713         }
1714         sprintf(buf,"%ld",aux);
1715         printf("%-11s",buf);
1716 
1717         /* Used memory */
1718         aux = getLongInfoField(reply->str,"used_memory");
1719         bytesToHuman(buf,aux);
1720         printf("%-8s",buf);
1721 
1722         /* Clients */
1723         aux = getLongInfoField(reply->str,"connected_clients");
1724         sprintf(buf,"%ld",aux);
1725         printf(" %-8s",buf);
1726 
1727         /* Blocked (BLPOPPING) Clients */
1728         aux = getLongInfoField(reply->str,"blocked_clients");
1729         sprintf(buf,"%ld",aux);
1730         printf("%-8s",buf);
1731 
1732         /* Requets */
1733         aux = getLongInfoField(reply->str,"total_commands_processed");
1734         sprintf(buf,"%ld (+%ld)",aux,requests == 0 ? 0 : aux-requests);
1735         printf("%-19s",buf);
1736         requests = aux;
1737 
1738         /* Connections */
1739         aux = getLongInfoField(reply->str,"total_connections_received");
1740         sprintf(buf,"%ld",aux);
1741         printf(" %-12s",buf);
1742 
1743         /* Children */
1744         aux = getLongInfoField(reply->str,"bgsave_in_progress");
1745         aux |= getLongInfoField(reply->str,"aof_rewrite_in_progress") << 1;
1746         switch(aux) {
1747         case 0: break;
1748         case 1:
1749             printf("SAVE");
1750             break;
1751         case 2:
1752             printf("AOF");
1753             break;
1754         case 3:
1755             printf("SAVE+AOF");
1756             break;
1757         }
1758 
1759         printf("\n");
1760         freeReplyObject(reply);
1761         usleep(config.interval);
1762     }
1763 }
1764 
1765 /*------------------------------------------------------------------------------
1766  * Scan mode
1767  *--------------------------------------------------------------------------- */
1768 
1769 static void scanMode(void) {
1770     redisReply *reply;
1771     unsigned long long cur = 0;
1772 
1773     do {
1774         if (config.pattern)
1775             reply = redisCommand(context,"SCAN %llu MATCH %s",
1776                 cur,config.pattern);
1777         else
1778             reply = redisCommand(context,"SCAN %llu",cur);
1779         if (reply == NULL) {
1780             printf("I/O error\n");
1781             exit(1);
1782         } else if (reply->type == REDIS_REPLY_ERROR) {
1783             printf("ERROR: %s\n", reply->str);
1784             exit(1);
1785         } else {
1786             unsigned int j;
1787 
1788             cur = strtoull(reply->element[0]->str,NULL,10);
1789             for (j = 0; j < reply->element[1]->elements; j++)
1790                 printf("%s\n", reply->element[1]->element[j]->str);
1791         }
1792         freeReplyObject(reply);
1793     } while(cur != 0);
1794 
1795     exit(0);
1796 }
1797 
1798 /*------------------------------------------------------------------------------
1799  * Intrisic latency mode.
1800  *
1801  * Measure max latency of a running process that does not result from
1802  * syscalls. Basically this software should provide an hint about how much
1803  * time the kernel leaves the process without a chance to run.
1804  *--------------------------------------------------------------------------- */
1805 
1806 /* This is just some computation the compiler can't optimize out.
1807  * Should run in less than 100-200 microseconds even using very
1808  * slow hardware. Runs in less than 10 microseconds in modern HW. */
1809 unsigned long compute_something_fast(void) {
1810     unsigned char s[256], i, j, t;
1811     int count = 1000, k;
1812     unsigned long output = 0;
1813 
1814     for (k = 0; k < 256; k++) s[k] = k;
1815 
1816     i = 0;
1817     j = 0;
1818     while(count--) {
1819         i++;
1820         j = j + s[i];
1821         t = s[i];
1822         s[i] = s[j];
1823         s[j] = t;
1824         output += s[(s[i]+s[j])&255];
1825     }
1826     return output;
1827 }
1828 
1829 static void intrinsicLatencyModeStop(int s) {
1830     REDIS_NOTUSED(s);
1831     force_cancel_loop = 1;
1832 }
1833 
1834 static void intrinsicLatencyMode(void) {
1835     long long test_end, run_time, max_latency = 0, runs = 0;
1836 
1837     run_time = config.intrinsic_latency_duration*1000000;
1838     test_end = ustime() + run_time;
1839     signal(SIGINT, intrinsicLatencyModeStop);
1840 
1841     while(1) {
1842         long long start, end, latency;
1843 
1844         start = ustime();
1845         compute_something_fast();
1846         end = ustime();
1847         latency = end-start;
1848         runs++;
1849         if (latency <= 0) continue;
1850 
1851         /* Reporting */
1852         if (latency > max_latency) {
1853             max_latency = latency;
1854             printf("Max latency so far: %lld microseconds.\n", max_latency);
1855         }
1856 
1857         double avg_us = (double)run_time/runs;
1858         double avg_ns = avg_us * 10e3;
1859         if (force_cancel_loop || end > test_end) {
1860             printf("\n%lld total runs "
1861                 "(avg latency: "
1862                 "%.4f microseconds / %.2f nanoseconds per run).\n",
1863                 runs, avg_us, avg_ns);
1864             printf("Worst run took %.0fx longer than the average latency.\n",
1865                 max_latency / avg_us);
1866             exit(0);
1867         }
1868     }
1869 }
1870 
1871 /*------------------------------------------------------------------------------
1872  * Program main()
1873  *--------------------------------------------------------------------------- */
1874 
1875 int main(int argc, char **argv) {
1876     int firstarg;
1877 
1878     config.hostip = sdsnew("127.0.0.1");
1879     config.hostport = 6379;
1880     config.hostsocket = NULL;
1881     config.repeat = 1;
1882     config.interval = 0;
1883     config.dbnum = 0;
1884     config.interactive = 0;
1885     config.shutdown = 0;
1886     config.monitor_mode = 0;
1887     config.pubsub_mode = 0;
1888     config.latency_mode = 0;
1889     config.latency_history = 0;
1890     config.cluster_mode = 0;
1891     config.slave_mode = 0;
1892     config.getrdb_mode = 0;
1893     config.stat_mode = 0;
1894     config.scan_mode = 0;
1895     config.intrinsic_latency_mode = 0;
1896     config.pattern = NULL;
1897     config.rdb_filename = NULL;
1898     config.pipe_mode = 0;
1899     config.pipe_timeout = REDIS_CLI_DEFAULT_PIPE_TIMEOUT;
1900     config.bigkeys = 0;
1901     config.stdinarg = 0;
1902     config.auth = NULL;
1903     config.eval = NULL;
1904     config.last_cmd_type = -1;
1905 
1906     if (!isatty(fileno(stdout)) && (getenv("FAKETTY") == NULL))
1907         config.output = OUTPUT_RAW;
1908     else
1909         config.output = OUTPUT_STANDARD;
1910     config.mb_delim = sdsnew("\n");
1911     cliInitHelp();
1912 
1913     firstarg = parseOptions(argc,argv);
1914     argc -= firstarg;
1915     argv += firstarg;
1916 
1917     /* Latency mode */
1918     if (config.latency_mode) {
1919         if (cliConnect(0) == REDIS_ERR) exit(1);
1920         latencyMode();
1921     }
1922 
1923     /* Slave mode */
1924     if (config.slave_mode) {
1925         if (cliConnect(0) == REDIS_ERR) exit(1);
1926         slaveMode();
1927     }
1928 
1929     /* Get RDB mode. */
1930     if (config.getrdb_mode) {
1931         if (cliConnect(0) == REDIS_ERR) exit(1);
1932         getRDB();
1933     }
1934 
1935     /* Pipe mode */
1936     if (config.pipe_mode) {
1937         if (cliConnect(0) == REDIS_ERR) exit(1);
1938         pipeMode();
1939     }
1940 
1941     /* Find big keys */
1942     if (config.bigkeys) {
1943         if (cliConnect(0) == REDIS_ERR) exit(1);
1944         findBigKeys();
1945     }
1946 
1947     /* Stat mode */
1948     if (config.stat_mode) {
1949         if (cliConnect(0) == REDIS_ERR) exit(1);
1950         if (config.interval == 0) config.interval = 1000000;
1951         statMode();
1952     }
1953 
1954     /* Scan mode */
1955     if (config.scan_mode) {
1956         if (cliConnect(0) == REDIS_ERR) exit(1);
1957         scanMode();
1958     }
1959 
1960     /* Intrinsic latency mode */
1961     if (config.intrinsic_latency_mode) intrinsicLatencyMode();
1962 
1963     /* Start interactive mode when no command is provided */
1964     if (argc == 0 && !config.eval) {
1965         /* Note that in repl mode we don't abort on connection error.
1966          * A new attempt will be performed for every command send. */
1967         cliConnect(0);
1968         repl();
1969     }
1970 
1971     /* Otherwise, we have some arguments to execute */
1972     if (cliConnect(0) != REDIS_OK) exit(1);
1973     if (config.eval) {
1974         return evalMode(argc,argv);
1975     } else {
1976         return noninteractive(argc,convertToSds(argc,argv));
1977     }
1978 }
1979