From e16933cec1f5c21ec6372f95b5baf9e71a8cf53d Mon Sep 17 00:00:00 2001 From: Tomasz Poradowski Date: Wed, 13 Dec 2017 23:32:36 +0100 Subject: [PATCH] enable command history in redis-cli - when output is a TTY - always enable linenoise history (regardless if history file name can be determined) - adjusted redis-cli/getDotfilePath() to use %HOMEDRIVE%%HOMPATH% environment variables to find user's home folder --- msvs/msi/RedisMsi/Product.wxs | 2 +- src/redis-cli.c | 1398 ++++++++++++++++++--------------- 2 files changed, 753 insertions(+), 647 deletions(-) diff --git a/msvs/msi/RedisMsi/Product.wxs b/msvs/msi/RedisMsi/Product.wxs index b027ddea..d4bb8142 100644 --- a/msvs/msi/RedisMsi/Product.wxs +++ b/msvs/msi/RedisMsi/Product.wxs @@ -22,7 +22,7 @@ Name="Redis on Windows" Language="1033" Version="4.0.2" - Manufacturer="MSOpenTech" + Manufacturer="Poradowski.com" UpgradeCode="{05410198-7212-4FC4-B7C8-AFEFC3DA0FBC}"> "); + snprintf(config.prompt + len, sizeof(config.prompt) - len, "> "); } /* Return the name of the dotfile for the specified 'dotfilename'. @@ -221,12 +221,23 @@ static sds getDotfilePath(char *envoverride, char *dotfilename) { /* If the env is set, return it. */ dotPath = sdsnew(path); - } else { + } + else { +#ifdef _WIN32_TEST + char *homeDrive = getenv("HOMEDRIVE"); + char *homePath = getenv("HOMEPATH"); + + if ((homeDrive != NULL) && (*homeDrive != '\0') + && (homePath != NULL) && (*homePath != '\0')) { + dotPath = sdscatprintf(sdsempty(), "%s%s\\%s", homeDrive, homePath, dotfilename); + } +#else char *home = getenv("HOME"); if (home != NULL && *home != '\0') { /* If no override is set use $HOME/. */ dotPath = sdscatprintf(sdsempty(), "%s/%s", home, dotfilename); } +#endif } return dotPath; } @@ -256,9 +267,9 @@ static sds cliVersion(void) { version = sdscatprintf(sdsempty(), "%s", REDIS_VERSION); /* Add git commit and working tree status when available */ - if (strtoll(redisGitSHA1(),NULL,16)) { + if (strtoll(redisGitSHA1(), NULL, 16)) { version = sdscatprintf(version, " (git:%s", redisGitSHA1()); - if (strtoll(redisGitDirty(),NULL,10)) + if (strtoll(redisGitDirty(), NULL, 10)) version = sdscatprintf(version, "-dirty"); version = sdscat(version, ")"); } @@ -266,18 +277,18 @@ static sds cliVersion(void) { } static void cliInitHelp(void) { - int commandslen = sizeof(commandHelp)/sizeof(struct commandHelp); - int groupslen = sizeof(commandGroups)/sizeof(char*); + int commandslen = sizeof(commandHelp) / sizeof(struct commandHelp); + int groupslen = sizeof(commandGroups) / sizeof(char*); int i, len, pos = 0; helpEntry tmp; - helpEntriesLen = len = commandslen+groupslen; + helpEntriesLen = len = commandslen + groupslen; helpEntries = zmalloc(sizeof(helpEntry)*len); for (i = 0; i < groupslen; i++) { tmp.argc = 1; tmp.argv = zmalloc(sizeof(sds)); - tmp.argv[0] = sdscatprintf(sdsempty(),"@%s",commandGroups[i]); + tmp.argv[0] = sdscatprintf(sdsempty(), "@%s", commandGroups[i]); tmp.full = tmp.argv[0]; tmp.type = CLI_HELP_GROUP; tmp.org = NULL; @@ -285,7 +296,7 @@ static void cliInitHelp(void) { } for (i = 0; i < commandslen; i++) { - tmp.argv = sdssplitargs(commandHelp[i].name,&tmp.argc); + tmp.argv = sdssplitargs(commandHelp[i].name, &tmp.argc); tmp.full = sdsnew(commandHelp[i].name); tmp.type = CLI_HELP_COMMAND; tmp.org = &commandHelp[i]; @@ -302,7 +313,7 @@ static void cliIntegrateHelp(void) { if (cliConnect(0) == REDIS_ERR) return; redisReply *reply = redisCommand(context, "COMMAND"); - if(reply == NULL || reply->type != REDIS_REPLY_ARRAY) return; + if (reply == NULL || reply->type != REDIS_REPLY_ARRAY) return; /* Scan the array reported by COMMAND and fill only the entries that * don't already match what we have. */ @@ -316,15 +327,15 @@ static void cliIntegrateHelp(void) { int i; for (i = 0; i < helpEntriesLen; i++) { - helpEntry *he = helpEntries+i; - if (!strcasecmp(he->argv[0],cmdname)) + helpEntry *he = helpEntries + i; + if (!strcasecmp(he->argv[0], cmdname)) break; } if (i != helpEntriesLen) continue; helpEntriesLen++; - helpEntries = zrealloc(helpEntries,sizeof(helpEntry)*helpEntriesLen); - helpEntry *new = helpEntries+(helpEntriesLen-1); + helpEntries = zrealloc(helpEntries, sizeof(helpEntry)*helpEntriesLen); + helpEntry *new = helpEntries + (helpEntriesLen - 1); new->argc = 1; new->argv = zmalloc(sizeof(sds)); @@ -338,12 +349,12 @@ static void cliIntegrateHelp(void) { ch->params = sdsempty(); int args = llabs(entry->element[1]->integer); if (entry->element[3]->integer == 1) { - ch->params = sdscat(ch->params,"key "); + ch->params = sdscat(ch->params, "key "); args--; } - while(args--) ch->params = sdscat(ch->params,"arg "); + while (args--) ch->params = sdscat(ch->params, "arg "); if (entry->element[1]->integer < 0) - ch->params = sdscat(ch->params,"...options..."); + ch->params = sdscat(ch->params, "...options..."); ch->summary = "Help not available"; ch->group = 0; ch->since = "not known"; @@ -392,10 +403,11 @@ static void cliOutputHelp(int argc, char **argv) { if (argc == 0) { cliOutputGenericHelp(); return; - } else if (argc > 0 && argv[0][0] == '@') { - len = sizeof(commandGroups)/sizeof(char*); + } + else if (argc > 0 && argv[0][0] == '@') { + len = sizeof(commandGroups) / sizeof(char*); for (i = 0; i < len; i++) { - if (strcasecmp(argv[0]+1,commandGroups[i]) == 0) { + if (strcasecmp(argv[0] + 1, commandGroups[i]) == 0) { group = i; break; } @@ -412,15 +424,16 @@ static void cliOutputHelp(int argc, char **argv) { /* Compare all arguments */ if (argc == entry->argc) { for (j = 0; j < argc; j++) { - if (strcasecmp(argv[j],entry->argv[j]) != 0) break; + if (strcasecmp(argv[j], entry->argv[j]) != 0) break; } if (j == argc) { - cliOutputCommandHelp(help,1); + cliOutputCommandHelp(help, 1); } } - } else { + } + else { if (group == help->group) { - cliOutputCommandHelp(help,0); + cliOutputCommandHelp(help, 0); } } } @@ -435,22 +448,23 @@ static void completionCallback(const char *buf, linenoiseCompletions *lc) { size_t matchlen; sds tmp; - if (strncasecmp(buf,"help ",5) == 0) { + if (strncasecmp(buf, "help ", 5) == 0) { startpos = 5; while (isspace(buf[startpos])) startpos++; mask = CLI_HELP_COMMAND | CLI_HELP_GROUP; - } else { + } + else { mask = CLI_HELP_COMMAND; } for (i = 0; i < helpEntriesLen; i++) { if (!(helpEntries[i].type & mask)) continue; - matchlen = strlen(buf+startpos); - if (strncasecmp(buf+startpos,helpEntries[i].full,matchlen) == 0) { - tmp = sdsnewlen(buf,startpos); - tmp = sdscat(tmp,helpEntries[i].full); - linenoiseAddCompletion(lc,tmp); + matchlen = strlen(buf + startpos); + if (strncasecmp(buf + startpos, helpEntries[i].full, matchlen) == 0) { + tmp = sdsnewlen(buf, startpos); + tmp = sdscat(tmp, helpEntries[i].full); + linenoiseAddCompletion(lc, tmp); sdsfree(tmp); } } @@ -460,20 +474,20 @@ static void completionCallback(const char *buf, linenoiseCompletions *lc) { static char *hintsCallback(const char *buf, int *color, int *bold) { if (!pref.hints) return NULL; - int i, argc, buflen = (int)strlen(buf); WIN_PORT_FIX /* cast int */ - sds *argv = sdssplitargs(buf,&argc); - int endspace = buflen && isspace(buf[buflen-1]); + int i, argc, buflen = (int) strlen(buf); WIN_PORT_FIX /* cast int */ + sds *argv = sdssplitargs(buf, &argc); + int endspace = buflen && isspace(buf[buflen - 1]); /* Check if the argument list is empty and return ASAP. */ if (argc == 0) { - sdsfreesplitres(argv,argc); + sdsfreesplitres(argv, argc); return NULL; } for (i = 0; i < helpEntriesLen; i++) { if (!(helpEntries[i].type & CLI_HELP_COMMAND)) continue; - if (strcasecmp(argv[0],helpEntries[i].full) == 0) + if (strcasecmp(argv[0], helpEntries[i].full) == 0) { *color = 90; *bold = 0; @@ -481,26 +495,26 @@ static char *hintsCallback(const char *buf, int *color, int *bold) { /* Remove arguments from the returned hint to show only the * ones the user did not yet typed. */ - int toremove = argc-1; - while(toremove > 0 && sdslen(hint)) { + int toremove = argc - 1; + while (toremove > 0 && sdslen(hint)) { if (hint[0] == '[') break; if (hint[0] == ' ') toremove--; - sdsrange(hint,1,-1); + sdsrange(hint, 1, -1); } /* Add an initial space if needed. */ if (!endspace) { - sds newhint = sdsnewlen(" ",1); - newhint = sdscatsds(newhint,hint); + sds newhint = sdsnewlen(" ", 1); + newhint = sdscatsds(newhint, hint); sdsfree(hint); hint = newhint; } - sdsfreesplitres(argv,argc); + sdsfreesplitres(argv, argc); return hint; } } - sdsfreesplitres(argv,argc); + sdsfreesplitres(argv, argc); return NULL; } @@ -512,12 +526,12 @@ static void freeHintsCallback(void *ptr) { * Networking / parsing *--------------------------------------------------------------------------- */ -/* Send AUTH command to the server */ + /* Send AUTH command to the server */ static int cliAuth(void) { redisReply *reply; if (config.auth == NULL) return REDIS_OK; - reply = redisCommand(context,"AUTH %s",config.auth); + reply = redisCommand(context, "AUTH %s", config.auth); if (reply != NULL) { freeReplyObject(reply); return REDIS_OK; @@ -530,7 +544,7 @@ static int cliSelect(void) { redisReply *reply; if (config.dbnum == 0) return REDIS_OK; - reply = redisCommand(context,"SELECT %d",config.dbnum); + reply = redisCommand(context, "SELECT %d", config.dbnum); if (reply != NULL) { int result = REDIS_OK; if (reply->type == REDIS_REPLY_ERROR) result = REDIS_ERR; @@ -549,17 +563,18 @@ static int cliConnect(int force) { } if (config.hostsocket == NULL) { - context = redisConnect(config.hostip,config.hostport); - } else { + context = redisConnect(config.hostip, config.hostport); + } + else { context = redisConnectUnix(config.hostsocket); } if (context->err) { - fprintf(stderr,"Could not connect to Redis at "); + fprintf(stderr, "Could not connect to Redis at "); if (config.hostsocket == NULL) - fprintf(stderr,"%s:%d: %s\n",config.hostip,config.hostport,context->errstr); + fprintf(stderr, "%s:%d: %s\n", config.hostip, config.hostport, context->errstr); else - fprintf(stderr,"%s: %s\n",config.hostsocket,context->errstr); + fprintf(stderr, "%s: %s\n", config.hostsocket, context->errstr); redisFree(context); context = NULL; return REDIS_ERR; @@ -582,35 +597,36 @@ static int cliConnect(int force) { static void cliPrintContextError(void) { if (context == NULL) return; - fprintf(stderr,"Error: %s\n",context->errstr); + fprintf(stderr, "Error: %s\n", context->errstr); } static sds cliFormatReplyTTY(redisReply *r, char *prefix) { sds out = sdsempty(); switch (r->type) { case REDIS_REPLY_ERROR: - out = sdscatprintf(out,"(error) %s\n", r->str); - break; + out = sdscatprintf(out, "(error) %s\n", r->str); + break; case REDIS_REPLY_STATUS: - out = sdscat(out,r->str); - out = sdscat(out,"\n"); - break; + out = sdscat(out, r->str); + out = sdscat(out, "\n"); + break; case REDIS_REPLY_INTEGER: - out = sdscatprintf(out,"(integer) %lld\n",r->integer); - break; + out = sdscatprintf(out, "(integer) %lld\n", r->integer); + break; case REDIS_REPLY_STRING: /* If you are producing output for the standard output we want * a more interesting output with quoted characters and so forth */ - out = sdscatrepr(out,r->str,r->len); - out = sdscat(out,"\n"); - break; + out = sdscatrepr(out, r->str, r->len); + out = sdscat(out, "\n"); + break; case REDIS_REPLY_NIL: - out = sdscat(out,"(nil)\n"); - break; + out = sdscat(out, "(nil)\n"); + break; case REDIS_REPLY_ARRAY: if (r->elements == 0) { - out = sdscat(out,"(empty list or set)\n"); - } else { + out = sdscat(out, "(empty list or set)\n"); + } + else { unsigned int i, idxlen = 0; char _prefixlen[16]; char _prefixfmt[16]; @@ -618,35 +634,35 @@ static sds cliFormatReplyTTY(redisReply *r, char *prefix) { sds tmp; /* Calculate chars needed to represent the largest index */ - i = (unsigned int)r->elements; + i = (unsigned int) r->elements; do { idxlen++; i /= 10; - } while(i); + } while (i); /* Prefix for nested multi bulks should grow with idxlen+2 spaces */ - memset(_prefixlen,' ',idxlen+2); - _prefixlen[idxlen+2] = '\0'; - _prefix = sdscat(sdsnew(prefix),_prefixlen); + memset(_prefixlen, ' ', idxlen + 2); + _prefixlen[idxlen + 2] = '\0'; + _prefix = sdscat(sdsnew(prefix), _prefixlen); /* Setup prefix format for every entry */ - snprintf(_prefixfmt,sizeof(_prefixfmt),"%%s%%%ud) ",idxlen); + snprintf(_prefixfmt, sizeof(_prefixfmt), "%%s%%%ud) ", idxlen); for (i = 0; i < r->elements; i++) { /* Don't use the prefix for the first element, as the parent * caller already prepended the index number. */ - out = sdscatprintf(out,_prefixfmt,i == 0 ? "" : prefix,i+1); + out = sdscatprintf(out, _prefixfmt, i == 0 ? "" : prefix, i + 1); /* Format the multi bulk entry */ - tmp = cliFormatReplyTTY(r->element[i],_prefix); - out = sdscatlen(out,tmp,sdslen(tmp)); + tmp = cliFormatReplyTTY(r->element[i], _prefix); + out = sdscatlen(out, tmp, sdslen(tmp)); sdsfree(tmp); } sdsfree(_prefix); } - break; + break; default: - fprintf(stderr,"Unknown reply type: %d\n", r->type); + fprintf(stderr, "Unknown reply type: %d\n", r->type); exit(1); } return out; @@ -654,27 +670,27 @@ static sds cliFormatReplyTTY(redisReply *r, char *prefix) { int isColorTerm(void) { char *t = getenv("TERM"); - return t != NULL && strstr(t,"xterm") != NULL; + return t != NULL && strstr(t, "xterm") != NULL; } /* Helpe function for sdsCatColorizedLdbReply() appending colorize strings * to an SDS string. */ sds sdscatcolor(sds o, char *s, size_t len, char *color) { - if (!isColorTerm()) return sdscatlen(o,s,len); + if (!isColorTerm()) return sdscatlen(o, s, len); - int bold = strstr(color,"bold") != NULL; + int bold = strstr(color, "bold") != NULL; int ccode = 37; /* Defaults to white. */ - if (strstr(color,"red")) ccode = 31; - else if (strstr(color,"green")) ccode = 32; - else if (strstr(color,"yellow")) ccode = 33; - else if (strstr(color,"blue")) ccode = 34; - else if (strstr(color,"magenta")) ccode = 35; - else if (strstr(color,"cyan")) ccode = 36; - else if (strstr(color,"white")) ccode = 37; + if (strstr(color, "red")) ccode = 31; + else if (strstr(color, "green")) ccode = 32; + else if (strstr(color, "yellow")) ccode = 33; + else if (strstr(color, "blue")) ccode = 34; + else if (strstr(color, "magenta")) ccode = 35; + else if (strstr(color, "cyan")) ccode = 36; + else if (strstr(color, "white")) ccode = 37; - o = sdscatfmt(o,"\033[%i;%i;49m",bold,ccode); - o = sdscatlen(o,s,len); - o = sdscat(o,"\033[0m"); + o = sdscatfmt(o, "\033[%i;%i;49m", bold, ccode); + o = sdscatlen(o, s, len); + o = sdscat(o, "\033[0m"); return o; } @@ -683,17 +699,17 @@ sds sdscatcolor(sds o, char *s, size_t len, char *color) { sds sdsCatColorizedLdbReply(sds o, char *s, size_t len) { char *color = "white"; - if (strstr(s,"")) color = "bold"; - if (strstr(s,"")) color = "green"; - if (strstr(s,"")) color = "cyan"; - if (strstr(s,"")) color = "red"; - if (strstr(s,"")) color = "bold"; - if (strstr(s,"") || strstr(s,"")) color = "magenta"; + if (strstr(s, "")) color = "bold"; + if (strstr(s, "")) color = "green"; + if (strstr(s, "")) color = "cyan"; + if (strstr(s, "")) color = "red"; + if (strstr(s, "")) color = "bold"; + if (strstr(s, "") || strstr(s, "")) color = "magenta"; if (len > 4 && isdigit(s[3])) { if (s[1] == '>') color = "yellow"; /* Current line. */ else if (s[2] == '#') color = "bold"; /* Break point. */ } - return sdscatcolor(o,s,len,color); + return sdscatcolor(o, s, len, color); } static sds cliFormatReplyRaw(redisReply *r) { @@ -705,8 +721,8 @@ static sds cliFormatReplyRaw(redisReply *r) { /* Nothing... */ break; case REDIS_REPLY_ERROR: - out = sdscatlen(out,r->str,r->len); - out = sdscatlen(out,"\n",1); + out = sdscatlen(out, r->str, r->len); + out = sdscatlen(out, "\n", 1); break; case REDIS_REPLY_STATUS: case REDIS_REPLY_STRING: @@ -715,33 +731,35 @@ static sds cliFormatReplyRaw(redisReply *r) { * strings. We colorize the output for more fun if this * is a debugging session. */ - /* Detect the end of a debugging session. */ - if (strstr(r->str,"") == r->str) { + /* Detect the end of a debugging session. */ + if (strstr(r->str, "") == r->str) { config.enable_ldb_on_eval = 0; config.eval_ldb = 0; config.eval_ldb_end = 1; /* Signal the caller session ended. */ config.output = OUTPUT_STANDARD; cliRefreshPrompt(); - } else { - out = sdsCatColorizedLdbReply(out,r->str,r->len); } - } else { - out = sdscatlen(out,r->str,r->len); + else { + out = sdsCatColorizedLdbReply(out, r->str, r->len); + } + } + else { + out = sdscatlen(out, r->str, r->len); } break; case REDIS_REPLY_INTEGER: - out = sdscatprintf(out,"%lld",r->integer); + out = sdscatprintf(out, "%lld", r->integer); break; case REDIS_REPLY_ARRAY: for (i = 0; i < r->elements; i++) { - if (i > 0) out = sdscat(out,config.mb_delim); + if (i > 0) out = sdscat(out, config.mb_delim); tmp = cliFormatReplyRaw(r->element[i]); - out = sdscatlen(out,tmp,sdslen(tmp)); + out = sdscatlen(out, tmp, sdslen(tmp)); sdsfree(tmp); } break; default: - fprintf(stderr,"Unknown reply type: %d\n", r->type); + fprintf(stderr, "Unknown reply type: %d\n", r->type); exit(1); } return out; @@ -753,31 +771,31 @@ static sds cliFormatReplyCSV(redisReply *r) { sds out = sdsempty(); switch (r->type) { case REDIS_REPLY_ERROR: - out = sdscat(out,"ERROR,"); - out = sdscatrepr(out,r->str,strlen(r->str)); - break; + out = sdscat(out, "ERROR,"); + out = sdscatrepr(out, r->str, strlen(r->str)); + break; case REDIS_REPLY_STATUS: - out = sdscatrepr(out,r->str,r->len); - break; + out = sdscatrepr(out, r->str, r->len); + break; case REDIS_REPLY_INTEGER: - out = sdscatprintf(out,"%lld",r->integer); - break; + out = sdscatprintf(out, "%lld", r->integer); + break; case REDIS_REPLY_STRING: - out = sdscatrepr(out,r->str,r->len); - break; + out = sdscatrepr(out, r->str, r->len); + break; case REDIS_REPLY_NIL: - out = sdscat(out,"NIL"); - break; + out = sdscat(out, "NIL"); + break; case REDIS_REPLY_ARRAY: for (i = 0; i < r->elements; i++) { sds tmp = cliFormatReplyCSV(r->element[i]); - out = sdscatlen(out,tmp,sdslen(tmp)); - if (i != r->elements-1) out = sdscat(out,","); + out = sdscatlen(out, tmp, sdslen(tmp)); + if (i != r->elements - 1) out = sdscat(out, ","); sdsfree(tmp); } - break; + break; default: - fprintf(stderr,"Unknown reply type: %d\n", r->type); + fprintf(stderr, "Unknown reply type: %d\n", r->type); exit(1); } return out; @@ -789,7 +807,7 @@ static int cliReadReply(int output_raw_strings) { sds out = NULL; int output = 1; - if (redisGetReply(context,&_reply) != REDIS_OK) { + if (redisGetReply(context, &_reply) != REDIS_OK) { if (config.shutdown) { redisFree(context); context = NULL; @@ -808,14 +826,14 @@ static int cliReadReply(int output_raw_strings) { return REDIS_ERR; /* avoid compiler warning */ } - reply = (redisReply*)_reply; + reply = (redisReply*) _reply; config.last_cmd_type = reply->type; /* Check if we need to connect to a different node and reissue the * request. */ if (config.cluster_mode && reply->type == REDIS_REPLY_ERROR && - (!strncmp(reply->str,"MOVED",5) || !strcmp(reply->str,"ASK"))) + (!strncmp(reply->str, "MOVED", 5) || !strcmp(reply->str, "ASK"))) { char *p = reply->str, *s; int slot; @@ -826,15 +844,15 @@ static int cliReadReply(int output_raw_strings) { * [S] for pointer 's' * [P] for pointer 'p' */ - s = strchr(p,' '); /* MOVED[S]3999 127.0.0.1:6381 */ - p = strchr(s+1,' '); /* MOVED[S]3999[P]127.0.0.1:6381 */ + s = strchr(p, ' '); /* MOVED[S]3999 127.0.0.1:6381 */ + p = strchr(s + 1, ' '); /* MOVED[S]3999[P]127.0.0.1:6381 */ *p = '\0'; - slot = atoi(s+1); - s = strrchr(p+1,':'); /* MOVED 3999[P]127.0.0.1[S]6381 */ + slot = atoi(s + 1); + s = strrchr(p + 1, ':'); /* MOVED 3999[P]127.0.0.1[S]6381 */ *s = '\0'; sdsfree(config.hostip); - config.hostip = sdsnew(p+1); - config.hostport = atoi(s+1); + config.hostip = sdsnew(p + 1); + config.hostport = atoi(s + 1); if (config.interactive) printf("-> Redirected to slot [%d] located at %s:%d\n", slot, config.hostip, config.hostport); @@ -845,22 +863,25 @@ static int cliReadReply(int output_raw_strings) { if (output) { if (output_raw_strings) { out = cliFormatReplyRaw(reply); - } else { + } + else { if (config.output == OUTPUT_RAW) { out = cliFormatReplyRaw(reply); - out = sdscat(out,"\n"); - } else if (config.output == OUTPUT_STANDARD) { - out = cliFormatReplyTTY(reply,""); - } else if (config.output == OUTPUT_CSV) { + out = sdscat(out, "\n"); + } + else if (config.output == OUTPUT_STANDARD) { + out = cliFormatReplyTTY(reply, ""); + } + else if (config.output == OUTPUT_CSV) { out = cliFormatReplyCSV(reply); - out = sdscat(out,"\n"); + out = sdscat(out, "\n"); } } #ifdef _WIN32 /* if size is too large, fwrite fails. Use fprintf */ fprintf(stdout, "%s", out); #else - fwrite(out,sdslen(out),1,stdout); + fwrite(out, sdslen(out), 1, stdout); #endif sdsfree(out); } @@ -874,7 +895,7 @@ static int cliSendCommand(int argc, char **argv, int repeat) { int j, output_raw; if (!config.eval_ldb && /* In debugging mode, let's pass "help" to Redis. */ - (!strcasecmp(command,"help") || !strcasecmp(command,"?"))) { + (!strcasecmp(command, "help") || !strcasecmp(command, "?"))) { cliOutputHelp(--argc, ++argv); return REDIS_OK; } @@ -882,57 +903,58 @@ static int cliSendCommand(int argc, char **argv, int repeat) { if (context == NULL) return REDIS_ERR; output_raw = 0; - if (!strcasecmp(command,"info") || - (argc >= 2 && !strcasecmp(command,"debug") && - !strcasecmp(argv[1],"htstats")) || - (argc >= 2 && !strcasecmp(command,"memory") && - (!strcasecmp(argv[1],"malloc-stats") || - !strcasecmp(argv[1],"doctor"))) || - (argc == 2 && !strcasecmp(command,"cluster") && - (!strcasecmp(argv[1],"nodes") || - !strcasecmp(argv[1],"info"))) || - (argc == 2 && !strcasecmp(command,"client") && - !strcasecmp(argv[1],"list")) || - (argc == 3 && !strcasecmp(command,"latency") && - !strcasecmp(argv[1],"graph")) || - (argc == 2 && !strcasecmp(command,"latency") && - !strcasecmp(argv[1],"doctor"))) + if (!strcasecmp(command, "info") || + (argc >= 2 && !strcasecmp(command, "debug") && + !strcasecmp(argv[1], "htstats")) || + (argc >= 2 && !strcasecmp(command, "memory") && + (!strcasecmp(argv[1], "malloc-stats") || + !strcasecmp(argv[1], "doctor"))) || + (argc == 2 && !strcasecmp(command, "cluster") && + (!strcasecmp(argv[1], "nodes") || + !strcasecmp(argv[1], "info"))) || + (argc == 2 && !strcasecmp(command, "client") && + !strcasecmp(argv[1], "list")) || + (argc == 3 && !strcasecmp(command, "latency") && + !strcasecmp(argv[1], "graph")) || + (argc == 2 && !strcasecmp(command, "latency") && + !strcasecmp(argv[1], "doctor"))) { output_raw = 1; } - if (!strcasecmp(command,"shutdown")) config.shutdown = 1; - if (!strcasecmp(command,"monitor")) config.monitor_mode = 1; - if (!strcasecmp(command,"subscribe") || - !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1; - if (!strcasecmp(command,"sync") || - !strcasecmp(command,"psync")) config.slave_mode = 1; + if (!strcasecmp(command, "shutdown")) config.shutdown = 1; + if (!strcasecmp(command, "monitor")) config.monitor_mode = 1; + if (!strcasecmp(command, "subscribe") || + !strcasecmp(command, "psubscribe")) config.pubsub_mode = 1; + if (!strcasecmp(command, "sync") || + !strcasecmp(command, "psync")) config.slave_mode = 1; /* When the user manually calls SCRIPT DEBUG, setup the activation of * debugging mode on the next eval if needed. */ - if (argc == 3 && !strcasecmp(argv[0],"script") && - !strcasecmp(argv[1],"debug")) + if (argc == 3 && !strcasecmp(argv[0], "script") && + !strcasecmp(argv[1], "debug")) { - if (!strcasecmp(argv[2],"yes") || !strcasecmp(argv[2],"sync")) { + if (!strcasecmp(argv[2], "yes") || !strcasecmp(argv[2], "sync")) { config.enable_ldb_on_eval = 1; - } else { + } + else { config.enable_ldb_on_eval = 0; } } /* Actually activate LDB on EVAL if needed. */ - if (!strcasecmp(command,"eval") && config.enable_ldb_on_eval) { + if (!strcasecmp(command, "eval") && config.enable_ldb_on_eval) { config.eval_ldb = 1; config.output = OUTPUT_RAW; } /* Setup argument length */ - argvlen = zmalloc(argc*sizeof(size_t)); + argvlen = zmalloc(argc * sizeof(size_t)); for (j = 0; j < argc; j++) argvlen[j] = sdslen(argv[j]); - while(repeat--) { - redisAppendCommandArgv(context,argc,(const char**)argv,argvlen); + while (repeat--) { + redisAppendCommandArgv(context, argc, (const char**) argv, argvlen); while (config.monitor_mode) { if (cliReadReply(output_raw) != REDIS_OK) exit(1); fflush(stdout); @@ -957,12 +979,14 @@ static int cliSendCommand(int argc, char **argv, int repeat) { if (cliReadReply(output_raw) != REDIS_OK) { zfree(argvlen); return REDIS_ERR; - } else { + } + else { /* Store database number when SELECT was successfully executed. */ - if (!strcasecmp(command,"select") && argc == 2 && config.last_cmd_type != REDIS_REPLY_ERROR) { + if (!strcasecmp(command, "select") && argc == 2 && config.last_cmd_type != REDIS_REPLY_ERROR) { config.dbnum = atoi(argv[1]); cliRefreshPrompt(); - } else if (!strcasecmp(command,"auth") && argc == 2) { + } + else if (!strcasecmp(command, "auth") && argc == 2) { cliSelect(); } } @@ -981,25 +1005,26 @@ static redisReply *reconnectingRedisCommand(redisContext *c, const char *fmt, .. va_list ap; assert(!c->err); - while(reply == NULL) { + while (reply == NULL) { while (c->err & (REDIS_ERR_IO | REDIS_ERR_EOF)) { printf("\r\x1b[0K"); /* Cursor to left edge + clear line. */ printf("Reconnecting... %d\r", ++tries); fflush(stdout); redisFree(c); - c = redisConnect(config.hostip,config.hostport); + c = redisConnect(config.hostip, config.hostport); usleep(1000000); } - va_start(ap,fmt); - reply = redisvCommand(c,fmt,ap); + va_start(ap, fmt); + reply = redisvCommand(c, fmt, ap); va_end(ap); if (c->err && !(c->err & (REDIS_ERR_IO | REDIS_ERR_EOF))) { fprintf(stderr, "Error: %s\n", c->errstr); exit(1); - } else if (tries > 0) { + } + else if (tries > 0) { printf("\r\x1b[0K"); /* Cursor to left edge + clear line. */ } } @@ -1016,95 +1041,129 @@ static int parseOptions(int argc, char **argv) { int i; for (i = 1; i < argc; i++) { - int lastarg = i==argc-1; + int lastarg = i == argc - 1; - if (!strcmp(argv[i],"-h") && !lastarg) { + if (!strcmp(argv[i], "-h") && !lastarg) { sdsfree(config.hostip); config.hostip = sdsnew(argv[++i]); - } else if (!strcmp(argv[i],"-h") && lastarg) { + } + else if (!strcmp(argv[i], "-h") && lastarg) { usage(); - } else if (!strcmp(argv[i],"--help")) { + } + else if (!strcmp(argv[i], "--help")) { usage(); - } else if (!strcmp(argv[i],"-x")) { + } + else if (!strcmp(argv[i], "-x")) { config.stdinarg = 1; - } else if (!strcmp(argv[i],"-p") && !lastarg) { + } + else if (!strcmp(argv[i], "-p") && !lastarg) { config.hostport = atoi(argv[++i]); - } else if (!strcmp(argv[i],"-s") && !lastarg) { + } + else if (!strcmp(argv[i], "-s") && !lastarg) { config.hostsocket = argv[++i]; - } else if (!strcmp(argv[i],"-r") && !lastarg) { - config.repeat = (PORT_LONG) strtol(argv[++i],NULL,10); - } else if (!strcmp(argv[i],"-i") && !lastarg) { + } + else if (!strcmp(argv[i], "-r") && !lastarg) { + config.repeat = (PORT_LONG) strtol(argv[++i], NULL, 10); + } + else if (!strcmp(argv[i], "-i") && !lastarg) { double seconds = atof(argv[++i]); - config.interval = (PORT_LONG) (seconds*1000000); - } else if (!strcmp(argv[i],"-n") && !lastarg) { + config.interval = (PORT_LONG) (seconds * 1000000); + } + else if (!strcmp(argv[i], "-n") && !lastarg) { config.dbnum = atoi(argv[++i]); - } else if (!strcmp(argv[i],"-a") && !lastarg) { + } + else if (!strcmp(argv[i], "-a") && !lastarg) { config.auth = argv[++i]; - } else if (!strcmp(argv[i],"--raw")) { + } + else if (!strcmp(argv[i], "--raw")) { config.output = OUTPUT_RAW; - } else if (!strcmp(argv[i],"--no-raw")) { + } + else if (!strcmp(argv[i], "--no-raw")) { config.output = OUTPUT_STANDARD; - } else if (!strcmp(argv[i],"--csv")) { + } + else if (!strcmp(argv[i], "--csv")) { config.output = OUTPUT_CSV; - } else if (!strcmp(argv[i],"--latency")) { + } + else if (!strcmp(argv[i], "--latency")) { config.latency_mode = 1; - } else if (!strcmp(argv[i],"--latency-dist")) { + } + else if (!strcmp(argv[i], "--latency-dist")) { config.latency_dist_mode = 1; - } else if (!strcmp(argv[i],"--mono")) { + } + else if (!strcmp(argv[i], "--mono")) { spectrum_palette = spectrum_palette_mono; spectrum_palette_size = spectrum_palette_mono_size; - } else if (!strcmp(argv[i],"--latency-history")) { + } + else if (!strcmp(argv[i], "--latency-history")) { config.latency_mode = 1; config.latency_history = 1; - } else if (!strcmp(argv[i],"--lru-test") && !lastarg) { + } + else if (!strcmp(argv[i], "--lru-test") && !lastarg) { config.lru_test_mode = 1; - config.lru_test_sample_size = strtoll(argv[++i],NULL,10); - } else if (!strcmp(argv[i],"--slave")) { + config.lru_test_sample_size = strtoll(argv[++i], NULL, 10); + } + else if (!strcmp(argv[i], "--slave")) { config.slave_mode = 1; - } else if (!strcmp(argv[i],"--stat")) { + } + else if (!strcmp(argv[i], "--stat")) { config.stat_mode = 1; - } else if (!strcmp(argv[i],"--scan")) { + } + else if (!strcmp(argv[i], "--scan")) { config.scan_mode = 1; - } else if (!strcmp(argv[i],"--pattern") && !lastarg) { + } + else if (!strcmp(argv[i], "--pattern") && !lastarg) { config.pattern = argv[++i]; - } else if (!strcmp(argv[i],"--intrinsic-latency") && !lastarg) { + } + else if (!strcmp(argv[i], "--intrinsic-latency") && !lastarg) { config.intrinsic_latency_mode = 1; config.intrinsic_latency_duration = atoi(argv[++i]); - } else if (!strcmp(argv[i],"--rdb") && !lastarg) { + } + else if (!strcmp(argv[i], "--rdb") && !lastarg) { config.getrdb_mode = 1; config.rdb_filename = argv[++i]; - } else if (!strcmp(argv[i],"--pipe")) { + } + else if (!strcmp(argv[i], "--pipe")) { config.pipe_mode = 1; - } else if (!strcmp(argv[i],"--pipe-timeout") && !lastarg) { + } + else if (!strcmp(argv[i], "--pipe-timeout") && !lastarg) { config.pipe_timeout = atoi(argv[++i]); - } else if (!strcmp(argv[i],"--bigkeys")) { + } + else if (!strcmp(argv[i], "--bigkeys")) { config.bigkeys = 1; - } else if (!strcmp(argv[i],"--eval") && !lastarg) { + } + else if (!strcmp(argv[i], "--eval") && !lastarg) { config.eval = argv[++i]; - } else if (!strcmp(argv[i],"--ldb")) { + } + else if (!strcmp(argv[i], "--ldb")) { config.eval_ldb = 1; config.output = OUTPUT_RAW; - } else if (!strcmp(argv[i],"--ldb-sync-mode")) { + } + else if (!strcmp(argv[i], "--ldb-sync-mode")) { config.eval_ldb = 1; config.eval_ldb_sync = 1; config.output = OUTPUT_RAW; - } else if (!strcmp(argv[i],"-c")) { + } + else if (!strcmp(argv[i], "-c")) { config.cluster_mode = 1; - } else if (!strcmp(argv[i],"-d") && !lastarg) { + } + else if (!strcmp(argv[i], "-d") && !lastarg) { sdsfree(config.mb_delim); config.mb_delim = sdsnew(argv[++i]); - } else if (!strcmp(argv[i],"-v") || !strcmp(argv[i], "--version")) { + } + else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--version")) { sds version = cliVersion(); printf("redis-cli %s\n", version); sdsfree(version); exit(0); - } else { + } + else { if (argv[i][0] == '-') { fprintf(stderr, "Unrecognized option or bad number of args for: '%s'\n", argv[i]); exit(1); - } else { + } + else { /* Likely the command name, stop here. */ break; } @@ -1113,8 +1172,8 @@ static int parseOptions(int argc, char **argv) { /* --ldb requires --eval. */ if (config.eval_ldb && config.eval == NULL) { - fprintf(stderr,"Options --ldb and --ldb-sync-mode require --eval.\n"); - fprintf(stderr,"Try %s --help for more information.\n", argv[0]); + fprintf(stderr, "Options --ldb and --ldb-sync-mode require --eval.\n"); + fprintf(stderr, "Try %s --help for more information.\n", argv[0]); exit(1); } return i; @@ -1124,15 +1183,15 @@ static sds readArgFromStdin(void) { char buf[1024]; sds arg = sdsempty(); - while(1) { - int nread = (int)read(fileno(stdin),buf,1024); WIN_PORT_FIX /* cast (int) */ + while (1) { + int nread = (int) read(fileno(stdin), buf, 1024); WIN_PORT_FIX /* cast (int) */ - if (nread == 0) break; - else if (nread == -1) { - perror("Reading from standard input"); - exit(1); - } - arg = sdscatlen(arg,buf,nread); + if (nread == 0) break; + else if (nread == -1) { + perror("Reading from standard input"); + exit(1); + } + arg = sdscatlen(arg, buf, nread); } return arg; } @@ -1140,70 +1199,70 @@ static sds readArgFromStdin(void) { static void usage(void) { sds version = cliVersion(); fprintf(stderr, -"redis-cli %s\n" -"\n" -"Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n" -" -h Server hostname (default: 127.0.0.1).\n" -" -p Server port (default: 6379).\n" -" -s Server socket (overrides hostname and port).\n" -" -a Password to use when connecting to the server.\n" -" -r Execute specified command N times.\n" -" -i When -r is used, waits seconds per command.\n" -" It is possible to specify sub-second times like -i 0.1.\n" -" -n Database number.\n" -" -x Read last argument from STDIN.\n" -" -d Multi-bulk delimiter in for raw formatting (default: \\n).\n" -" -c Enable cluster mode (follow -ASK and -MOVED redirections).\n" -" --raw Use raw formatting for replies (default when STDOUT is\n" -" not a tty).\n" -" --no-raw Force formatted output even when STDOUT is not a tty.\n" -" --csv Output in CSV format.\n" -" --stat Print rolling stats about server: mem, clients, ...\n" -" --latency Enter a special mode continuously sampling latency.\n" -" If you use this mode in an interactive session it runs\n" -" forever displaying real-time stats. Otherwise if --raw or\n" -" --csv is specified, or if you redirect the output to a non\n" -" TTY, it samples the latency for 1 second (you can use\n" -" -i to change the interval), then produces a single output\n" -" and exits.\n" -" --latency-history Like --latency but tracking latency changes over time.\n" -" Default time interval is 15 sec. Change it using -i.\n" -" --latency-dist Shows latency as a spectrum, requires xterm 256 colors.\n" -" Default time interval is 1 sec. Change it using -i.\n" -" --lru-test Simulate a cache workload with an 80-20 distribution.\n" -" --slave Simulate a slave showing commands received from the master.\n" -" --rdb Transfer an RDB dump from remote server to local file.\n" -" --pipe Transfer raw Redis protocol from stdin to server.\n" -" --pipe-timeout In --pipe mode, abort with error if after sending all data.\n" -" no reply is received within seconds.\n" -" Default timeout: %d. Use 0 to wait forever.\n" -" --bigkeys Sample Redis keys looking for big keys.\n" -" --scan List all keys using the SCAN command.\n" -" --pattern Useful with --scan to specify a SCAN pattern.\n" -" --intrinsic-latency Run a test to measure intrinsic system latency.\n" -" The test will run for the specified amount of seconds.\n" -" --eval Send an EVAL command using the Lua script at .\n" -" --ldb Used with --eval enable the Redis Lua debugger.\n" -" --ldb-sync-mode Like --ldb but uses the synchronous Lua debugger, in\n" -" this mode the server is blocked and script changes are\n" -" are not rolled back from the server memory.\n" -" --help Output this help and exit.\n" -" --version Output version and exit.\n" -"\n" -"Examples:\n" -" cat /etc/passwd | redis-cli -x set mypasswd\n" -" redis-cli get mypasswd\n" -" redis-cli -r 100 lpush mylist x\n" -" redis-cli -r 100 -i 1 info | grep used_memory_human:\n" -" redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3\n" -" redis-cli --scan --pattern '*:12345*'\n" -"\n" -" (Note: when using --eval the comma separates KEYS[] from ARGV[] items)\n" -"\n" -"When no command is given, redis-cli starts in interactive mode.\n" -"Type \"help\" in interactive mode for information on available commands\n" -"and settings.\n" -"\n", + "redis-cli %s\n" + "\n" + "Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n" + " -h Server hostname (default: 127.0.0.1).\n" + " -p Server port (default: 6379).\n" + " -s Server socket (overrides hostname and port).\n" + " -a Password to use when connecting to the server.\n" + " -r Execute specified command N times.\n" + " -i When -r is used, waits seconds per command.\n" + " It is possible to specify sub-second times like -i 0.1.\n" + " -n Database number.\n" + " -x Read last argument from STDIN.\n" + " -d Multi-bulk delimiter in for raw formatting (default: \\n).\n" + " -c Enable cluster mode (follow -ASK and -MOVED redirections).\n" + " --raw Use raw formatting for replies (default when STDOUT is\n" + " not a tty).\n" + " --no-raw Force formatted output even when STDOUT is not a tty.\n" + " --csv Output in CSV format.\n" + " --stat Print rolling stats about server: mem, clients, ...\n" + " --latency Enter a special mode continuously sampling latency.\n" + " If you use this mode in an interactive session it runs\n" + " forever displaying real-time stats. Otherwise if --raw or\n" + " --csv is specified, or if you redirect the output to a non\n" + " TTY, it samples the latency for 1 second (you can use\n" + " -i to change the interval), then produces a single output\n" + " and exits.\n" + " --latency-history Like --latency but tracking latency changes over time.\n" + " Default time interval is 15 sec. Change it using -i.\n" + " --latency-dist Shows latency as a spectrum, requires xterm 256 colors.\n" + " Default time interval is 1 sec. Change it using -i.\n" + " --lru-test Simulate a cache workload with an 80-20 distribution.\n" + " --slave Simulate a slave showing commands received from the master.\n" + " --rdb Transfer an RDB dump from remote server to local file.\n" + " --pipe Transfer raw Redis protocol from stdin to server.\n" + " --pipe-timeout In --pipe mode, abort with error if after sending all data.\n" + " no reply is received within seconds.\n" + " Default timeout: %d. Use 0 to wait forever.\n" + " --bigkeys Sample Redis keys looking for big keys.\n" + " --scan List all keys using the SCAN command.\n" + " --pattern Useful with --scan to specify a SCAN pattern.\n" + " --intrinsic-latency Run a test to measure intrinsic system latency.\n" + " The test will run for the specified amount of seconds.\n" + " --eval Send an EVAL command using the Lua script at .\n" + " --ldb Used with --eval enable the Redis Lua debugger.\n" + " --ldb-sync-mode Like --ldb but uses the synchronous Lua debugger, in\n" + " this mode the server is blocked and script changes are\n" + " are not rolled back from the server memory.\n" + " --help Output this help and exit.\n" + " --version Output version and exit.\n" + "\n" + "Examples:\n" + " cat /etc/passwd | redis-cli -x set mypasswd\n" + " redis-cli get mypasswd\n" + " redis-cli -r 100 lpush mylist x\n" + " redis-cli -r 100 -i 1 info | grep used_memory_human:\n" + " redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3\n" + " redis-cli --scan --pattern '*:12345*'\n" + "\n" + " (Note: when using --eval the comma separates KEYS[] from ARGV[] items)\n" + "\n" + "When no command is given, redis-cli starts in interactive mode.\n" + "Type \"help\" in interactive mode for information on available commands\n" + "and settings.\n" + "\n", version, REDIS_CLI_DEFAULT_PIPE_TIMEOUT); sdsfree(version); exit(1); @@ -1211,33 +1270,36 @@ static void usage(void) { /* Turn the plain C strings into Sds strings */ static char **convertToSds(int count, char** args) { - int j; - char **sds = zmalloc(sizeof(char*)*count); + int j; + char **sds = zmalloc(sizeof(char*)*count); - for(j = 0; j < count; j++) - sds[j] = sdsnew(args[j]); + for (j = 0; j < count; j++) + sds[j] = sdsnew(args[j]); - return sds; + return sds; } static int issueCommandRepeat(int argc, char **argv, PORT_LONG repeat) { while (1) { config.cluster_reissue_command = 0; - if (cliSendCommand(argc,argv,(int)repeat) != REDIS_OK) { WIN_PORT_FIX /* cast (int) */ - cliConnect(1); + if (cliSendCommand(argc, argv, (int) repeat) != REDIS_OK) { + WIN_PORT_FIX /* cast (int) */ + cliConnect(1); /* If we still cannot send the command print error. * We'll try to reconnect the next time. */ - if (cliSendCommand(argc,argv,(int)repeat) != REDIS_OK) { WIN_PORT_FIX /* cast (int) */ - cliPrintContextError(); + if (cliSendCommand(argc, argv, (int) repeat) != REDIS_OK) { + WIN_PORT_FIX /* cast (int) */ + cliPrintContextError(); return REDIS_ERR; } - } - /* Issue the command again if we got redirected in cluster mode */ - if (config.cluster_mode && config.cluster_reissue_command) { + } + /* Issue the command again if we got redirected in cluster mode */ + if (config.cluster_mode && config.cluster_reissue_command) { cliConnect(1); - } else { - break; + } + else { + break; } } return REDIS_OK; @@ -1254,18 +1316,19 @@ static int issueCommand(int argc, char **argv) { * the remaining Lua script (after "e " or "eval ") to be passed verbatim * as a single big argument. */ static sds *cliSplitArgs(char *line, int *argc) { - if (config.eval_ldb && (strstr(line,"eval ") == line || - strstr(line,"e ") == line)) + if (config.eval_ldb && (strstr(line, "eval ") == line || + strstr(line, "e ") == line)) { - sds *argv = sds_malloc(sizeof(sds)*2); + sds *argv = sds_malloc(sizeof(sds) * 2); *argc = 2; - int len = (int)strlen(line); WIN_PORT_FIX /* cast int */ - int elen = line[1] == ' ' ? 2 : 5; /* "e " or "eval "? */ - argv[0] = sdsnewlen(line,elen-1); - argv[1] = sdsnewlen(line+elen,len-elen); + int len = (int) strlen(line); WIN_PORT_FIX /* cast int */ + int elen = line[1] == ' ' ? 2 : 5; /* "e " or "eval "? */ + argv[0] = sdsnewlen(line, elen - 1); + argv[1] = sdsnewlen(line + elen, len - elen); return argv; - } else { - return sdssplitargs(line,argc); + } + else { + return sdssplitargs(line, argc); } } @@ -1273,15 +1336,16 @@ static sds *cliSplitArgs(char *line, int *argc) { * ":command" is called, or when reading ~/.redisclirc file, in order to * set user preferences. */ void cliSetPreferences(char **argv, int argc, int interactive) { - if (!strcasecmp(argv[0],":set") && argc >= 2) { - if (!strcasecmp(argv[1],"hints")) pref.hints = 1; - else if (!strcasecmp(argv[1],"nohints")) pref.hints = 0; + if (!strcasecmp(argv[0], ":set") && argc >= 2) { + if (!strcasecmp(argv[1], "hints")) pref.hints = 1; + else if (!strcasecmp(argv[1], "nohints")) pref.hints = 0; else { printf("%sunknown redis-cli preference '%s'\n", interactive ? "" : ".redisclirc: ", argv[1]); } - } else { + } + else { printf("%sunknown redis-cli internal command '%s'\n", interactive ? "" : ".redisclirc: ", argv[0]); @@ -1290,19 +1354,19 @@ void cliSetPreferences(char **argv, int argc, int interactive) { /* Load the ~/.redisclirc file if any. */ void cliLoadPreferences(void) { - sds rcfile = getDotfilePath(REDIS_CLI_RCFILE_ENV,REDIS_CLI_RCFILE_DEFAULT); + sds rcfile = getDotfilePath(REDIS_CLI_RCFILE_ENV, REDIS_CLI_RCFILE_DEFAULT); if (rcfile == NULL) return; - FILE *fp = fopen(rcfile,"r"); + FILE *fp = fopen(rcfile, "r"); char buf[1024]; if (fp) { - while(fgets(buf,sizeof(buf),fp) != NULL) { + while (fgets(buf, sizeof(buf), fp) != NULL) { sds *argv; int argc; - argv = sdssplitargs(buf,&argc); - if (argc > 0) cliSetPreferences(argv,argc,0); - sdsfreesplitres(argv,argc); + argv = sdssplitargs(buf, &argc); + if (argc > 0) cliSetPreferences(argv, argc, 0); + sdsfreesplitres(argv, argc); } fclose(fp); } @@ -1329,18 +1393,19 @@ static void repl(void) { /* Only use history and load the rc file when stdin is a tty. */ if (isatty(fileno(stdin))) { - historyfile = getDotfilePath(REDIS_CLI_HISTFILE_ENV,REDIS_CLI_HISTFILE_DEFAULT); + historyfile = getDotfilePath(REDIS_CLI_HISTFILE_ENV, REDIS_CLI_HISTFILE_DEFAULT); + //keep in-memory history always regardless if history file can be determined + history = 1; if (historyfile != NULL) { - history = 1; linenoiseHistoryLoad(historyfile); } cliLoadPreferences(); } cliRefreshPrompt(); - while((line = linenoise(context ? config.prompt : "not connected> ")) != NULL) { + while ((line = linenoise(context ? config.prompt : "not connected> ")) != NULL) { if (line[0] != '\0') { - argv = cliSplitArgs(line,&argc); + argv = cliSplitArgs(line, &argc); if (history) linenoiseHistoryAdd(line); if (historyfile) linenoiseHistorySave(historyfile); @@ -1348,31 +1413,38 @@ static void repl(void) { printf("Invalid argument(s)\n"); linenoiseFree(line); continue; - } else if (argc > 0) { - if (strcasecmp(argv[0],"quit") == 0 || - strcasecmp(argv[0],"exit") == 0) + } + else if (argc > 0) { + if (strcasecmp(argv[0], "quit") == 0 || + strcasecmp(argv[0], "exit") == 0) { exit(0); - } else if (argv[0][0] == ':') { - cliSetPreferences(argv,argc,1); + } + else if (argv[0][0] == ':') { + cliSetPreferences(argv, argc, 1); continue; - } else if (strcasecmp(argv[0],"restart") == 0) { + } + else if (strcasecmp(argv[0], "restart") == 0) { if (config.eval) { config.eval_ldb = 1; config.output = OUTPUT_RAW; return; /* Return to evalMode to restart the session. */ - } else { + } + else { printf("Use 'restart' only in Lua debugging mode."); } - } else if (argc == 3 && !strcasecmp(argv[0],"connect")) { + } + else if (argc == 3 && !strcasecmp(argv[0], "connect")) { sdsfree(config.hostip); config.hostip = sdsnew(argv[1]); config.hostport = atoi(argv[2]); cliRefreshPrompt(); cliConnect(1); - } else if (argc == 1 && !strcasecmp(argv[0],"clear")) { + } + else if (argc == 1 && !strcasecmp(argv[0], "clear")) { linenoiseClearScreen(); - } else { + } + else { PORT_LONGLONG start_time = mstime(), elapsed; int repeat, skipargs = 0; char *endptr; @@ -1380,11 +1452,12 @@ static void repl(void) { repeat = strtol(argv[0], &endptr, 10); if (argc > 1 && *endptr == '\0' && repeat) { skipargs = 1; - } else { + } + else { repeat = 1; } - issueCommandRepeat(argc-skipargs, argv+skipargs, repeat); + issueCommandRepeat(argc - skipargs, argv + skipargs, repeat); /* If our debugging session ended, show the EVAL final * reply. */ @@ -1396,16 +1469,16 @@ static void repl(void) { " -- dataset changes rolled back"); } - elapsed = mstime()-start_time; + elapsed = mstime() - start_time; if (elapsed >= 500 && config.output == OUTPUT_STANDARD) { - printf("(%.2fs)\n",(double)elapsed/1000); + printf("(%.2fs)\n", (double) elapsed / 1000); } } } /* Free the argument vector */ - sdsfreesplitres(argv,argc); + sdsfreesplitres(argv, argc); } /* linenoise() returns malloc-ed lines like readline() */ linenoiseFree(line); @@ -1416,10 +1489,11 @@ static void repl(void) { static int noninteractive(int argc, char **argv) { int retval = 0; if (config.stdinarg) { - argv = zrealloc(argv, (argc+1)*sizeof(char*)); + argv = zrealloc(argv, (argc + 1) * sizeof(char*)); argv[argc] = readArgFromStdin(); - retval = issueCommand(argc+1, argv); - } else { + retval = issueCommand(argc + 1, argv); + } + else { retval = issueCommand(argc, argv); } return retval; @@ -1438,13 +1512,13 @@ static int evalMode(int argc, char **argv) { int j, got_comma, keys; int retval = REDIS_OK; - while(1) { + while (1) { if (config.eval_ldb) { printf( - "Lua debugging session started, please use:\n" - "quit -- End the session.\n" - "restart -- Restart the script in debug mode again.\n" - "help -- Show Lua script debugging commands.\n\n" + "Lua debugging session started, please use:\n" + "quit -- End the session.\n" + "restart -- Restart the script in debug mode again.\n" + "help -- Show Lua script debugging commands.\n\n" ); } @@ -1454,27 +1528,27 @@ static int evalMode(int argc, char **argv) { keys = 0; /* Load the script from the file, as an sds string. */ - fp = fopen(config.eval,"r"); + fp = fopen(config.eval, "r"); if (!fp) { fprintf(stderr, "Can't open file '%s': %s\n", config.eval, strerror(errno)); exit(1); } - while((nread = fread(buf,1,sizeof(buf),fp)) != 0) { - script = sdscatlen(script,buf,nread); + while ((nread = fread(buf, 1, sizeof(buf), fp)) != 0) { + script = sdscatlen(script, buf, nread); } fclose(fp); /* If we are debugging a script, enable the Lua debugger. */ if (config.eval_ldb) { redisReply *reply = redisCommand(context, - config.eval_ldb_sync ? - "SCRIPT DEBUG sync": "SCRIPT DEBUG yes"); + config.eval_ldb_sync ? + "SCRIPT DEBUG sync" : "SCRIPT DEBUG yes"); if (reply) freeReplyObject(reply); } /* Create our argument vector */ - argv2 = zmalloc(sizeof(sds)*(argc+3)); + argv2 = zmalloc(sizeof(sds)*(argc + 3)); argv2[0] = sdsnew("EVAL"); argv2[1] = script; for (j = 0; j < argc; j++) { @@ -1482,14 +1556,14 @@ static int evalMode(int argc, char **argv) { got_comma = 1; continue; } - argv2[j+3-got_comma] = sdsnew(argv[j]); + argv2[j + 3 - got_comma] = sdsnew(argv[j]); if (!got_comma) keys++; } - argv2[2] = sdscatprintf(sdsempty(),"%d",keys); + argv2[2] = sdscatprintf(sdsempty(), "%d", keys); /* Call it */ int eval_ldb = config.eval_ldb; /* Save it, may be reverteed. */ - retval = issueCommand(argc+3-got_comma, argv2); + retval = issueCommand(argc + 3 - got_comma, argv2); if (eval_ldb) { if (!config.eval_ldb) { /* If the debugging session ended immediately, there was an @@ -1498,14 +1572,16 @@ static int evalMode(int argc, char **argv) { printf("Eval debugging session can't start:\n"); cliReadReply(0); break; /* Return to the caller. */ - } else { - strncpy(config.prompt,"lua debugger> ",sizeof(config.prompt)); + } + else { + strncpy(config.prompt, "lua debugger> ", sizeof(config.prompt)); repl(); /* Restart the session if repl() returned. */ cliConnect(1); printf("\n"); } - } else { + } + else { break; /* Return to the caller. */ } } @@ -1519,11 +1595,13 @@ static int evalMode(int argc, char **argv) { static void latencyModePrint(PORT_LONGLONG min, PORT_LONGLONG max, double avg, PORT_LONGLONG count) { if (config.output == OUTPUT_STANDARD) { printf("min: %lld, max: %lld, avg: %.2f (%lld samples)", - min, max, avg, count); + min, max, avg, count); fflush(stdout); - } else if (config.output == OUTPUT_CSV) { + } + else if (config.output == OUTPUT_CSV) { printf("%lld,%lld,%.2f,%lld\n", min, max, avg, count); - } else if (config.output == OUTPUT_RAW) { + } + else if (config.output == OUTPUT_RAW) { printf("%lld %lld %.2f %lld\n", min, max, avg, count); } } @@ -1534,8 +1612,8 @@ static void latencyMode(void) { redisReply *reply; PORT_LONGLONG start, latency, min = 0, max = 0, tot = 0, count = 0; PORT_LONGLONG history_interval = - config.interval ? config.interval/1000 : - LATENCY_HISTORY_DEFAULT_INTERVAL; + config.interval ? config.interval / 1000 : + LATENCY_HISTORY_DEFAULT_INTERVAL; double avg; PORT_LONGLONG history_start = mstime(); @@ -1543,46 +1621,50 @@ static void latencyMode(void) { * with --raw, --csv or when it is redirected to non tty. */ if (config.interval == 0) { config.interval = 1000; - } else { + } + else { config.interval /= 1000; /* We need to convert to milliseconds. */ } if (!context) exit(1); - while(1) { + while (1) { start = mstime(); - reply = reconnectingRedisCommand(context,"PING"); + reply = reconnectingRedisCommand(context, "PING"); if (reply == NULL) { - fprintf(stderr,"\nI/O error\n"); + fprintf(stderr, "\nI/O error\n"); exit(1); } - latency = mstime()-start; + latency = mstime() - start; freeReplyObject(reply); count++; if (count == 1) { min = max = tot = latency; avg = (double) latency; - } else { + } + else { if (latency < min) min = latency; if (latency > max) max = latency; tot += latency; - avg = (double) tot/count; + avg = (double) tot / count; } if (config.output == OUTPUT_STANDARD) { printf("\x1b[0G\x1b[2K"); /* Clear the line. */ - latencyModePrint(min,max,avg,count); - } else { + latencyModePrint(min, max, avg, count); + } + else { if (config.latency_history) { - latencyModePrint(min,max,avg,count); - } else if (mstime()-history_start > config.interval) { - latencyModePrint(min,max,avg,count); + latencyModePrint(min, max, avg, count); + } + else if (mstime() - history_start > config.interval) { + latencyModePrint(min, max, avg, count); exit(0); } } - if (config.latency_history && mstime()-history_start > history_interval) + if (config.latency_history && mstime() - history_start > history_interval) { - printf(" -- %.2f seconds range\n", (float)(mstime()-history_start)/1000); + printf(" -- %.2f seconds range\n", (float) (mstime() - history_start) / 1000); history_start = mstime(); min = max = tot = count = 0; } @@ -1596,7 +1678,7 @@ static void latencyMode(void) { #define LATENCY_DIST_DEFAULT_INTERVAL 1000 /* milliseconds. */ -/* Structure to store samples distribution. */ + /* Structure to store samples distribution. */ struct distsamples { PORT_LONGLONG max; /* Max latency to fit into this interval (usec). */ PORT_LONGLONG count; /* Number of samples in this interval. */ @@ -1617,17 +1699,17 @@ struct distsamples { void showLatencyDistSamples(struct distsamples *samples, PORT_LONGLONG tot) { int j; - /* We convert samples into a index inside the palette - * proportional to the percentage a given bucket represents. - * This way intensity of the different parts of the spectrum - * don't change relative to the number of requests, which avoids to - * pollute the visualization with non-latency related info. */ + /* We convert samples into a index inside the palette + * proportional to the percentage a given bucket represents. + * This way intensity of the different parts of the spectrum + * don't change relative to the number of requests, which avoids to + * pollute the visualization with non-latency related info. */ printf("\033[38;5;0m"); /* Set foreground color to black. */ for (j = 0; ; j++) { int coloridx = - (int)ceil((float) samples[j].count / tot * (spectrum_palette_size-1)); WIN_PORT_FIX /* cast (int) */ - int color = spectrum_palette[coloridx]; - printf("\033[48;5;%dm%c", (int)color, samples[j].character); + (int) ceil((float) samples[j].count / tot * (spectrum_palette_size - 1)); WIN_PORT_FIX /* cast (int) */ + int color = spectrum_palette[coloridx]; + printf("\033[48;5;%dm%c", (int) color, samples[j].character); samples[j].count = 0; if (samples[j].max == 0) break; /* Last sample. */ } @@ -1658,8 +1740,8 @@ static void latencyDistMode(void) { redisReply *reply; PORT_LONGLONG start, latency, count = 0; PORT_LONGLONG history_interval = - config.interval ? config.interval/1000 : - LATENCY_DIST_DEFAULT_INTERVAL; + config.interval ? config.interval / 1000 : + LATENCY_DIST_DEFAULT_INTERVAL; PORT_LONGLONG history_start = ustime(); int j, outputs = 0; @@ -1701,14 +1783,14 @@ static void latencyDistMode(void) { }; if (!context) exit(1); - while(1) { + while (1) { start = ustime(); - reply = reconnectingRedisCommand(context,"PING"); + reply = reconnectingRedisCommand(context, "PING"); if (reply == NULL) { - fprintf(stderr,"\nI/O error\n"); + fprintf(stderr, "\nI/O error\n"); exit(1); } - latency = ustime()-start; + latency = ustime() - start; freeReplyObject(reply); count++; @@ -1721,10 +1803,10 @@ static void latencyDistMode(void) { } /* From time to time show the spectrum. */ - if (count && (ustime()-history_start)/1000 > history_interval) { + if (count && (ustime() - history_start) / 1000 > history_interval) { if ((outputs++ % 20) == 0) showLatencyDistLegend(); - showLatencyDistSamples(samples,count); + showLatencyDistSamples(samples, count); history_start = ustime(); count = 0; } @@ -1736,8 +1818,8 @@ static void latencyDistMode(void) { * Slave mode *--------------------------------------------------------------------------- */ -/* Sends SYNC and reads the number of bytes in the payload. Used both by - * slaveMode() and getRDB(). */ + /* Sends SYNC and reads the number of bytes in the payload. Used both by + * slaveMode() and getRDB(). */ PORT_ULONGLONG sendSync(int fd) { /* To start we need to send the SYNC command and return the payload. * The hiredis client lib does not understand this part of the protocol @@ -1747,17 +1829,17 @@ PORT_ULONGLONG sendSync(int fd) { ssize_t nread; /* Send the SYNC command. */ - if (write(fd,"SYNC\r\n",6) != 6) { - fprintf(stderr,"Error writing to master\n"); + if (write(fd, "SYNC\r\n", 6) != 6) { + fprintf(stderr, "Error writing to master\n"); exit(1); } /* Read $\r\n, making sure to read just up to "\n" */ p = buf; - while(1) { - nread = read(fd,p,1); + while (1) { + nread = read(fd, p, 1); if (nread <= 0) { - fprintf(stderr,"Error reading bulk length while SYNCing\n"); + fprintf(stderr, "Error reading bulk length while SYNCing\n"); exit(1); } if (*p == '\n' && p != buf) break; @@ -1768,7 +1850,7 @@ PORT_ULONGLONG sendSync(int fd) { printf("SYNC with master failed: %s\n", buf); exit(1); } - return strtoull(buf+1,NULL,10); + return strtoull(buf + 1, NULL, 10); } static void slaveMode(void) { @@ -1777,21 +1859,21 @@ static void slaveMode(void) { char buf[1024]; int original_output = config.output; - fprintf(stderr,"SYNC with master, discarding %llu " - "bytes of bulk transfer...\n", payload); + fprintf(stderr, "SYNC with master, discarding %llu " + "bytes of bulk transfer...\n", payload); /* Discard the payload. */ - while(payload) { + while (payload) { ssize_t nread; - nread = read(fd,buf,(payload > sizeof(buf)) ? sizeof(buf) : payload); + nread = read(fd, buf, (payload > sizeof(buf)) ? sizeof(buf) : payload); if (nread <= 0) { - fprintf(stderr,"Error reading RDB payload while SYNCing\n"); + fprintf(stderr, "Error reading RDB payload while SYNCing\n"); exit(1); } payload -= nread; } - fprintf(stderr,"SYNC done. Logging commands from master.\n"); + fprintf(stderr, "SYNC done. Logging commands from master.\n"); /* Now we can use hiredis to read the incoming protocol. */ config.output = OUTPUT_CSV; @@ -1803,22 +1885,23 @@ static void slaveMode(void) { * RDB transfer mode *--------------------------------------------------------------------------- */ -/* This function implements --rdb, so it uses the replication protocol in order - * to fetch the RDB file from a remote server. */ + /* This function implements --rdb, so it uses the replication protocol in order + * to fetch the RDB file from a remote server. */ static void getRDB(void) { int s = context->fd; int fd; PORT_ULONGLONG payload = sendSync(s); char buf[4096]; - fprintf(stderr,"SYNC sent to master, writing %llu bytes to '%s'\n", + fprintf(stderr, "SYNC sent to master, writing %llu bytes to '%s'\n", payload, config.rdb_filename); /* Write to file. */ - if (!strcmp(config.rdb_filename,"-")) { + if (!strcmp(config.rdb_filename, "-")) { fd = STDOUT_FILENO; - } else { - fd = open(config.rdb_filename, O_CREAT|O_WRONLY, 0644); + } + else { + fd = open(config.rdb_filename, O_CREAT | O_WRONLY, 0644); if (fd == -1) { fprintf(stderr, "Error opening '%s': %s\n", config.rdb_filename, strerror(errno)); @@ -1826,17 +1909,17 @@ static void getRDB(void) { } } - while(payload) { + while (payload) { ssize_t nread, nwritten; - nread = read(s,buf,(payload > sizeof(buf)) ? sizeof(buf) : payload); + nread = read(s, buf, (payload > sizeof(buf)) ? sizeof(buf) : payload); if (nread <= 0) { - fprintf(stderr,"I/O Error reading RDB payload from socket\n"); + fprintf(stderr, "I/O Error reading RDB payload from socket\n"); exit(1); } nwritten = write(fd, buf, nread); if (nwritten != nread) { - fprintf(stderr,"Error writing data to file: %s\n", + fprintf(stderr, "Error writing data to file: %s\n", strerror(errno)); exit(1); } @@ -1844,7 +1927,7 @@ static void getRDB(void) { } close(s); /* Close the file descriptor ASAP as fsync() may take time. */ fsync(fd); - fprintf(stderr,"Transfer finished with success.\n"); + fprintf(stderr, "Transfer finished with success.\n"); exit(0); } @@ -1854,9 +1937,9 @@ static void getRDB(void) { #define PIPEMODE_WRITE_LOOP_MAX_BYTES (128*1024) static void pipeMode(void) { - int fd = (int)context->fd; + int fd = (int) context->fd; PORT_LONGLONG errors = 0, replies = 0, obuf_len = 0, obuf_pos = 0; - char ibuf[1024*16], obuf[1024*16]; /* Input and output buffers */ + char ibuf[1024 * 16], obuf[1024 * 16]; /* Input and output buffers */ char aneterr[ANET_ERR_LEN]; redisReader *reader = redisReaderCreate(); redisReply *reply; @@ -1867,25 +1950,25 @@ static void pipeMode(void) { #ifdef _WIN32 /* Prevent translation or CRLF sequences. */ - setmode(STDIN_FILENO,_O_BINARY); + setmode(STDIN_FILENO, _O_BINARY); #endif - srand((unsigned int)time(NULL)); WIN_PORT_FIX /* cast unsigned int */ + srand((unsigned int) time(NULL)); WIN_PORT_FIX /* cast unsigned int */ /* Use non blocking I/O. */ - if (anetNonBlock(aneterr,fd) == ANET_ERR) { - fprintf(stderr, "Can't set the socket in non blocking mode: %s\n", - aneterr); - exit(1); - } + if (anetNonBlock(aneterr, fd) == ANET_ERR) { + fprintf(stderr, "Can't set the socket in non blocking mode: %s\n", + aneterr); + exit(1); + } /* Transfer raw protocol and read replies from the server at the same * time. */ - while(!done) { + while (!done) { int mask = AE_READABLE; if (!eof || obuf_len != 0) mask |= AE_WRITABLE; - mask = aeWait(fd,mask,1000); + mask = aeWait(fd, mask, 1000); /* Handle the readable state: we can read replies from the server. */ if (mask & AE_READABLE) { @@ -1893,34 +1976,35 @@ static void pipeMode(void) { /* Read from socket and feed the hiredis reader. */ do { - nread = read(fd,ibuf,sizeof(ibuf)); + nread = read(fd, ibuf, sizeof(ibuf)); if (nread == -1 && errno != EAGAIN && errno != EINTR) { fprintf(stderr, "Error reading from the server: %s\n", strerror(errno)); exit(1); } if (nread > 0) { - redisReaderFeed(reader,ibuf,nread); + redisReaderFeed(reader, ibuf, nread); last_read_time = time(NULL); } - } while(nread > 0); + } while (nread > 0); /* Consume replies. */ do { - if (redisReaderGetReply(reader,(void**)&reply) == REDIS_ERR) { + if (redisReaderGetReply(reader, (void**) &reply) == REDIS_ERR) { fprintf(stderr, "Error reading replies from server\n"); exit(1); } if (reply) { if (reply->type == REDIS_REPLY_ERROR) { - fprintf(stderr,"%s\n", reply->str); + fprintf(stderr, "%s\n", reply->str); errors++; - } else if (eof && reply->type == REDIS_REPLY_STRING && - reply->len == 20) { + } + else if (eof && reply->type == REDIS_REPLY_STRING && + reply->len == 20) { /* Check if this is the reply to our final ECHO * command. If so everything was received * from the server. */ - if (memcmp(reply->str,magic,20) == 0) { + if (memcmp(reply->str, magic, 20) == 0) { printf("Last reply received from server.\n"); done = 1; replies--; @@ -1929,24 +2013,25 @@ static void pipeMode(void) { replies++; freeReplyObject(reply); } - } while(reply); + } while (reply); } /* Handle the writable state: we can send protocol to the server. */ if (mask & AE_WRITABLE) { ssize_t loop_nwritten = 0; - while(1) { + while (1) { /* Transfer current buffer to server. */ if (obuf_len != 0) { - ssize_t nwritten = write(fd,obuf+obuf_pos,(unsigned int)obuf_len); + ssize_t nwritten = write(fd, obuf + obuf_pos, (unsigned int) obuf_len); if (nwritten == -1) { if (errno != EAGAIN && errno != EINTR) { fprintf(stderr, "Error writing to the server: %s\n", strerror(errno)); exit(1); - } else { + } + else { nwritten = 0; } } @@ -1957,7 +2042,7 @@ static void pipeMode(void) { } /* If buffer is empty, load from stdin. */ if (obuf_len == 0 && !eof) { - ssize_t nread = read(STDIN_FILENO,obuf,sizeof(obuf)); + ssize_t nread = read(STDIN_FILENO, obuf, sizeof(obuf)); if (nread == 0) { /* The ECHO sequence starts with a "\r\n" so that if there @@ -1965,7 +2050,7 @@ static void pipeMode(void) { * will likely still be properly formatted. * CRLF is ignored by Redis, so it has no effects. */ char echo[] = - "\r\n*2\r\n$4\r\nECHO\r\n$20\r\n01234567890123456789\r\n"; + "\r\n*2\r\n$4\r\nECHO\r\n$20\r\n01234567890123456789\r\n"; int j; eof = 1; @@ -1974,16 +2059,18 @@ static void pipeMode(void) { * to make sure everything was read from the server. */ for (j = 0; j < 20; j++) magic[j] = rand() & 0xff; - memcpy(echo+21,magic,20); - memcpy(obuf,echo,sizeof(echo)-1); - obuf_len = sizeof(echo)-1; + memcpy(echo + 21, magic, 20); + memcpy(obuf, echo, sizeof(echo) - 1); + obuf_len = sizeof(echo) - 1; obuf_pos = 0; printf("All data transferred. Waiting for the last reply...\n"); - } else if (nread == -1) { + } + else if (nread == -1) { fprintf(stderr, "Error reading from stdin: %s\n", strerror(errno)); exit(1); - } else { + } + else { obuf_len = nread; obuf_pos = 0; } @@ -1997,9 +2084,9 @@ static void pipeMode(void) { * replies from the server for a few seconds, nor the final ECHO is * received. */ if (eof && config.pipe_timeout > 0 && - time(NULL)-last_read_time > config.pipe_timeout) + time(NULL) - last_read_time > config.pipe_timeout) { - fprintf(stderr,"No replies for %d seconds: exiting.\n", + fprintf(stderr, "No replies for %d seconds: exiting.\n", config.pipe_timeout); errors++; break; @@ -2028,16 +2115,19 @@ static redisReply *sendScan(PORT_ULONGLONG *it) { redisReply *reply = redisCommand(context, "SCAN %llu", *it); /* Handle any error conditions */ - if(reply == NULL) { + if (reply == NULL) { fprintf(stderr, "\nI/O error\n"); exit(1); - } else if(reply->type == REDIS_REPLY_ERROR) { + } + else if (reply->type == REDIS_REPLY_ERROR) { fprintf(stderr, "SCAN error: %s\n", reply->str); exit(1); - } else if(reply->type != REDIS_REPLY_ARRAY) { + } + else if (reply->type != REDIS_REPLY_ARRAY) { fprintf(stderr, "Non ARRAY response from SCAN!\n"); exit(1); - } else if(reply->elements != 2) { + } + else if (reply->elements != 2) { fprintf(stderr, "Invalid element count from SCAN!\n"); exit(1); } @@ -2058,32 +2148,38 @@ static int getDbSize(void) { reply = redisCommand(context, "DBSIZE"); - if(reply == NULL || reply->type != REDIS_REPLY_INTEGER) { + if (reply == NULL || reply->type != REDIS_REPLY_INTEGER) { fprintf(stderr, "Couldn't determine DBSIZE!\n"); exit(1); } /* Grab the number of keys and free our reply */ - size = (int)reply->integer; + size = (int) reply->integer; freeReplyObject(reply); return size; } static int toIntType(char *key, char *type) { - if(!strcmp(type, "string")) { + if (!strcmp(type, "string")) { return TYPE_STRING; - } else if(!strcmp(type, "list")) { + } + else if (!strcmp(type, "list")) { return TYPE_LIST; - } else if(!strcmp(type, "set")) { + } + else if (!strcmp(type, "set")) { return TYPE_SET; - } else if(!strcmp(type, "hash")) { + } + else if (!strcmp(type, "hash")) { return TYPE_HASH; - } else if(!strcmp(type, "zset")) { + } + else if (!strcmp(type, "zset")) { return TYPE_ZSET; - } else if(!strcmp(type, "none")) { + } + else if (!strcmp(type, "none")) { return TYPE_NONE; - } else { + } + else { fprintf(stderr, "Unknown type '%s' for key '%s'\n", type, key); exit(1); } @@ -2094,20 +2190,22 @@ static void getKeyTypes(redisReply *keys, int *types) { unsigned int i; /* Pipeline TYPE commands */ - for(i=0;ielements;i++) { + for (i = 0; i < keys->elements; i++) { redisAppendCommand(context, "TYPE %s", keys->element[i]->str); } /* Retrieve types */ - for(i=0;ielements;i++) { - if(redisGetReply(context, (void**)&reply)!=REDIS_OK) { + for (i = 0; i < keys->elements; i++) { + if (redisGetReply(context, (void**) &reply) != REDIS_OK) { fprintf(stderr, "Error getting type for key '%s' (%d: %s)\n", keys->element[i]->str, context->err, context->errstr); exit(1); - } else if(reply->type != REDIS_REPLY_STATUS) { - if(reply->type == REDIS_REPLY_ERROR) { + } + else if (reply->type != REDIS_REPLY_STATUS) { + if (reply->type == REDIS_REPLY_ERROR) { fprintf(stderr, "TYPE returned an error: %s\n", reply->str); - } else { + } + else { fprintf(stderr, "Invalid reply type (%d) for TYPE on key '%s'!\n", reply->type, keys->element[i]->str); @@ -2121,16 +2219,16 @@ static void getKeyTypes(redisReply *keys, int *types) { } static void getKeySizes(redisReply *keys, int *types, - PORT_ULONGLONG *sizes) + PORT_ULONGLONG *sizes) { redisReply *reply; - char *sizecmds[] = {"STRLEN","LLEN","SCARD","HLEN","ZCARD"}; + char *sizecmds[] = { "STRLEN","LLEN","SCARD","HLEN","ZCARD" }; unsigned int i; /* Pipeline size commands */ - for(i=0;ielements;i++) { + for (i = 0; i < keys->elements; i++) { /* Skip keys that were deleted */ - if(types[i]==TYPE_NONE) + if (types[i] == TYPE_NONE) continue; redisAppendCommand(context, "%s %s", sizecmds[types[i]], @@ -2138,26 +2236,28 @@ static void getKeySizes(redisReply *keys, int *types, } /* Retreive sizes */ - for(i=0;ielements;i++) { + for (i = 0; i < keys->elements; i++) { /* Skip keys that dissapeared between SCAN and TYPE */ - if(types[i] == TYPE_NONE) { + if (types[i] == TYPE_NONE) { sizes[i] = 0; continue; } /* Retreive size */ - if(redisGetReply(context, (void**)&reply)!=REDIS_OK) { + if (redisGetReply(context, (void**) &reply) != REDIS_OK) { fprintf(stderr, "Error getting size for key '%s' (%d: %s)\n", keys->element[i]->str, context->err, context->errstr); exit(1); - } else if(reply->type != REDIS_REPLY_INTEGER) { + } + else if (reply->type != REDIS_REPLY_INTEGER) { /* Theoretically the key could have been removed and * added as a different type between TYPE and SIZE */ fprintf(stderr, "Warning: %s on '%s' failed (may have changed type)\n", - sizecmds[types[i]], keys->element[i]->str); + sizecmds[types[i]], keys->element[i]->str); sizes[i] = 0; - } else { + } + else { sizes[i] = reply->integer; } @@ -2166,14 +2266,14 @@ static void getKeySizes(redisReply *keys, int *types, } static void findBigKeys(void) { - PORT_ULONGLONG biggest[5] = {0}, counts[5] = {0}, totalsize[5] = {0}; - PORT_ULONGLONG sampled = 0, total_keys, totlen=0, *sizes=NULL, it=0; - sds maxkeys[5] = {0}; - char *typename[] = {"string","list","set","hash","zset"}; - char *typeunit[] = {"bytes","items","members","fields","members"}; + PORT_ULONGLONG biggest[5] = { 0 }, counts[5] = { 0 }, totalsize[5] = { 0 }; + PORT_ULONGLONG sampled = 0, total_keys, totlen = 0, *sizes = NULL, it = 0; + sds maxkeys[5] = { 0 }; + char *typename[] = { "string","list","set","hash","zset" }; + char *typeunit[] = { "bytes","items","members","fields","members" }; redisReply *reply, *keys; - unsigned int arrsize=0, i; - int type, *types=NULL; + unsigned int arrsize = 0, i; + int type, *types = NULL; double pct; /* Total keys pre scanning */ @@ -2185,9 +2285,9 @@ static void findBigKeys(void) { printf("# per 100 SCAN commands (not usually needed).\n\n"); /* New up sds strings to keep track of overall biggest per type */ - for(i=0;ielement[1]; + keys = reply->element[1]; /* Reallocate our type and size array if we need to */ - if(keys->elements > arrsize) { + if (keys->elements > arrsize) { types = zrealloc(types, sizeof(int)*keys->elements); sizes = zrealloc(sizes, sizeof(PORT_ULONGLONG)*keys->elements); - if(!types || !sizes) { + if (!types || !sizes) { fprintf(stderr, "Failed to allocate storage for keys!\n"); exit(1); } - arrsize = (int)keys->elements; + arrsize = (int) keys->elements; } /* Retreive types and then sizes */ @@ -2220,8 +2320,8 @@ static void findBigKeys(void) { getKeySizes(keys, types, sizes); /* Now update our stats */ - for(i=0;ielements;i++) { - if((type = types[i]) == TYPE_NONE) + for (i = 0; i < keys->elements; i++) { + if ((type = types[i]) == TYPE_NONE) continue; totalsize[type] += sizes[i]; @@ -2229,15 +2329,15 @@ static void findBigKeys(void) { totlen += keys->element[i]->len; sampled++; - if(biggest[type]element[i]->str, sizes[i], - typeunit[type]); + "[%05.2f%%] Biggest %-6s found so far '%s' with %llu %s\n", + pct, typename[type], keys->element[i]->str, sizes[i], + typeunit[type]); /* Keep track of biggest key name for this type */ maxkeys[type] = sdscpy(maxkeys[type], keys->element[i]->str); - if(!maxkeys[type]) { + if (!maxkeys[type]) { fprintf(stderr, "Failed to allocate memory for key!\n"); exit(1); } @@ -2247,48 +2347,48 @@ static void findBigKeys(void) { } /* Update overall progress */ - if(sampled % 1000000 == 0) { + if (sampled % 1000000 == 0) { printf("[%05.2f%%] Sampled %llu keys so far\n", pct, sampled); } } /* Sleep if we've been directed to do so */ - if(sampled && (sampled %100) == 0 && config.interval) { + if (sampled && (sampled % 100) == 0 && config.interval) { usleep(config.interval); } freeReplyObject(reply); - } while(it != 0); + } while (it != 0); - if(types) zfree(types); - if(sizes) zfree(sizes); + if (types) zfree(types); + if (sizes) zfree(sizes); /* We're done */ printf("\n-------- summary -------\n\n"); printf("Sampled %llu keys in the keyspace!\n", sampled); printf("Total key length in bytes is %llu (avg len %.2f)\n\n", - totlen, totlen ? (double)totlen/sampled : 0); + totlen, totlen ? (double) totlen / sampled : 0); /* Output the biggest keys we found, for types we did find */ - for(i=0;i0) { + for (i = 0; i < TYPE_NONE; i++) { + if (sdslen(maxkeys[i]) > 0) { printf("Biggest %6s found '%s' has %llu %s\n", typename[i], maxkeys[i], - biggest[i], typeunit[i]); + biggest[i], typeunit[i]); } } printf("\n"); - for(i=0;itype == REDIS_REPLY_ERROR) { printf("ERROR: %s\n", reply->str); exit(1); @@ -2374,8 +2477,8 @@ static void statMode(void) { if ((i++ % 20) == 0) { printf( -"------- data ------ --------------------- load -------------------- - child -\n" -"keys mem clients blocked requests connections \n"); + "------- data ------ --------------------- load -------------------- - child -\n" + "keys mem clients blocked requests connections \n"); } /* Keys */ @@ -2383,45 +2486,45 @@ static void statMode(void) { for (j = 0; j < 20; j++) { PORT_LONG k; - sprintf(buf,"db%d:keys",j); - k = getLongInfoField(reply->str,buf); + sprintf(buf, "db%d:keys", j); + k = getLongInfoField(reply->str, buf); if (k == PORT_LONG_MIN) continue; aux += k; } - sprintf(buf,"%Id",aux); WIN_PORT_FIX /* %ld -> %Id */ - printf("%-11s",buf); + sprintf(buf, "%Id", aux); WIN_PORT_FIX /* %ld -> %Id */ + printf("%-11s", buf); /* Used memory */ - aux = getLongInfoField(reply->str,"used_memory"); - bytesToHuman(buf,aux); - printf("%-8s",buf); + aux = getLongInfoField(reply->str, "used_memory"); + bytesToHuman(buf, aux); + printf("%-8s", buf); /* Clients */ - aux = getLongInfoField(reply->str,"connected_clients"); - sprintf(buf,"%Id",aux); WIN_PORT_FIX /* %ld -> %Id */ - printf(" %-8s",buf); + aux = getLongInfoField(reply->str, "connected_clients"); + sprintf(buf, "%Id", aux); WIN_PORT_FIX /* %ld -> %Id */ + printf(" %-8s", buf); /* Blocked (BLPOPPING) Clients */ - aux = getLongInfoField(reply->str,"blocked_clients"); - sprintf(buf,"%Id",aux); WIN_PORT_FIX /* %ld -> %Id */ - printf("%-8s",buf); + aux = getLongInfoField(reply->str, "blocked_clients"); + sprintf(buf, "%Id", aux); WIN_PORT_FIX /* %ld -> %Id */ + printf("%-8s", buf); /* Requets */ - aux = getLongInfoField(reply->str,"total_commands_processed"); - sprintf(buf,"%Id (+%Id)",aux,requests == 0 ? 0 : aux-requests); WIN_PORT_FIX /* %ld -> %Id */ - printf("%-19s",buf); + aux = getLongInfoField(reply->str, "total_commands_processed"); + sprintf(buf, "%Id (+%Id)", aux, requests == 0 ? 0 : aux - requests); WIN_PORT_FIX /* %ld -> %Id */ + printf("%-19s", buf); requests = aux; /* Connections */ - aux = getLongInfoField(reply->str,"total_connections_received"); - sprintf(buf,"%Id",aux); WIN_PORT_FIX /* %ld -> %Id */ - printf(" %-12s",buf); + aux = getLongInfoField(reply->str, "total_connections_received"); + sprintf(buf, "%Id", aux); WIN_PORT_FIX /* %ld -> %Id */ + printf(" %-12s", buf); /* Children */ - aux = getLongInfoField(reply->str,"bgsave_in_progress"); - aux |= getLongInfoField(reply->str,"aof_rewrite_in_progress") << 1; - aux |= getLongInfoField(reply->str,"loading") << 2; - switch(aux) { + aux = getLongInfoField(reply->str, "bgsave_in_progress"); + aux |= getLongInfoField(reply->str, "aof_rewrite_in_progress") << 1; + aux |= getLongInfoField(reply->str, "loading") << 2; + switch (aux) { case 0: break; case 1: printf("SAVE"); @@ -2453,25 +2556,27 @@ static void scanMode(void) { do { if (config.pattern) - reply = redisCommand(context,"SCAN %llu MATCH %s", - cur,config.pattern); + reply = redisCommand(context, "SCAN %llu MATCH %s", + cur, config.pattern); else - reply = redisCommand(context,"SCAN %llu",cur); + reply = redisCommand(context, "SCAN %llu", cur); if (reply == NULL) { printf("I/O error\n"); exit(1); - } else if (reply->type == REDIS_REPLY_ERROR) { + } + else if (reply->type == REDIS_REPLY_ERROR) { printf("ERROR: %s\n", reply->str); exit(1); - } else { + } + else { unsigned int j; - cur = strtoull(reply->element[0]->str,NULL,10); + cur = strtoull(reply->element[0]->str, NULL, 10); for (j = 0; j < reply->element[1]->elements; j++) printf("%s\n", reply->element[1]->element[j]->str); } freeReplyObject(reply); - } while(cur != 0); + } while (cur != 0); exit(0); } @@ -2480,21 +2585,21 @@ static void scanMode(void) { * LRU test mode *--------------------------------------------------------------------------- */ -/* Return an integer from min to max (both inclusive) using a power-law - * distribution, depending on the value of alpha: the greater the alpha - * the more bias towards lower values. - * - * With alpha = 6.2 the output follows the 80-20 rule where 20% of - * the returned numbers will account for 80% of the frequency. */ + /* Return an integer from min to max (both inclusive) using a power-law + * distribution, depending on the value of alpha: the greater the alpha + * the more bias towards lower values. + * + * With alpha = 6.2 the output follows the 80-20 rule where 20% of + * the returned numbers will account for 80% of the frequency. */ PORT_LONGLONG powerLawRand(PORT_LONGLONG min, PORT_LONGLONG max, double alpha) { double pl, r; max += 1; - r = ((double)rand()) / RAND_MAX; + r = ((double) rand()) / RAND_MAX; pl = pow( - ((pow((double)max,alpha+1) - pow((double)min,alpha+1))*r + pow((double)min,alpha+1)), WIN_PORT_FIX /* cast (double) */ - (1.0/(alpha+1))); - return (max-1-(PORT_LONGLONG)pl)+min; + ((pow((double) max, alpha + 1) - pow((double) min, alpha + 1))*r + pow((double) min, alpha + 1)), WIN_PORT_FIX /* cast (double) */ + (1.0 / (alpha + 1))); + return (max - 1 - (PORT_LONGLONG) pl) + min; } /* Generates a key name among a set of lru_test_sample_size keys, using @@ -2512,33 +2617,33 @@ static void LRUTestMode(void) { PORT_LONGLONG start_cycle; int j; - srand((unsigned int)(time(NULL)^getpid())); WIN_PORT_FIX /* cast (unsigned int) */ - while(1) { - /* Perform cycles of 1 second with 50% writes and 50% reads. - * We use pipelining batching writes / reads N times per cycle in order - * to fill the target instance easily. */ - start_cycle = mstime(); - PORT_LONGLONG hits = 0, misses = 0; - while(mstime() - start_cycle < 1000) { - /* Write cycle. */ - for (j = 0; j < LRU_CYCLE_PIPELINE_SIZE; j++) { - char val[6]; - val[5] = '\0'; - for (int i = 0; i < 5; i++) val[i] = 'A'+rand()%('z'-'A'); - LRUTestGenKey(key,sizeof(key)); - redisAppendCommand(context, "SET %s %s",key,val); - } - for (j = 0; j < LRU_CYCLE_PIPELINE_SIZE; j++) - redisGetReply(context, (void**)&reply); + srand((unsigned int) (time(NULL) ^ getpid())); WIN_PORT_FIX /* cast (unsigned int) */ + while (1) { + /* Perform cycles of 1 second with 50% writes and 50% reads. + * We use pipelining batching writes / reads N times per cycle in order + * to fill the target instance easily. */ + start_cycle = mstime(); + PORT_LONGLONG hits = 0, misses = 0; + while (mstime() - start_cycle < 1000) { + /* Write cycle. */ + for (j = 0; j < LRU_CYCLE_PIPELINE_SIZE; j++) { + char val[6]; + val[5] = '\0'; + for (int i = 0; i < 5; i++) val[i] = 'A' + rand() % ('z' - 'A'); + LRUTestGenKey(key, sizeof(key)); + redisAppendCommand(context, "SET %s %s", key, val); + } + for (j = 0; j < LRU_CYCLE_PIPELINE_SIZE; j++) + redisGetReply(context, (void**) &reply); - /* Read cycle. */ - for (j = 0; j < LRU_CYCLE_PIPELINE_SIZE; j++) { - LRUTestGenKey(key,sizeof(key)); - redisAppendCommand(context, "GET %s",key); - } - for (j = 0; j < LRU_CYCLE_PIPELINE_SIZE; j++) { - if (redisGetReply(context, (void**)&reply) == REDIS_OK) { - switch(reply->type) { + /* Read cycle. */ + for (j = 0; j < LRU_CYCLE_PIPELINE_SIZE; j++) { + LRUTestGenKey(key, sizeof(key)); + redisAppendCommand(context, "GET %s", key); + } + for (j = 0; j < LRU_CYCLE_PIPELINE_SIZE; j++) { + if (redisGetReply(context, (void**) &reply) == REDIS_OK) { + switch (reply->type) { case REDIS_REPLY_ERROR: printf("%s\n", reply->str); break; @@ -2548,22 +2653,22 @@ static void LRUTestMode(void) { default: hits++; break; + } } } - } - if (context->err) { - fprintf(stderr,"I/O error during LRU test\n"); - exit(1); + if (context->err) { + fprintf(stderr, "I/O error during LRU test\n"); + exit(1); + } } + /* Print stats. */ + printf( + "%lld Gets/sec | Hits: %lld (%.2f%%) | Misses: %lld (%.2f%%)\n", + hits + misses, + hits, (double) hits / (hits + misses) * 100, + misses, (double) misses / (hits + misses) * 100); } - /* Print stats. */ - printf( - "%lld Gets/sec | Hits: %lld (%.2f%%) | Misses: %lld (%.2f%%)\n", - hits+misses, - hits, (double)hits/(hits+misses)*100, - misses, (double)misses/(hits+misses)*100); - } exit(0); } @@ -2575,9 +2680,9 @@ static void LRUTestMode(void) { * time the kernel leaves the process without a chance to run. *--------------------------------------------------------------------------- */ -/* This is just some computation the compiler can't optimize out. - * Should run in less than 100-200 microseconds even using very - * slow hardware. Runs in less than 10 microseconds in modern HW. */ + /* This is just some computation the compiler can't optimize out. + * Should run in less than 100-200 microseconds even using very + * slow hardware. Runs in less than 10 microseconds in modern HW. */ PORT_ULONG compute_something_fast(void) { unsigned char s[256], i, j, t; int count = 1000, k; @@ -2587,13 +2692,13 @@ PORT_ULONG compute_something_fast(void) { i = 0; j = 0; - while(count--) { + while (count--) { i++; j = j + s[i]; t = s[i]; s[i] = s[j]; s[j] = t; - output += s[(s[i]+s[j])&255]; + output += s[(s[i] + s[j]) & 255]; } return output; } @@ -2606,17 +2711,17 @@ static void intrinsicLatencyModeStop(int s) { static void intrinsicLatencyMode(void) { PORT_LONGLONG test_end, run_time, max_latency = 0, runs = 0; - run_time = config.intrinsic_latency_duration*1000000; + run_time = config.intrinsic_latency_duration * 1000000; test_end = ustime() + run_time; signal(SIGINT, intrinsicLatencyModeStop); - while(1) { + while (1) { PORT_LONGLONG start, end, latency; start = ustime(); compute_something_fast(); end = ustime(); - latency = end-start; + latency = end - start; runs++; if (latency <= 0) continue; @@ -2626,7 +2731,7 @@ static void intrinsicLatencyMode(void) { printf("Max latency so far: %lld microseconds.\n", max_latency); } - double avg_us = (double)run_time/runs; + double avg_us = (double) run_time / runs; double avg_ns = avg_us * 1e3; if (force_cancel_loop || end > test_end) { printf("\n%lld total runs " @@ -2697,7 +2802,7 @@ int main(int argc, char **argv) { config.output = OUTPUT_STANDARD; config.mb_delim = sdsnew("\n"); - firstarg = parseOptions(argc,argv); + firstarg = parseOptions(argc, argv); argc -= firstarg; argv += firstarg; @@ -2773,8 +2878,9 @@ int main(int argc, char **argv) { /* Otherwise, we have some arguments to execute */ if (cliConnect(0) != REDIS_OK) exit(1); if (config.eval) { - return evalMode(argc,argv); - } else { - return noninteractive(argc,convertToSds(argc,argv)); + return evalMode(argc, argv); } -} + else { + return noninteractive(argc, convertToSds(argc, argv)); + } +} \ No newline at end of file