diff --git a/src/notify.c b/src/notify.c index 686bf69c..5edb4f22 100644 --- a/src/notify.c +++ b/src/notify.c @@ -98,13 +98,11 @@ void notifyKeyspaceEvent(int type, char *event, robj *key, int dbid) { int len = -1; char buf[24]; -#ifndef _WIN32 /* If any modules are interested in events, notify the module system now. * This bypasses the notifications configuration, but the module engine * will only call event subscribers if the event type matches the types * they are interested in. */ moduleNotifyKeyspaceEvent(type, event, key, dbid); -#endif /* If notifications for this class of events are off, return ASAP. */ if (!(server.notify_keyspace_events & type)) return; diff --git a/src/object.c b/src/object.c index bf529aeb..b3865ee6 100644 --- a/src/object.c +++ b/src/object.c @@ -36,7 +36,6 @@ #include #include - #ifdef __CYGWIN__ #define strtold(a,b) ((PORT_LONGDOUBLE)strtod((a),(b))) #endif @@ -143,14 +142,14 @@ robj *createStringObjectFromLongLong(PORT_LONGLONG value) { return o; } -/* Create a string object from a PORT_LONGDOUBLE. If humanfriendly is non-zero +/* Create a string object from a long double. If humanfriendly is non-zero * it does not use exponential format and trims trailing zeroes at the end, * however this results in loss of precision. Otherwise exp format is used * and the output of snprintf() is not modified. * * The 'humanfriendly' option is used for INCRBYFLOAT and HINCRBYFLOAT. */ robj *createStringObjectFromLongDouble(PORT_LONGDOUBLE value, int humanfriendly) { - char buf[256]; + char buf[MAX_LONG_DOUBLE_CHARS]; int len = ld2string(buf,sizeof(buf),value,humanfriendly); return createStringObject(buf,len); } @@ -536,7 +535,7 @@ int equalStringObjects(robj *a, robj *b) { if (a->encoding == OBJ_ENCODING_INT && b->encoding == OBJ_ENCODING_INT){ /* If both strings are integer encoded just check if the stored - * PORT_LONG is the same. */ + * long is the same. */ return a->ptr == b->ptr; } else { return compareStringObjects(a,b) == 0; @@ -552,8 +551,8 @@ size_t stringObjectLen(robj *o) { } } -int getDoubleFromObject(const robj *o, PORT_LONGDOUBLE *target) { - PORT_LONGDOUBLE value; +int getDoubleFromObject(const robj *o, double *target) { + double value; char *eptr; if (o == NULL) { @@ -580,8 +579,8 @@ int getDoubleFromObject(const robj *o, PORT_LONGDOUBLE *target) { return C_OK; } -int getDoubleFromObjectOrReply(client *c, robj *o, PORT_LONGDOUBLE *target, const char *msg) { - PORT_LONGDOUBLE value; +int getDoubleFromObjectOrReply(client *c, robj *o, double *target, const char *msg) { + double value; if (getDoubleFromObject(o, &value) != C_OK) { if (msg != NULL) { addReplyError(c,(char*)msg); @@ -604,7 +603,7 @@ int getLongDoubleFromObject(robj *o, PORT_LONGDOUBLE *target) { serverAssertWithInfo(NULL,o,o->type == OBJ_STRING); if (sdsEncodedObject(o)) { errno = 0; - value = IF_WIN32(wstrtod,strtold)(o->ptr,&eptr); // TODO: verify for 32-bit + value = IF_WIN32(wstrtod,strtold)(o->ptr, &eptr); // TODO: verify for 32-bit if (sdslen(o->ptr) == 0 || isspace(((const char*)o->ptr)[0]) || (size_t)(eptr-(char*)o->ptr) != sdslen(o->ptr) || @@ -638,7 +637,6 @@ int getLongDoubleFromObjectOrReply(client *c, robj *o, PORT_LONGDOUBLE *target, int getLongLongFromObject(robj *o, PORT_LONGLONG *target) { PORT_LONGLONG value; - char *eptr; if (o == NULL) { value = 0; @@ -733,7 +731,7 @@ size_t objectComputeSize(robj *o, size_t sample_size) { elesize += sizeof(quicklistNode)+ziplistBlobLen(node->zl); samples++; } while ((node = node->next) && samples < sample_size); - asize += (PORT_LONGDOUBLE)elesize/samples*ql->len; + asize += (double)elesize/samples*ql->len; } else if (o->encoding == OBJ_ENCODING_ZIPLIST) { asize = sizeof(*o)+ziplistBlobLen(o->ptr); } else { @@ -750,7 +748,7 @@ size_t objectComputeSize(robj *o, size_t sample_size) { samples++; } dictReleaseIterator(di); - if (samples) asize += (PORT_LONGDOUBLE)elesize/samples*dictSize(d); + if (samples) asize += (double)elesize/samples*dictSize(d); } else if (o->encoding == OBJ_ENCODING_INTSET) { intset *is = o->ptr; asize = sizeof(*o)+sizeof(*is)+is->encoding*is->length; @@ -771,7 +769,7 @@ size_t objectComputeSize(robj *o, size_t sample_size) { samples++; znode = znode->level[0].forward; } - if (samples) asize += (PORT_LONGDOUBLE)elesize/samples*dictSize(d); + if (samples) asize += (double)elesize/samples*dictSize(d); } else { serverPanic("Unknown sorted set encoding"); } @@ -790,7 +788,7 @@ size_t objectComputeSize(robj *o, size_t sample_size) { samples++; } dictReleaseIterator(di); - if (samples) asize += (PORT_LONGDOUBLE)elesize/samples*dictSize(d); + if (samples) asize += (double)elesize/samples*dictSize(d); } else { serverPanic("Unknown hash encoding"); } diff --git a/src/quicklist.c b/src/quicklist.c index 55510532..d4f3f791 100644 --- a/src/quicklist.c +++ b/src/quicklist.c @@ -1315,7 +1315,7 @@ void quicklistRotate(quicklist *quicklist) { /* pop from quicklist and return result in 'data' ptr. Value of 'data' * is the return value of 'saver' function pointer if the data is NOT a number. * - * If the quicklist element is a PORT_LONGLONG, then the return value is returned in + * If the quicklist element is a long long, then the return value is returned in * 'sval'. * * Return value of 0 means no elements available. diff --git a/src/quicklist.h b/src/quicklist.h index 064dd295..be3e0365 100644 --- a/src/quicklist.h +++ b/src/quicklist.h @@ -68,7 +68,7 @@ typedef struct quicklistLZF { char compressed[]; } quicklistLZF; -/* quicklist is a 32 byte struct (on 64-bit systems) describing a quicklist. +/* quicklist is a 40 byte struct (on 64-bit systems) describing a quicklist. * 'count' is the number of total entries. * 'len' is the number of quicklist nodes. * 'compress' is: -1 if compression disabled, otherwise it's the number @@ -78,7 +78,7 @@ typedef struct quicklist { quicklistNode *head; quicklistNode *tail; PORT_ULONG count; /* total count of all entries in all ziplists */ - unsigned int len; /* number of quicklistNodes */ + PORT_ULONG len; /* number of quicklistNodes */ int fill : 16; /* fill factor for individual nodes */ unsigned int compress : 16; /* depth of end nodes not to compress;0=off */ } quicklist; diff --git a/src/rdb.c b/src/rdb.c index c3a6399b..57b4761a 100644 --- a/src/rdb.c +++ b/src/rdb.c @@ -409,7 +409,7 @@ ssize_t rdbSaveRawString(rio *rdb, unsigned char *s, size_t len) { } /* Store verbatim */ - if ((n = rdbSaveLen(rdb,(uint32_t)len)) == -1) return -1; WIN_PORT_FIX /* cast (uint32_t) */ + if ((n = rdbSaveLen(rdb,len)) == -1) return -1; nwritten += n; if (len > 0) { if (rdbWriteRaw(rdb,s,len) == -1) return -1; @@ -418,7 +418,7 @@ ssize_t rdbSaveRawString(rio *rdb, unsigned char *s, size_t len) { return nwritten; } -/* Save a PORT_LONGLONG value as either an encoded string or a string. */ +/* Save a long long value as either an encoded string or a string. */ ssize_t rdbSaveLongLongAsStringObject(rio *rdb, PORT_LONGLONG value) { unsigned char buf[32]; ssize_t n, nwritten = 0; @@ -438,7 +438,7 @@ ssize_t rdbSaveLongLongAsStringObject(rio *rdb, PORT_LONGLONG value) { } /* Like rdbSaveRawString() gets a Redis object instead. */ -int rdbSaveStringObject(rio *rdb, robj *obj) { +ssize_t rdbSaveStringObject(rio *rdb, robj *obj) { /* Avoid to decode the object, then encode it again, if the * object is already integer encoded. */ if (obj->encoding == OBJ_ENCODING_INT) { @@ -535,12 +535,12 @@ int rdbSaveDoubleValue(rio *rdb, double val) { } else { #if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL) /* Check if the float is in a safe range to be casted into a - * PORT_LONGLONG. We are assuming that PORT_LONGLONG is 64 bit here. + * long long. We are assuming that long long is 64 bit here. * Also we are assuming that there are no implementations around where * double has precision < 52 bit. * * Under this assumptions we test if a double is inside an interval - * where casting to PORT_LONGLONG is safe. Then using two castings we + * where casting to long long is safe. Then using two castings we * make sure the decimal part is zero. If all this is true we use * integer printing function that is much faster. */ double min = -4503599627370495; /* (2^52)-1 */ @@ -707,7 +707,7 @@ ssize_t rdbSaveObject(rio *rdb, robj *o) { dictIterator *di = dictGetIterator(set); dictEntry *de; - if ((n = rdbSaveLen(rdb,(uint32_t)dictSize(set))) == -1) return -1; WIN_PORT_FIX /* cast (uint32_t) */ + if ((n = rdbSaveLen(rdb,dictSize(set))) == -1) return -1; nwritten += n; while((de = dictNext(di)) != NULL) { @@ -773,7 +773,7 @@ ssize_t rdbSaveObject(rio *rdb, robj *o) { dictIterator *di = dictGetIterator(o->ptr); dictEntry *de; - if ((n = rdbSaveLen(rdb,(uint32_t)dictSize((dict*)o->ptr))) == -1) return -1; WIN_PORT_FIX /* cast (uint32_t) */ + if ((n = rdbSaveLen(rdb,dictSize((dict*)o->ptr))) == -1) return -1; nwritten += n; while((de = dictNext(di)) != NULL) { @@ -865,12 +865,12 @@ ssize_t rdbSaveAuxField(rio *rdb, void *key, size_t keylen, void *val, size_t va /* Wrapper for rdbSaveAuxField() used when key/val length can be obtained * with strlen(). */ -int rdbSaveAuxFieldStrStr(rio *rdb, char *key, char *val) { +ssize_t rdbSaveAuxFieldStrStr(rio *rdb, char *key, char *val) { return rdbSaveAuxField(rdb,key,strlen(key),val,strlen(val)); } -/* Wrapper for strlen(key) + integer type (up to PORT_LONGLONG range). */ -int rdbSaveAuxFieldStrInt(rio *rdb, char *key, PORT_LONGLONG val) { +/* Wrapper for strlen(key) + integer type (up to long long range). */ +ssize_t rdbSaveAuxFieldStrInt(rio *rdb, char *key, PORT_LONGLONG val) { char buf[LONG_STR_SIZE]; int vlen = ll2string(buf,sizeof(buf),val); return rdbSaveAuxField(rdb,key,strlen(key),buf,vlen); @@ -1126,7 +1126,7 @@ int rdbSaveBackground(char *filename, rdbSaveInfo *rsi) { #endif /* Parent */ server.stat_fork_time = ustime()-start; - server.stat_fork_rate = (double) zmalloc_used_memory() * 1000000 / server.stat_fork_time / (1024*1024*1024); /* GB per second. */ + server.stat_fork_rate = (double) (zmalloc_used_memory() * 1000000 / server.stat_fork_time / (1024*1024*1024)); /* GB per second. */ latencyAddSampleIfNeeded("fork",server.stat_fork_time/1000); if (childpid == -1) { closeChildInfoPipe(); @@ -1685,15 +1685,15 @@ int rdbLoadRio(rio *rdb, rdbSaveInfo *rsi, int loading_aof) { if (rioRead(rdb,&cksum,8) == 0) goto eoferr; if (server.rdb_checksum) { - memrev64ifbe(&cksum); - if (cksum == 0) { - serverLog(LL_WARNING,"RDB file was saved with checksum disabled: no check performed."); - } else if (cksum != expected) { - serverLog(LL_WARNING,"Wrong RDB checksum. Aborting now."); - rdbExitReportCorruptRDB("RDB CRC error"); + memrev64ifbe(&cksum); + if (cksum == 0) { + serverLog(LL_WARNING,"RDB file was saved with checksum disabled: no check performed."); + } else if (cksum != expected) { + serverLog(LL_WARNING,"Wrong RDB checksum. Aborting now."); + rdbExitReportCorruptRDB("RDB CRC error"); + } } } - } return C_OK; eoferr: /* unexpected end of file is handled here with a fatal exit */ @@ -2017,7 +2017,7 @@ int rdbSaveToSlavesSockets(rdbSaveInfo *rsi) { closeChildInfoPipe(); } else { server.stat_fork_time = ustime()-start; - server.stat_fork_rate = (double) zmalloc_used_memory() * 1000000 / server.stat_fork_time / (1024*1024*1024); /* GB per second. */ + server.stat_fork_rate = (double) (zmalloc_used_memory() * 1000000 / server.stat_fork_time / (1024*1024*1024)); /* GB per second. */ latencyAddSampleIfNeeded("fork",server.stat_fork_time/1000); serverLog(LL_NOTICE,"Background RDB transfer started by pid %d", diff --git a/src/rdb.h b/src/rdb.h index 6a34fee5..3ec06d2e 100644 --- a/src/rdb.h +++ b/src/rdb.h @@ -137,9 +137,9 @@ ssize_t rdbSaveObject(rio *rdb, robj *o); size_t rdbSavedObjectLen(robj *o); robj *rdbLoadObject(int type, rio *rdb); void backgroundSaveDoneHandler(int exitcode, int bysignal); -int rdbSaveKeyValuePair(rio *rdb, robj *key, robj *val, PORT_LONGLONG expiretime, PORT_LONGLONG now); +int rdbSaveKeyValuePair(rio *rdb, robj *key, robj *val, PORT_LONGLONG expiretime); robj *rdbLoadStringObject(rio *rdb); -int rdbSaveStringObject(rio *rdb, robj *obj); +ssize_t rdbSaveStringObject(rio *rdb, robj *obj); ssize_t rdbSaveRawString(rio *rdb, unsigned char *s, size_t len); void *rdbGenericLoadStringObject(rio *rdb, int flags, size_t *lenptr); int rdbSaveBinaryDoubleValue(rio *rdb, double val); diff --git a/src/redis-benchmark.c b/src/redis-benchmark.c index 24a79d26..43515d88 100644 --- a/src/redis-benchmark.c +++ b/src/redis-benchmark.c @@ -349,6 +349,7 @@ static void writeHandler(aeEventLoop *el, int fd, void *privdata, int mask) { return; } #else + ssize_t nwritten = write(c->context->fd,ptr,sdslen(c->obuf)-c->written); if (nwritten == -1) { if (errno != EPIPE) fprintf(stderr, "Writing to socket: %s\n", strerror(errno)); @@ -695,7 +696,7 @@ int showThroughput(struct aeEventLoop *eventLoop, PORT_LONGLONG id, void *client UNUSED(id); UNUSED(clientData); - if (config.liveclients == 0) { + if (config.liveclients == 0 && config.requests_finished != config.requests) { fprintf(stderr,"All clients disconnected... aborting.\n"); exit(1); } diff --git a/src/redis-check-aof.c b/src/redis-check-aof.c index 03e09e2a..167ac3c3 100644 --- a/src/redis-check-aof.c +++ b/src/redis-check-aof.c @@ -33,17 +33,10 @@ #include "Win32_Interop/win32_types.h" #include "Win32_Interop/Win32_Error.h" #include "Win32_Interop/win32fixes.h" -#include "zmalloc.h" #endif #include "server.h" -#include "fmacros.h" -#include -#include -#include -POSIX_ONLY(#include ) #include -#include "config.h" #ifdef _WIN32 #define strcasecmp _stricmp @@ -60,8 +53,8 @@ static char error[1024]; static off_t epos; int consumeNewline(char *buf) { - if (strncmp(buf, "\r\n", 2) != 0) { - ERROR("Expected \\r\\n, got: %02x%02x", buf[0], buf[1]); + if (strncmp(buf,"\r\n",2) != 0) { + ERROR("Expected \\r\\n, got: %02x%02x",buf[0],buf[1]); return 0; } return 1; @@ -70,24 +63,24 @@ int consumeNewline(char *buf) { int readLong(FILE *fp, char prefix, PORT_LONG *target) { char buf[128], *eptr; epos = ftello(fp); - if (fgets(buf, sizeof(buf), fp) == NULL) { + if (fgets(buf,sizeof(buf),fp) == NULL) { return 0; } if (buf[0] != prefix) { - ERROR("Expected prefix '%c', got: '%c'", prefix, buf[0]); + ERROR("Expected prefix '%c', got: '%c'",prefix,buf[0]); return 0; } - *target = strtol(buf + 1, &eptr, 10); + *target = strtol(buf+1,&eptr,10); return consumeNewline(eptr); } int readBytes(FILE *fp, char *target, PORT_LONG length) { PORT_LONG real; epos = ftello(fp); - real = (PORT_LONG) fread(target, 1, length, fp); + real = (PORT_LONG)fread(target,1,length,fp); if (real != length) { - ERROR("Expected to read %Id bytes, got %Id bytes", length, real); WIN_PORT_FIX /* %ld -> %Id */ - return 0; + ERROR("Expected to read %Id bytes, got %Id bytes",length,real); WIN_PORT_FIX /* %ld -> %Id */ + return 0; } return 1; } @@ -95,25 +88,25 @@ int readBytes(FILE *fp, char *target, PORT_LONG length) { int readString(FILE *fp, char** target) { PORT_LONG len; *target = NULL; - if (!readLong(fp, '$', &len)) { + if (!readLong(fp,'$',&len)) { return 0; } /* Increase length to also consume \r\n */ len += 2; - *target = (char*) zmalloc(len); - if (!readBytes(fp, *target, len)) { + *target = (char*)zmalloc(len); + if (!readBytes(fp,*target,len)) { return 0; } - if (!consumeNewline(*target + len - 2)) { + if (!consumeNewline(*target+len-2)) { return 0; } - (*target)[len - 2] = '\0'; + (*target)[len-2] = '\0'; return 1; } int readArgc(FILE *fp, PORT_LONG *target) { - return readLong(fp, '*', target); + return readLong(fp,'*',target); } off_t process(FILE *fp) { @@ -122,20 +115,19 @@ off_t process(FILE *fp) { int i, multi = 0; char *str; - while (1) { - if (!multi) pos = (off_t) ftello(fp); + while(1) { + if (!multi) pos = ftello(fp); if (!readArgc(fp, &argc)) break; for (i = 0; i < argc; i++) { - if (!readString(fp, &str)) break; + if (!readString(fp,&str)) break; if (i == 0) { if (strcasecmp(str, "multi") == 0) { if (multi++) { ERROR("Unexpected MULTI"); break; } - } - else if (strcasecmp(str, "exec") == 0) { + } else if (strcasecmp(str, "exec") == 0) { if (--multi) { ERROR("Unexpected EXEC"); break; @@ -174,19 +166,16 @@ int redis_check_aof_main(int argc, char **argv) { if (argc < 2) { printf("Usage: %s [--fix] \n", argv[0]); exit(1); - } - else if (argc == 2) { + } else if (argc == 2) { filename = argv[1]; - } - else if (argc == 3) { - if (strcmp(argv[1], "--fix") != 0) { + } else if (argc == 3) { + if (strcmp(argv[1],"--fix") != 0) { printf("Invalid argument: %s\n", argv[1]); exit(1); } filename = argv[2]; fix = 1; - } - else { + } else { printf("Invalid arguments\n"); exit(1); } @@ -198,7 +187,7 @@ int redis_check_aof_main(int argc, char **argv) { } struct redis_stat sb; - if (redis_fstat(fileno(fp), &sb) == -1) { + if (redis_fstat(fileno(fp),&sb) == -1) { printf("Cannot stat file: %s\n", filename); exit(1); } @@ -213,54 +202,50 @@ int redis_check_aof_main(int argc, char **argv) { * is the case, start processing the RDB part. */ if (size >= 8) { /* There must be at least room for the RDB header. */ char sig[5]; - int has_preamble = fread(sig, sizeof(sig), 1, fp) == 1 && - memcmp(sig, "REDIS", sizeof(sig)) == 0; + int has_preamble = fread(sig,sizeof(sig),1,fp) == 1 && + memcmp(sig,"REDIS",sizeof(sig)) == 0; rewind(fp); if (has_preamble) { printf("The AOF appears to start with an RDB preamble.\n" - "Checking the RDB preamble to start:\n"); - if (redis_check_rdb_main(argc, argv, fp) == C_ERR) { + "Checking the RDB preamble to start:\n"); + if (redis_check_rdb_main(argc,argv,fp) == C_ERR) { printf("RDB preamble of AOF file is not sane, aborting.\n"); exit(1); - } - else { + } else { printf("RDB preamble is OK, proceeding with AOF tail...\n"); } } } off_t pos = process(fp); - off_t diff = size - pos; + off_t diff = size-pos; printf("AOF analyzed: size=%lld, ok_up_to=%lld, diff=%lld\n", (PORT_LONGLONG) size, (PORT_LONGLONG) pos, (PORT_LONGLONG) diff); if (diff > 0) { if (fix) { char buf[2]; - printf("This will shrink the AOF from %lld bytes, with %lld bytes, to %lld bytes\n", (PORT_LONGLONG) size, (PORT_LONGLONG) diff, (PORT_LONGLONG) pos); + printf("This will shrink the AOF from %lld bytes, with %lld bytes, to %lld bytes\n", (PORT_LONGLONG)size, (PORT_LONGLONG)diff, (PORT_LONGLONG)pos); printf("Continue? [y/N]: "); - if (fgets(buf, sizeof(buf), stdin) == NULL || - strncasecmp(buf, "y", 1) != 0) { - printf("Aborting...\n"); - exit(1); + if (fgets(buf,sizeof(buf),stdin) == NULL || + strncasecmp(buf,"y",1) != 0) { + printf("Aborting...\n"); + exit(1); } if (ftruncate(fileno(fp), pos) == -1) { printf("Failed to truncate AOF\n"); exit(1); - } - else { + } else { printf("Successfully truncated AOF\n"); } - } - else { + } else { printf("AOF is not valid. " - "Use the --fix option to try fixing it.\n"); + "Use the --fix option to try fixing it.\n"); exit(1); } - } - else { + } else { printf("AOF is valid\n"); } fclose(fp); - return 0; -} \ No newline at end of file + exit(0); +} diff --git a/src/redis-check-rdb.c b/src/redis-check-rdb.c index 688b8ade..ff3fb94a 100644 --- a/src/redis-check-rdb.c +++ b/src/redis-check-rdb.c @@ -53,10 +53,10 @@ struct { rio *rio; robj *key; /* Current key we are reading. */ int key_type; /* Current key type if != -1. */ - PORT_ULONG keys; /* Number of keys processed. */ WIN_PORT_FIX - PORT_ULONG expires; /* Number of keys with an expire. */ WIN_PORT_FIX - PORT_ULONG already_expired; /* Number of keys already expired. */ WIN_PORT_FIX - int doing; /* The state while reading the RDB. */ + PORT_ULONG keys; /* Number of keys processed. */ WIN_PORT_FIX + PORT_ULONG expires; /* Number of keys with an expire. */ WIN_PORT_FIX + PORT_ULONG already_expired; /* Number of keys already expired. */ WIN_PORT_FIX + int doing; /* The state while reading the RDB. */ int error_set; /* True if error is populated. */ char error[1024]; } rdbstate; @@ -103,8 +103,8 @@ char *rdb_type_string[] = { /* Show a few stats collected into 'rdbstate' */ void rdbShowGenericInfo(void) { printf("[info] %Iu keys read\n", rdbstate.keys); WIN_PORT_FIX /* %lu -> %Iu */ - printf("[info] %Iu expires\n", rdbstate.expires); WIN_PORT_FIX /* %lu -> %Iu */ - printf("[info] %Iu already expired\n", rdbstate.already_expired); WIN_PORT_FIX /* %lu -> %Iu */ + printf("[info] %Iu expires\n", rdbstate.expires); WIN_PORT_FIX /* %lu -> %Iu */ + printf("[info] %Iu already expired\n", rdbstate.already_expired); WIN_PORT_FIX /* %lu -> %Iu */ } /* Called on RDB errors. Provides details about the RDB and the offset @@ -125,13 +125,13 @@ void rdbCheckError(const char *fmt, ...) { rdb_check_doing_string[rdbstate.doing]); if (rdbstate.key) printf("[additional info] Reading key '%s'\n", - (char*) rdbstate.key->ptr); + (char*)rdbstate.key->ptr); if (rdbstate.key_type != -1) printf("[additional info] Reading type %d (%s)\n", rdbstate.key_type, - ((unsigned) rdbstate.key_type < - sizeof(rdb_type_string) / sizeof(char*)) ? - rdb_type_string[rdbstate.key_type] : "unknown"); + ((unsigned)rdbstate.key_type < + sizeof(rdb_type_string)/sizeof(char*)) ? + rdb_type_string[rdbstate.key_type] : "unknown"); rdbShowGenericInfo(); } @@ -200,23 +200,23 @@ int redis_check_rdb(char *rdbfilename, FILE *fp) { int closefile = (fp == NULL); if (fp == NULL && (fp = fopen(rdbfilename, IF_WIN32("rb", "r"))) == NULL) return 1; - rioInitWithFile(&rdb, fp); + rioInitWithFile(&rdb,fp); rdbstate.rio = &rdb; rdb.update_cksum = rdbLoadProgressCallback; - if (rioRead(&rdb, buf, 9) == 0) goto eoferr; + if (rioRead(&rdb,buf,9) == 0) goto eoferr; buf[9] = '\0'; - if (memcmp(buf, "REDIS", 5) != 0) { + if (memcmp(buf,"REDIS",5) != 0) { rdbCheckError("Wrong signature trying to load DB from file"); - return 1; + goto err; } - rdbver = atoi(buf + 5); + rdbver = atoi(buf+5); if (rdbver < 1 || rdbver > RDB_VERSION) { - rdbCheckError("Can't handle RDB format version %d", rdbver); - return 1; + rdbCheckError("Can't handle RDB format version %d",rdbver); + goto err; } startLoading(fp); - while (1) { + while(1) { robj *key, *val; expiretime = -1; @@ -237,8 +237,7 @@ int redis_check_rdb(char *rdbfilename, FILE *fp) { /* the EXPIRETIME opcode specifies time in seconds, so convert * into milliseconds. */ expiretime *= 1000; - } - else if (type == RDB_OPCODE_EXPIRETIME_MS) { + } else if (type == RDB_OPCODE_EXPIRETIME_MS) { /* EXPIRETIME_MS: milliseconds precision expire times introduced * with RDB v3. Like EXPIRETIME but no with more precision. */ rdbstate.doing = RDB_CHECK_DOING_READ_EXPIRE; @@ -246,31 +245,27 @@ int redis_check_rdb(char *rdbfilename, FILE *fp) { /* We read the time so we need to read the object type again. */ rdbstate.doing = RDB_CHECK_DOING_READ_TYPE; if ((type = rdbLoadType(&rdb)) == -1) goto eoferr; - } - else if (type == RDB_OPCODE_EOF) { + } else if (type == RDB_OPCODE_EOF) { /* EOF: End of file, exit the main loop. */ break; - } - else if (type == RDB_OPCODE_SELECTDB) { + } else if (type == RDB_OPCODE_SELECTDB) { /* SELECTDB: Select the specified database. */ rdbstate.doing = RDB_CHECK_DOING_READ_LEN; - if ((dbid = rdbLoadLen(&rdb, NULL)) == RDB_LENERR) + if ((dbid = rdbLoadLen(&rdb,NULL)) == RDB_LENERR) goto eoferr; rdbCheckInfo("Selecting DB ID %d", dbid); continue; /* Read type again. */ - } - else if (type == RDB_OPCODE_RESIZEDB) { + } else if (type == RDB_OPCODE_RESIZEDB) { /* RESIZEDB: Hint about the size of the keys in the currently * selected data base, in order to avoid useless rehashing. */ uint64_t db_size, expires_size; rdbstate.doing = RDB_CHECK_DOING_READ_LEN; - if ((db_size = rdbLoadLen(&rdb, NULL)) == RDB_LENERR) + if ((db_size = rdbLoadLen(&rdb,NULL)) == RDB_LENERR) goto eoferr; - if ((expires_size = rdbLoadLen(&rdb, NULL)) == RDB_LENERR) + if ((expires_size = rdbLoadLen(&rdb,NULL)) == RDB_LENERR) goto eoferr; continue; /* Read type again. */ - } - else if (type == RDB_OPCODE_AUX) { + } else if (type == RDB_OPCODE_AUX) { /* AUX: generic string-string fields. Use to add state to RDB * which is backward compatible. Implementations of RDB loading * are requierd to skip AUX fields they don't understand. @@ -282,15 +277,14 @@ int redis_check_rdb(char *rdbfilename, FILE *fp) { if ((auxval = rdbLoadStringObject(&rdb)) == NULL) goto eoferr; rdbCheckInfo("AUX FIELD %s = '%s'", - (char*) auxkey->ptr, (char*) auxval->ptr); + (char*)auxkey->ptr, (char*)auxval->ptr); decrRefCount(auxkey); decrRefCount(auxval); continue; /* Read type again. */ - } - else { + } else { if (!rdbIsObjectType(type)) { rdbCheckError("Invalid object type: %d", type); - return 1; + goto err; } rdbstate.key_type = type; } @@ -302,7 +296,7 @@ int redis_check_rdb(char *rdbfilename, FILE *fp) { rdbstate.keys++; /* Read value */ rdbstate.doing = RDB_CHECK_DOING_READ_OBJECT_VALUE; - if ((val = rdbLoadObject(type, &rdb)) == NULL) goto eoferr; + if ((val = rdbLoadObject(type,&rdb)) == NULL) goto eoferr; /* Check if the key already expired. This function is used when loading * an RDB file from disk, either at startup, or when an RDB was * received from the master. In the latter case, the master is @@ -321,15 +315,14 @@ int redis_check_rdb(char *rdbfilename, FILE *fp) { uint64_t cksum, expected = rdb.cksum; rdbstate.doing = RDB_CHECK_DOING_CHECK_SUM; - if (rioRead(&rdb, &cksum, 8) == 0) goto eoferr; + if (rioRead(&rdb,&cksum,8) == 0) goto eoferr; memrev64ifbe(&cksum); if (cksum == 0) { rdbCheckInfo("RDB file was saved with checksum disabled: no check performed."); - } - else if (cksum != expected) { + } else if (cksum != expected) { rdbCheckError("RDB CRC error"); - } - else { + goto err; + } else { rdbCheckInfo("Checksum OK"); } } @@ -340,10 +333,11 @@ int redis_check_rdb(char *rdbfilename, FILE *fp) { eoferr: /* unexpected end of file is handled here with a fatal exit */ if (rdbstate.error_set) { rdbCheckError(rdbstate.error); - } - else { + } else { rdbCheckError("Unexpected EOF reading RDB file"); } +err: + if (closefile) fclose(fp); return 1; } @@ -373,11 +367,11 @@ int redis_check_rdb_main(int argc, char **argv, FILE *fp) { rdbCheckMode = 1; rdbCheckInfo("Checking RDB file %s", argv[1]); POSIX_ONLY(rdbCheckSetupSignals();) - int retval = redis_check_rdb(argv[1], fp); + int retval = redis_check_rdb(argv[1],fp); if (retval == 0) { rdbCheckInfo("\\o/ RDB looks OK! \\o/"); rdbShowGenericInfo(); } if (fp) return (retval == 0) ? C_OK : C_ERR; exit(retval); -} \ No newline at end of file +} diff --git a/src/redis-cli.c b/src/redis-cli.c index a48ddee6..d696f646 100644 --- a/src/redis-cli.c +++ b/src/redis-cli.c @@ -91,12 +91,12 @@ #define REDIS_CLI_RCFILE_ENV "REDISCLI_RCFILE" #define REDIS_CLI_RCFILE_DEFAULT ".redisclirc" - /* --latency-dist palettes. */ +/* --latency-dist palettes. */ int spectrum_palette_color_size = 19; -int spectrum_palette_color[] = { 0,233,234,235,237,239,241,243,245,247,144,143,142,184,226,214,208,202,196 }; +int spectrum_palette_color[] = {0,233,234,235,237,239,241,243,245,247,144,143,142,184,226,214,208,202,196}; int spectrum_palette_mono_size = 13; -int spectrum_palette_mono[] = { 0,233,234,235,237,239,241,243,245,247,249,251,253 }; +int spectrum_palette_mono[] = {0,233,234,235,237,239,241,243,245,247,249,251,253}; /* The actual palette in use. */ int *spectrum_palette; @@ -227,8 +227,7 @@ static sds getDotfilePath(char *envoverride, char *dotfilename) { /* If the env is set, return it. */ dotPath = sdsnew(path); - } - else { + } else { #ifdef _WIN32 char *homeDrive = getenv("HOMEDRIVE"); char *homePath = getenv("HOMEPATH"); @@ -359,9 +358,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, ")"); } @@ -369,18 +368,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; @@ -388,7 +387,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]; @@ -405,7 +404,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. */ @@ -419,15 +418,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)); @@ -441,12 +440,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"; @@ -496,9 +495,9 @@ static void cliOutputHelp(int argc, char **argv) { cliOutputGenericHelp(); return; } else if (argc > 0 && argv[0][0] == '@') { - len = sizeof(commandGroups) / sizeof(char*); + 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; } @@ -515,15 +514,15 @@ 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 { if (group == help->group) { - cliOutputCommandHelp(help, 0); + cliOutputCommandHelp(help,0); } } } @@ -538,7 +537,7 @@ 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; @@ -549,11 +548,11 @@ static void completionCallback(const char *buf, linenoiseCompletions *lc) { 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); } } @@ -563,20 +562,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; @@ -584,26 +583,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; } @@ -615,12 +614,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; @@ -633,7 +632,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; @@ -652,24 +651,24 @@ static int cliConnect(int force) { } if (config.hostsocket == NULL) { - context = redisConnect(config.hostip, config.hostport); + 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; } /* Set aggressive KEEP_ALIVE socket option in the Redis context socket - * in order to prevent timeouts caused by the execution of PORT_LONG + * in order to prevent timeouts caused by the execution of long * commands. At the same time this improves the detection of real * errors. */ anetKeepAlive(NULL, context->fd, REDIS_CLI_KEEPALIVE_INTERVAL); @@ -685,36 +684,35 @@ 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]; @@ -722,35 +720,35 @@ static sds cliFormatReplyTTY(redisReply *r, char *prefix) { sds tmp; /* Calculate chars needed to represent the largest index */ - i = (unsigned int) r->elements; + i = 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; @@ -758,27 +756,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; } /* Helper 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; - - o = sdscatfmt(o, "\033[%i;%i;49m", bold, ccode); - o = sdscatlen(o, s, len); - o = sdscat(o, "\033[0m"); + 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"); return o; } @@ -787,17 +785,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) { @@ -809,8 +807,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: @@ -819,35 +817,33 @@ 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 = sdsCatColorizedLdbReply(out, r->str, r->len); - } - } - else { - out = sdscatlen(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,"%I64d",r->integer); WIN_PORT_FIX /* %lld -> %I64d */ 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; @@ -859,31 +855,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,"%I64d",r->integer); WIN_PORT_FIX /* %lld -> %I64d */ + 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; @@ -895,7 +891,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; @@ -914,14 +910,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; @@ -932,15 +928,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); @@ -951,25 +947,22 @@ 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); } @@ -977,13 +970,13 @@ static int cliReadReply(int output_raw_strings) { return REDIS_OK; } -static int cliSendCommand(int argc, char **argv, int repeat) { +static int cliSendCommand(int argc, char **argv, long repeat) { char *command = argv[0]; size_t *argvlen; 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; } @@ -991,58 +984,57 @@ 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-- > 0) { - redisAppendCommandArgv(context, argc, (const char**) argv, argvlen); + redisAppendCommandArgv(context,argc,(const char**)argv,argvlen); while (config.monitor_mode) { if (cliReadReply(output_raw) != REDIS_OK) exit(1); fflush(stdout); @@ -1067,14 +1059,12 @@ 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(); } } @@ -1093,26 +1083,25 @@ 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. */ } } @@ -1129,129 +1118,100 @@ 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)strtoll(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) { + fputs("Warning: Using a password with '-a' option on the command line interface may not be safe.\n", stderr); config.auth = argv[++i]; - } - else if (!strcmp(argv[i], "--raw")) { + } else if (!strcmp(argv[i],"-u") && !lastarg) { + parseRedisUri(argv[++i]); + } 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],"--hotkeys")) { + config.hotkeys = 1; + } 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; } @@ -1260,8 +1220,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; @@ -1271,15 +1231,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; } @@ -1287,73 +1247,73 @@ 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" - " -u Server URI.\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" - " --hotkeys Sample Redis keys looking for hot keys.\n" - " only works when maxmemory-policy is *lfu.\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" +" -u Server URI.\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" +" --hotkeys Sample Redis keys looking for hot keys.\n" +" only works when maxmemory-policy is *lfu.\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); @@ -1361,36 +1321,33 @@ 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; @@ -1407,19 +1364,18 @@ 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 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); } } @@ -1427,16 +1383,15 @@ 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]); @@ -1445,19 +1400,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); } @@ -1484,7 +1439,7 @@ 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) { @@ -1494,13 +1449,13 @@ static void repl(void) { } cliRefreshPrompt(); - while ((line = linenoise(context ? config.prompt : "not connected> ")) != NULL) { + while((line = linenoise(context ? config.prompt : "not connected> ")) != NULL) { if (line[0] != '\0') { PORT_LONG repeat = 1; int skipargs = 0; char *endptr = NULL; - argv = cliSplitArgs(line, &argc); + argv = cliSplitArgs(line,&argc); /* check if we have a repeat command option and * need to skip the first arg */ @@ -1522,8 +1477,8 @@ static void repl(void) { /* Won't save auth command in history file */ if (!(argv && argc > 0 && !strcasecmp(argv[0+skipargs], "auth"))) { - if (history) linenoiseHistoryAdd(line); - if (historyfile) linenoiseHistorySave(historyfile); + if (history) linenoiseHistoryAdd(line); + if (historyfile) linenoiseHistorySave(historyfile); } if (argv == NULL) { @@ -1531,12 +1486,12 @@ static void repl(void) { linenoiseFree(line); continue; } else if (argc > 0) { - if (strcasecmp(argv[0], "quit") == 0 || - strcasecmp(argv[0], "exit") == 0) + if (strcasecmp(argv[0],"quit") == 0 || + strcasecmp(argv[0],"exit") == 0) { exit(0); } else if (argv[0][0] == ':') { - cliSetPreferences(argv, argc, 1); + cliSetPreferences(argv,argc,1); sdsfreesplitres(argv,argc); linenoiseFree(line); continue; @@ -1559,7 +1514,7 @@ static void repl(void) { } else { PORT_LONGLONG start_time = mstime(), elapsed; - issueCommandRepeat(argc - skipargs, argv + skipargs, repeat); + issueCommandRepeat(argc-skipargs, argv+skipargs, repeat); /* If our debugging session ended, show the EVAL final * reply. */ @@ -1571,16 +1526,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); @@ -1591,9 +1546,9 @@ 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); + retval = issueCommand(argc+1, argv); } else { retval = issueCommand(argc, argv); } @@ -1613,13 +1568,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" ); } @@ -1629,27 +1584,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++) { @@ -1657,14 +1612,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 @@ -1673,16 +1628,14 @@ 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. */ } } @@ -1696,13 +1649,11 @@ 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); } } @@ -1713,8 +1664,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(); @@ -1722,50 +1673,46 @@ 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; } @@ -1779,7 +1726,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. */ @@ -1800,17 +1747,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. */ } @@ -1841,8 +1788,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; @@ -1884,14 +1831,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++; @@ -1904,10 +1851,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; } @@ -1919,8 +1866,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 @@ -1930,17 +1877,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; @@ -1951,7 +1898,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) { @@ -1960,21 +1907,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; @@ -1986,23 +1933,22 @@ 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)); @@ -2010,17 +1956,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); } @@ -2028,7 +1974,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); } @@ -2038,9 +1984,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; @@ -2057,19 +2003,19 @@ static void pipeMode(void) { 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) { @@ -2077,35 +2023,34 @@ 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--; @@ -2114,25 +2059,24 @@ 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; } } @@ -2143,7 +2087,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 @@ -2151,7 +2095,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; @@ -2160,18 +2104,16 @@ 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; } @@ -2185,9 +2127,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; @@ -2218,19 +2160,16 @@ 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); } @@ -2251,38 +2190,32 @@ 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 = 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); } @@ -2293,22 +2226,20 @@ static void getKeyTypes(redisReply *keys, int *types) { unsigned int i; /* Pipeline TYPE commands */ - for (i = 0; i < keys->elements; i++) { + for(i=0;ielements;i++) { redisAppendCommand(context, "TYPE %s", keys->element[i]->str); } /* Retrieve types */ - for (i = 0; i < keys->elements; i++) { - if (redisGetReply(context, (void**) &reply) != REDIS_OK) { + for(i=0;ielements;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); @@ -2322,16 +2253,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; i < keys->elements; i++) { + for(i=0;ielements;i++) { /* Skip keys that were deleted */ - if (types[i] == TYPE_NONE) + if(types[i]==TYPE_NONE) continue; redisAppendCommand(context, "%s %s", sizecmds[types[i]], @@ -2339,28 +2270,26 @@ static void getKeySizes(redisReply *keys, int *types, } /* Retreive sizes */ - for (i = 0; i < keys->elements; i++) { + for(i=0;ielements;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; } @@ -2369,14 +2298,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[TYPE_COUNT] = {0}, counts[TYPE_COUNT] = {0}, totalsize[TYPE_COUNT] = {0}; + PORT_ULONGLONG sampled = 0, total_keys, totlen=0, *sizes=NULL, it=0; + sds maxkeys[TYPE_COUNT] = {0}; + char *typename[] = {"string","list","set","hash","zset","stream","none"}; + char *typeunit[] = {"bytes","items","members","fields","members","entries",""}; 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 */ @@ -2388,9 +2317,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; i < TYPE_NONE; i++) { + 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 = keys->elements; } /* Retreive types and then sizes */ @@ -2423,8 +2352,8 @@ static void findBigKeys(void) { getKeySizes(keys, types, sizes); /* Now update our stats */ - for (i = 0; i < keys->elements; i++) { - if ((type = types[i]) == TYPE_NONE) + for(i=0;ielements;i++) { + if((type = types[i]) == TYPE_NONE) continue; totalsize[type] += sizes[i]; @@ -2432,15 +2361,15 @@ static void findBigKeys(void) { totlen += keys->element[i]->len; sampled++; - if (biggest[type] < sizes[i]) { + 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); } @@ -2450,48 +2379,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; i < TYPE_NONE; i++) { - if (sdslen(maxkeys[i]) > 0) { + for(i=0;i0) { 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; i < TYPE_NONE; i++) { + for(i=0;itype == REDIS_REPLY_ERROR) { printf("ERROR: %s\n", reply->str); exit(1); @@ -2703,8 +2629,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 */ @@ -2712,45 +2638,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); + /* Requests */ + 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"); @@ -2782,27 +2708,25 @@ 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); } @@ -2811,21 +2735,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 @@ -2843,58 +2767,58 @@ 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) { - case REDIS_REPLY_ERROR: - printf("%s\n", reply->str); - break; - case REDIS_REPLY_NIL: - misses++; - break; - default: - hits++; - break; - } + /* 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; + case REDIS_REPLY_NIL: + misses++; + break; + default: + hits++; + break; } } - - 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); + + 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); + } exit(0); } @@ -2906,9 +2830,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; @@ -2918,13 +2842,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; } @@ -2937,17 +2861,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; @@ -2957,7 +2881,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 " @@ -3029,7 +2953,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; @@ -3111,9 +3035,8 @@ 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); + return evalMode(argc,argv); + } else { + return noninteractive(argc,convertToSds(argc,argv)); } - else { - return noninteractive(argc, convertToSds(argc, argv)); - } -} \ No newline at end of file +} diff --git a/src/release.c b/src/release.c index d702ef4d..4e59c747 100644 --- a/src/release.c +++ b/src/release.c @@ -27,11 +27,12 @@ * POSSIBILITY OF SUCH DAMAGE. */ - /* Every time the Redis Git SHA1 or Dirty status changes only this small - * file is recompiled, as we access this information in all the other - * files using this functions. */ +/* Every time the Redis Git SHA1 or Dirty status changes only this small + * file is recompiled, as we access this information in all the other + * files using this functions. */ #include + #include "release.h" #include "version.h" #include "crc64.h" @@ -47,5 +48,5 @@ char *redisGitDirty(void) { uint64_t redisBuildId(void) { char *buildid = REDIS_VERSION REDIS_BUILD_ID REDIS_GIT_DIRTY REDIS_GIT_SHA1; - return crc64(0, (unsigned char*) buildid, strlen(buildid)); -} \ No newline at end of file + return crc64(0,(unsigned char*)buildid,strlen(buildid)); +} diff --git a/src/replication.c b/src/replication.c index db046a53..eac78b24 100644 --- a/src/replication.c +++ b/src/replication.c @@ -39,6 +39,7 @@ #endif #include "server.h" + POSIX_ONLY(#include ) POSIX_ONLY(#include ) #include @@ -1289,7 +1290,7 @@ void readSyncBulkPayload(aeEventLoop *el, int fd, void *privdata, int mask) { (nread == -1) ? wsa_strerror(errno) : "connection lost"); } #else - serverLog(LL_WARNING, "I/O error trying to sync with MASTER: %s", + serverLog(LL_WARNING,"I/O error trying to sync with MASTER: %s", (nread == -1) ? strerror(errno) : "connection lost"); #endif cancelReplicationHandshake(); @@ -1368,7 +1369,7 @@ void readSyncBulkPayload(aeEventLoop *el, int fd, void *privdata, int mask) { "any race", (PORT_LONG) server.rdb_child_pid); - IF_WIN32(AbortForkOperation(), kill(server.rdb_child_pid, SIGUSR1)); + IF_WIN32(AbortForkOperation(), kill(server.rdb_child_pid,SIGUSR1)); rdbRemoveTempFile(server.rdb_child_pid); } if (rename(server.repl_transfer_tmpfile,server.rdb_filename) == -1) { @@ -1464,7 +1465,7 @@ char *sendSynchronousCommand(int flags, int fd, ...) { } cmd = sdscatlen(cmd,"\r\n",2); va_end(ap); - + /* Transfer command to the server. */ if (syncWrite(fd,cmd,(ssize_t)sdslen(cmd),server.repl_syncio_timeout*1000) WIN_PORT_FIX /* cast (ssize_t) */ == -1) @@ -1951,7 +1952,7 @@ void syncWithMaster(aeEventLoop *el, int fd, void *privdata, int mask) { dfd = open(tmpfile,O_CREAT|O_WRONLY|O_EXCL|O_BINARY,_S_IREAD|_S_IWRITE); #else snprintf(tmpfile,256, - "temp-%d.%ld.rdb",(int)server.unixtime,(PORT_LONG int)getpid()); + "temp-%d.%ld.rdb",(int)server.unixtime,(long int)getpid()); dfd = open(tmpfile,O_CREAT|O_WRONLY|O_EXCL,0644); #endif if (dfd != -1) break; @@ -2086,7 +2087,6 @@ void replicationSetMaster(char *ip, int port) { * our own parameters, to later PSYNC with the new master. */ if (was_master) replicationCacheMasterUsingMyself(); server.repl_state = REPL_STATE_CONNECT; - server.repl_down_since = 0; } /* Cancel replication, setting the instance as a master itself. */ @@ -2155,14 +2155,14 @@ void slaveofCommand(client *c) { } else { PORT_LONG port; - if (c->flags & CLIENT_SLAVE) - { - /* If a client is already a replica they cannot run this command, - * because it involves flushing all replicas (including this - * client) */ - addReplyError(c,"Command is not valid when client is a replica."); - return; - } + if (c->flags & CLIENT_SLAVE) + { + /* If a client is already a replica they cannot run this command, + * because it involves flushing all replicas (including this + * client) */ + addReplyError(c, "Command is not valid when client is a replica."); + return; + } if ((getLongFromObjectOrReply(c, c->argv[2], &port, NULL) != C_OK)) return; @@ -2743,7 +2743,7 @@ void replicationCron(void) { #else if (write(slave->fd, "\n", 1) == -1) { #endif - /* Don't worry, it's just a ping. */ + /* Don't worry about socket errors, it's just a ping. */ } } } diff --git a/src/rio.c b/src/rio.c index 81a0e7db..1496d003 100644 --- a/src/rio.c +++ b/src/rio.c @@ -337,7 +337,7 @@ size_t rioWriteBulkString(rio *r, const char *buf, size_t len) { return nwritten+len+2; } -/* Write a PORT_LONGLONG value in format: "$\r\n\r\n". */ +/* Write a long long value in format: "$\r\n\r\n". */ size_t rioWriteBulkLongLong(rio *r, PORT_LONGLONG l) { char lbuf[32]; unsigned int llen; diff --git a/src/scripting.c b/src/scripting.c index 16716b37..3800d61c 100644 --- a/src/scripting.c +++ b/src/scripting.c @@ -1186,7 +1186,7 @@ sds luaCreateFunction(client *c, lua_State *lua, robj *body) { if (c != NULL) { addReplyErrorFormat(c, "Error compiling script (new function): %s\n", - lua_tostring(lua,-1)); + lua_tostring(lua,-1)); } lua_pop(lua,1); sdsfree(sha); @@ -1194,10 +1194,11 @@ sds luaCreateFunction(client *c, lua_State *lua, robj *body) { return NULL; } sdsfree(funcdef); + if (lua_pcall(lua,0,0,0)) { if (c != NULL) { - addReplyErrorFormat(c,"Error running script (new function): %s\n", - lua_tostring(lua,-1)); + addReplyErrorFormat(c,"Error running script (new function): %s\n", + lua_tostring(lua,-1)); } lua_pop(lua,1); sdsfree(sha); @@ -1209,7 +1210,7 @@ sds luaCreateFunction(client *c, lua_State *lua, robj *body) { * EVALSHA commands as EVAL using the original script. */ int retval = dictAdd(server.lua_scripts,sha,body); serverAssertWithInfo(c ? c : server.lua_client,NULL,retval == DICT_OK); - incrRefCount(body); + incrRefCount(body); return sha; } @@ -1636,7 +1637,7 @@ int ldbStartSession(client *c) { closeListeningSockets(0); } else { /* Parent */ - listAddNodeTail(ldb.children,(void*)(PORT_ULONG)cp); + listAddNodeTail(ldb.children,(void*)(unsigned long)cp); freeClientAsync(c); /* Close the client in the parent side. */ return 0; } @@ -1724,8 +1725,8 @@ void ldbKillForkedSessions(void) { listRewind(ldb.children,&li); while((ln = listNext(&li))) { - pid_t pid = (PORT_ULONG) ln->value; - serverLog(LL_WARNING,"Killing debugging session %ld",(PORT_LONG)pid); + pid_t pid = (unsigned long) ln->value; + serverLog(LL_WARNING,"Killing debugging session %ld",(long)pid); kill(pid,SIGKILL); } listRelease(ldb.children); diff --git a/src/sds.c b/src/sds.c index 749b78a2..9e640c66 100644 --- a/src/sds.c +++ b/src/sds.c @@ -472,7 +472,7 @@ int sdsll2str(char *s, PORT_LONGLONG value) { return (int)l; WIN_PORT_FIX /* cast (int) */ } -/* Identical sdsll2str(), but for PORT_ULONGLONG type. */ +/* Identical sdsll2str(), but for unsigned long long type. */ int sdsull2str(char *s, PORT_ULONGLONG v) { char *p, aux; size_t l; @@ -501,7 +501,7 @@ int sdsull2str(char *s, PORT_ULONGLONG v) { return (int)l; } -/* Create an sds string from a PORT_LONGLONG value. It is much faster than: +/* Create an sds string from a long long value. It is much faster than: * * sdscatprintf(sdsempty(),"%lld\n", value); */ @@ -587,20 +587,20 @@ sds sdscatprintf(sds s, const char *fmt, ...) { * %s - C String * %S - SDS string * %i - signed int - * %I - 64 bit signed integer (PORT_LONGLONG, int64_t) + * %I - 64 bit signed integer (long long, int64_t) * %u - unsigned int - * %U - 64 bit unsigned integer (PORT_ULONGLONG, uint64_t) + * %U - 64 bit unsigned integer (unsigned long long, uint64_t) * %% - Verbatim "%" character. */ sds sdscatfmt(sds s, char const *fmt, ...) { size_t initlen = sdslen(s); const char *f = fmt; - int i; + PORT_LONG i; va_list ap; va_start(ap,fmt); f = fmt; /* Next format specifier byte to process. */ - i = (int)initlen; /* Position of the next byte to write to dest str. */ + i = initlen; /* Position of the next byte to write to dest str. */ while(*f) { char next, *str; size_t l; @@ -741,9 +741,9 @@ void sdsrange(sds s, ssize_t start, ssize_t end) { } newlen = (start > end) ? 0 : (end-start)+1; if (newlen != 0) { - if (start >= (signed)len) { + if (start >= (ssize_t)len) { newlen = 0; - } else if (end >= (signed)len) { + } else if (end >= (ssize_t)len) { end = (int)len-1; WIN_PORT_FIX /* cast (int) */ newlen = (start > end) ? 0 : (end-start)+1; } @@ -757,14 +757,14 @@ void sdsrange(sds s, ssize_t start, ssize_t end) { /* Apply tolower() to every character of the sds string 's'. */ void sdstolower(sds s) { - int len = (int)sdslen(s), j; WIN_PORT_FIX /* cast (int) */ + size_t len = sdslen(s), j; for (j = 0; j < len; j++) s[j] = tolower(s[j]); } /* Apply toupper() to every character of the sds string 's'. */ void sdstoupper(sds s) { - int len = (int)sdslen(s), j; WIN_PORT_FIX /* cast (int) */ + size_t len = sdslen(s), j; for (j = 0; j < len; j++) s[j] = toupper(s[j]); } diff --git a/src/sds.h b/src/sds.h index 413b0c2e..cf48b72c 100644 --- a/src/sds.h +++ b/src/sds.h @@ -280,11 +280,11 @@ sds sdscatprintf(sds s, const char *fmt, ...); sds sdscatfmt(sds s, char const *fmt, ...); sds sdstrim(sds s, const char *cset); -void sdsrange(sds s, int start, int end); +void sdsrange(sds s, ssize_t start, ssize_t end); void sdsupdatelen(sds s); void sdsclear(sds s); int sdscmp(const sds s1, const sds s2); -sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count); +sds *sdssplitlen(const char *s, ssize_t len, const char *sep, int seplen, int *count); void sdsfreesplitres(sds *tokens, int count); void sdstolower(sds s); void sdstoupper(sds s); @@ -297,7 +297,7 @@ sds sdsjoinsds(sds *argv, int argc, const char *sep, size_t seplen); /* Low level functions exposed to the user API */ sds sdsMakeRoomFor(sds s, size_t addlen); -void sdsIncrLen(sds s,ssize_t incr); +void sdsIncrLen(sds s, ssize_t incr); sds sdsRemoveFreeSpace(sds s); size_t sdsAllocSize(sds s); void *sdsAllocPtr(sds s); diff --git a/src/sentinel.c b/src/sentinel.c index e5450da8..7819e9c2 100644 --- a/src/sentinel.c +++ b/src/sentinel.c @@ -258,8 +258,8 @@ struct sentinelState { int announce_port; /* Port that is gossiped to other sentinels if non zero. */ PORT_ULONG simfailure_flags; /* Failures simulation. */ - int deny_scripts_reconfig; /* Allow SENTINEL SET ... to change script - paths at runtime? */ + int deny_scripts_reconfig; /* Allow SENTINEL SET ... to change script + paths at runtime? */ } sentinel; /* A script execution job. */ @@ -456,7 +456,7 @@ dictType instancesDictType = { dictInstancesValDestructor /* val destructor */ }; -/* Instance runid (sds) -> votes (PORT_LONG casted to void*) +/* Instance runid (sds) -> votes (long casted to void*) * * This is useful into sentinelGetObjectiveLeader() function in order to * count the votes and understand who is the leader. */ @@ -875,7 +875,7 @@ void sentinelRunPendingScripts(void) { } else { sentinel.running_scripts++; sj->pid = pid; - sentinelEvent(LL_DEBUG,"+script-child",NULL,"%ld",(PORT_LONG)pid); + sentinelEvent(LL_DEBUG,"+script-child",NULL,"%ld",(long)pid); } #endif } @@ -954,11 +954,11 @@ void sentinelCollectTerminatedScripts(void) { if (WIFSIGNALED(statloc)) bysignal = WTERMSIG(statloc); sentinelEvent(LL_DEBUG,"-script-child",NULL,"%ld %d %d", - (PORT_LONG)pid, exitcode, bysignal); + (long)pid, exitcode, bysignal); ln = sentinelGetScriptListNodeByPid(pid); if (ln == NULL) { - serverLog(LL_WARNING,"wait3() returned a pid (%ld) we can't find in our scripts execution queue!", (PORT_LONG)pid); + serverLog(LL_WARNING,"wait3() returned a pid (%ld) we can't find in our scripts execution queue!", (long)pid); continue; } sj = ln->value; @@ -2738,7 +2738,7 @@ void sentinelSendPeriodicCommands(sentinelRedisInstance *ri) { * also have a limit of SENTINEL_MAX_PENDING_COMMANDS. We don't * want to use a lot of memory just because a link is not working * properly (note that anyway there is a redundant protection about this, - * that is, the link will be disconnected and reconnected if a PORT_LONG + * that is, the link will be disconnected and reconnected if a long * timeout condition is detected. */ if (ri->link->pending_commands >= SENTINEL_MAX_PENDING_COMMANDS * ri->link->refcount) return; @@ -2776,13 +2776,13 @@ void sentinelSendPeriodicCommands(sentinelRedisInstance *ri) { if (retval == C_OK) ri->link->pending_commands++; } - /* Send PING to all the three kinds of instances. */ + /* Send PING to all the three kinds of instances. */ if ((now - ri->link->last_pong_time) > ping_period && (now - ri->link->last_ping_time) > ping_period/2) { sentinelSendPing(ri); } - /* PUBLISH hello messages to all the three kinds of instances. */ + /* PUBLISH hello messages to all the three kinds of instances. */ if ((now - ri->last_pub_time) > SENTINEL_PUBLISH_PERIOD) { sentinelSendHello(ri); } @@ -3000,7 +3000,7 @@ void addReplyDictOfRedisInstances(client *c, dict *instances) { dictEntry *de; di = dictGetIterator(instances); - addReplyMultiBulkLen(c, (PORT_LONG) dictSize(instances)); WIN_PORT_FIX /* cast (PORT_LONG) */ + addReplyMultiBulkLen(c,(PORT_LONG)dictSize(instances)); WIN_PORT_FIX /* cast (PORT_LONG) */ while((de = dictNext(di)) != NULL) { sentinelRedisInstance *ri = dictGetVal(de); @@ -3450,7 +3450,7 @@ void sentinelRoleCommand(client *c) { addReplyMultiBulkLen(c,2); addReplyBulkCBuffer(c,"sentinel",8); - addReplyMultiBulkLen(c, (PORT_LONG) dictSize(sentinel.masters)); + addReplyMultiBulkLen(c,(PORT_LONG)dictSize(sentinel.masters)); di = dictGetIterator(sentinel.masters); while((de = dictNext(di)) != NULL) { diff --git a/src/server.c b/src/server.c index 17768070..b27c4f7e 100644 --- a/src/server.c +++ b/src/server.c @@ -133,7 +133,7 @@ volatile PORT_ULONG lru_clock; /* Server global current LRU time. */ * are not fast commands. */ struct redisCommand redisCommandTable[] = { - {"module",moduleCommand,-2,"as",0,NULL,1,1,1,0,0}, + {"module",moduleCommand,-2,"as",0,NULL,0,0,0,0,0}, {"get",getCommand,2,"rF",0,NULL,1,1,1,0,0}, {"set",setCommand,-3,"wm",0,NULL,1,1,1,0,0}, {"setnx",setnxCommand,3,"wmF",0,NULL,1,1,1,0,0}, @@ -331,32 +331,29 @@ void serverLogRaw(int level, const char *msg) { level &= 0xff; /* clear flags */ if (level < server.verbosity) return; - fp = log_to_stdout ? stdout : fopen(server.logfile, "a"); + fp = log_to_stdout ? stdout : fopen(server.logfile,"a"); if (!fp) return; if (rawmode) { - fprintf(fp, "%s", msg); - } - else { + fprintf(fp,"%s",msg); + } else { int off; struct timeval tv; int role_char; pid_t pid = getpid(); - gettimeofday(&tv, NULL); - off = strftime(buf, sizeof(buf), "%d %b %H:%M:%S.", localtime(&tv.tv_sec)); - snprintf(buf + off, sizeof(buf) - off, "%03d", (int) tv.tv_usec / 1000); + gettimeofday(&tv,NULL); + off = strftime(buf,sizeof(buf),"%d %b %H:%M:%S.",localtime(&tv.tv_sec)); + snprintf(buf+off,sizeof(buf)-off,"%03d",(int)tv.tv_usec/1000); if (server.sentinel_mode) { role_char = 'X'; /* Sentinel. */ - } - else if (pid != server.pid) { + } else if (pid != server.pid) { role_char = 'C'; /* RDB / AOF writing child. */ + } else { + role_char = (server.masterhost ? 'S':'M'); /* Slave or Master. */ } - else { - role_char = (server.masterhost ? 'S' : 'M'); /* Slave or Master. */ - } - fprintf(fp, "%d:%c %s %c %s\n", - (int) getpid(), role_char, buf, c[level], msg); + fprintf(fp,"%d:%c %s %c %s\n", + (int)getpid(),role_char, buf,c[level],msg); } fflush(fp); @@ -371,13 +368,13 @@ void serverLog(int level, const char *fmt, ...) { va_list ap; char msg[LOG_MAX_LEN]; - if ((level & 0xff) < server.verbosity) return; + if ((level&0xff) < server.verbosity) return; va_start(ap, fmt); vsnprintf(msg, sizeof(msg), fmt, ap); va_end(ap); - serverLogRaw(level, msg); + serverLogRaw(level,msg); } /* Log a fixed message without printf-alike capabilities, in a way that is @@ -391,19 +388,19 @@ void serverLogFromHandler(int level, const char *msg) { int log_to_stdout = server.logfile[0] == '\0'; char buf[64]; - if ((level & 0xff) < server.verbosity || (log_to_stdout && server.daemonize)) + if ((level&0xff) < server.verbosity || (log_to_stdout && server.daemonize)) return; fd = log_to_stdout ? STDOUT_FILENO : - open(server.logfile, O_APPEND | O_CREAT | O_WRONLY, 0644); + open(server.logfile, O_APPEND|O_CREAT|O_WRONLY, 0644); if (fd == -1) return; - ll2string(buf, sizeof(buf), getpid()); - if (write(fd, buf, strlen(buf)) == -1) goto err; - if (write(fd, ":signal-handler (", 17) == -1) goto err; - ll2string(buf, sizeof(buf), time(NULL)); - if (write(fd, buf, strlen(buf)) == -1) goto err; - if (write(fd, ") ", 2) == -1) goto err; - if (write(fd, msg, strlen(msg)) == -1) goto err; - if (write(fd, "\n", 1) == -1) goto err; + ll2string(buf,sizeof(buf),getpid()); + if (write(fd,buf,strlen(buf)) == -1) goto err; + if (write(fd,":signal-handler (",17) == -1) goto err; + ll2string(buf,sizeof(buf),time(NULL)); + if (write(fd,buf,strlen(buf)) == -1) goto err; + if (write(fd,") ",2) == -1) goto err; + if (write(fd,msg,strlen(msg)) == -1) goto err; + if (write(fd,"\n",1) == -1) goto err; err: if (!log_to_stdout) close(fd); } @@ -415,14 +412,14 @@ PORT_LONGLONG ustime(void) { PORT_LONGLONG ust; gettimeofday(&tv, NULL); - ust = ((PORT_LONGLONG) tv.tv_sec) * 1000000; + ust = ((PORT_LONGLONG)tv.tv_sec)*1000000; ust += tv.tv_usec; return ust; } /* Return the UNIX time in milliseconds */ PORT_LONGLONG mstime(void) { - return ustime() / 1000; + return ustime()/1000; } /* After an RDB dump or AOF rewrite we exit from children using _exit() instead of @@ -452,17 +449,17 @@ void dictVanillaFree(void *privdata, void *val) void dictListDestructor(void *privdata, void *val) { DICT_NOTUSED(privdata); - listRelease((list*) val); + listRelease((list*)val); } int dictSdsKeyCompare(void *privdata, const void *key1, - const void *key2) + const void *key2) { - int l1, l2; + int l1,l2; DICT_NOTUSED(privdata); - l1 = (int) sdslen((sds) key1); WIN_PORT_FIX /* cast (int) */ - l2 = (int) sdslen((sds) key2); WIN_PORT_FIX /* cast (int) */ + l1 = (int) sdslen((sds)key1); WIN_PORT_FIX /* cast (int) */ + l2 = (int) sdslen((sds)key2); WIN_PORT_FIX /* cast (int) */ if (l1 != l2) return 0; return memcmp(key1, key2, l1) == 0; } @@ -470,7 +467,7 @@ int dictSdsKeyCompare(void *privdata, const void *key1, /* A case insensitive version used for the command lookup table and other * places where case insensitive non binary-safe comparison is needed. */ int dictSdsKeyCaseCompare(void *privdata, const void *key1, - const void *key2) + const void *key2) { DICT_NOTUSED(privdata); @@ -493,38 +490,38 @@ void dictSdsDestructor(void *privdata, void *val) } int dictObjKeyCompare(void *privdata, const void *key1, - const void *key2) + const void *key2) { const robj *o1 = key1, *o2 = key2; - return dictSdsKeyCompare(privdata, o1->ptr, o2->ptr); + return dictSdsKeyCompare(privdata,o1->ptr,o2->ptr); } uint64_t dictObjHash(const void *key) { const robj *o = key; - return dictGenHashFunction(o->ptr, (int) sdslen((sds) o->ptr)); WIN_PORT_FIX /* cast (int) */ + return dictGenHashFunction(o->ptr, (int)sdslen((sds)o->ptr)); WIN_PORT_FIX /* cast (int) */ } uint64_t dictSdsHash(const void *key) { - return dictGenHashFunction((unsigned char*) key, (int) sdslen((char*) key)); WIN_PORT_FIX /* cast (int) */ + return dictGenHashFunction((unsigned char*)key, (int)sdslen((char*)key)); WIN_PORT_FIX /* cast (int) */ } uint64_t dictSdsCaseHash(const void *key) { - return dictGenCaseHashFunction((unsigned char*) key, (int) sdslen((char*) key)); WIN_PORT_FIX /* cast (int) */ + return dictGenCaseHashFunction((unsigned char*)key, (int)sdslen((char*)key)); WIN_PORT_FIX /* cast (int) */ } int dictEncObjKeyCompare(void *privdata, const void *key1, - const void *key2) + const void *key2) { robj *o1 = (robj*) key1, *o2 = (robj*) key2; int cmp; if (o1->encoding == OBJ_ENCODING_INT && o2->encoding == OBJ_ENCODING_INT) - return o1->ptr == o2->ptr; + return o1->ptr == o2->ptr; o1 = getDecodedObject(o1); o2 = getDecodedObject(o2); - cmp = dictSdsKeyCompare(privdata, o1->ptr, o2->ptr); + cmp = dictSdsKeyCompare(privdata,o1->ptr,o2->ptr); decrRefCount(o1); decrRefCount(o2); return cmp; @@ -534,22 +531,20 @@ uint64_t dictEncObjHash(const void *key) { robj *o = (robj*) key; if (sdsEncodedObject(o)) { - return dictGenHashFunction(o->ptr, (int) sdslen((sds) o->ptr)); WIN_PORT_FIX /* cast (int) */ - } - else { + return dictGenHashFunction(o->ptr, (int)sdslen((sds)o->ptr)); WIN_PORT_FIX /* cast (int) */ + } else { if (o->encoding == OBJ_ENCODING_INT) { char buf[32]; int len; - len = ll2string(buf, 32, (PORT_LONG) o->ptr); - return dictGenHashFunction((unsigned char*) buf, len); - } - else { + len = ll2string(buf,32,(PORT_LONG)o->ptr); + return dictGenHashFunction((unsigned char*)buf, len); + } else { uint64_t hash; o = getDecodedObject(o); - hash = dictGenHashFunction(o->ptr, (int) sdslen((sds) o->ptr)); WIN_PORT_FIX /* cast (int) */ - decrRefCount(o); + hash = dictGenHashFunction(o->ptr, (int)sdslen((sds)o->ptr)); WIN_PORT_FIX /* cast (int) */ + decrRefCount(o); return hash; } } @@ -711,7 +706,7 @@ int htNeedsResize(dict *dict) { size = dictSlots(dict); used = dictSize(dict); return (size > DICT_HT_INITIAL_SIZE && - (used * 100 / size < HASHTABLE_MIN_FILL)); + (used*100/size < HASHTABLE_MIN_FILL)); } /* If the percentage of used slots in the HT reaches HASHTABLE_MIN_FILL @@ -733,12 +728,12 @@ void tryResizeHashTables(int dbid) { int incrementallyRehash(int dbid) { /* Keys dictionary */ if (dictIsRehashing(server.db[dbid].dict)) { - dictRehashMilliseconds(server.db[dbid].dict, 1); + dictRehashMilliseconds(server.db[dbid].dict,1); return 1; /* already used our millisecond for this loop... */ } /* Expires */ if (dictIsRehashing(server.db[dbid].expires)) { - dictRehashMilliseconds(server.db[dbid].expires, 1); + dictRehashMilliseconds(server.db[dbid].expires,1); return 1; /* already used our millisecond for this loop... */ } return 0; @@ -766,7 +761,7 @@ void trackInstantaneousMetric(int metric, PORT_LONGLONG current_reading) { server.inst_metric[metric].last_sample_count; PORT_LONGLONG ops_sec; - ops_sec = t > 0 ? (ops * 1000 / t) : 0; + ops_sec = t > 0 ? (ops*1000/t) : 0; server.inst_metric[metric].samples[server.inst_metric[metric].idx] = ops_sec; @@ -791,7 +786,7 @@ PORT_LONGLONG getInstantaneousMetric(int metric) { * it gets called multiple times in a loop, so calling gettimeofday() for * each iteration would be costly without any actual gain. */ int clientsCronHandleTimeout(client *c, mstime_t now_ms) { - time_t now = now_ms / 1000; + time_t now = now_ms/1000; if (server.maxidletime && !(c->flags & CLIENT_SLAVE) && /* no timeout for slaves */ @@ -800,11 +795,10 @@ int clientsCronHandleTimeout(client *c, mstime_t now_ms) { !(c->flags & CLIENT_PUBSUB) && /* no timeout for Pub/Sub clients */ (now - c->lastinteraction > server.maxidletime)) { - serverLog(LL_VERBOSE, "Closing idle client"); + serverLog(LL_VERBOSE,"Closing idle client"); freeClient(c); return 1; - } - else if (c->flags & CLIENT_BLOCKED) { + } else if (c->flags & CLIENT_BLOCKED) { /* Blocked OPS timeout is handled with milliseconds resolution. * However note that the actual resolution is limited by * server.hz. */ @@ -813,8 +807,7 @@ int clientsCronHandleTimeout(client *c, mstime_t now_ms) { /* Handle blocking operation specific timeout. */ replyToBlockedClientTimedOut(c); unblockClient(c); - } - else if (server.cluster_enabled) { + } else if (server.cluster_enabled) { /* Cluster: handle unblock & redirect of clients blocked * into keys no longer served by this server. */ if (clusterRedirectBlockedClientIfNeeded(c)) @@ -836,8 +829,8 @@ int clientsCronResizeQueryBuffer(client *c) { * 1) Query buffer is > BIG_ARG and too big for latest peak. * 2) Client is inactive and the buffer is bigger than 1k. */ if (((querybuf_size > PROTO_MBULK_BIG_ARG) && - (querybuf_size / (c->querybuf_peak + 1)) > 2) || - (querybuf_size > 1024 && idletime > 2)) + (querybuf_size/(c->querybuf_peak+1)) > 2) || + (querybuf_size > 1024 && idletime > 2)) { /* Only resize the query buffer if it is actually wasting space. */ if (sdsavail(c->querybuf) > 1024) { @@ -856,8 +849,8 @@ void clientsCron(void) { * per call. Since this function is called server.hz times per second * we are sure that in the worst case we process all the clients in 1 * second. */ - int numclients = (int) listLength(server.clients); WIN_PORT_FIX /* cast (int) */ - int iterations = numclients / server.hz; + int numclients = (int)listLength(server.clients); WIN_PORT_FIX /* cast (int) */ + int iterations = numclients/server.hz; mstime_t now = mstime(); /* Process at least a few clients while we are at it, even if we need @@ -865,9 +858,9 @@ void clientsCron(void) { * of processing each client once per second. */ if (iterations < CLIENTS_CRON_MIN_ITERATIONS) iterations = (numclients < CLIENTS_CRON_MIN_ITERATIONS) ? - numclients : CLIENTS_CRON_MIN_ITERATIONS; + numclients : CLIENTS_CRON_MIN_ITERATIONS; - while (listLength(server.clients) && iterations--) { + while(listLength(server.clients) && iterations--) { client *c; listNode *head; @@ -880,7 +873,7 @@ void clientsCron(void) { /* The following functions do different service checks on the client. * The protocol is that they return non-zero if the client was * terminated. */ - if (clientsCronHandleTimeout(c, now)) continue; + if (clientsCronHandleTimeout(c,now)) continue; if (clientsCronResizeQueryBuffer(c)) continue; } } @@ -893,8 +886,7 @@ void databasesCron(void) { * as master will synthesize DELs for us. */ if (server.active_expire_enabled && server.masterhost == NULL) { activeExpireCycle(ACTIVE_EXPIRE_CYCLE_SLOW); - } - else if (server.masterhost != NULL) { + } else if (server.masterhost != NULL) { expireSlaveKeys(); } @@ -947,7 +939,7 @@ void databasesCron(void) { * a lot faster than calling time(NULL) */ void updateCachedTime(void) { time_t unixtime = time(NULL); - atomicSet(server.unixtime, unixtime); + atomicSet(server.unixtime,unixtime); server.mstime = mstime(); } @@ -984,11 +976,11 @@ int serverCron(struct aeEventLoop *eventLoop, PORT_LONGLONG id, void *clientData updateCachedTime(); run_with_period(100) { - trackInstantaneousMetric(STATS_METRIC_COMMAND, server.stat_numcommands); + trackInstantaneousMetric(STATS_METRIC_COMMAND,server.stat_numcommands); trackInstantaneousMetric(STATS_METRIC_NET_INPUT, - server.stat_net_input_bytes); + server.stat_net_input_bytes); trackInstantaneousMetric(STATS_METRIC_NET_OUTPUT, - server.stat_net_output_bytes); + server.stat_net_output_bytes); } /* We have just LRU_BITS bits per object for LRU information. @@ -1003,7 +995,7 @@ int serverCron(struct aeEventLoop *eventLoop, PORT_LONGLONG id, void *clientData * Note that you can change the resolution altering the * LRU_CLOCK_RESOLUTION define. */ PORT_ULONG lruclock = getLRUClock(); - atomicSet(server.lruclock, lruclock); + atomicSet(server.lruclock,lruclock); /* Record the max memory used since the server was started. */ if (zmalloc_used_memory() > server.stat_peak_memory) @@ -1016,7 +1008,7 @@ int serverCron(struct aeEventLoop *eventLoop, PORT_LONGLONG id, void *clientData * not ok doing so inside the signal handler. */ if (server.shutdown_asap) { if (prepareForShutdown(SHUTDOWN_NOFLAGS) == C_OK) exit(0); - serverLog(LL_WARNING, "SIGTERM received but errors trying to shut down the server, check the logs for more information"); + serverLog(LL_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information"); server.shutdown_asap = 0; } @@ -1029,7 +1021,7 @@ int serverCron(struct aeEventLoop *eventLoop, PORT_LONGLONG id, void *clientData used = dictSize(server.db[j].dict); vkeys = dictSize(server.db[j].expires); if (used || vkeys) { - serverLog(LL_VERBOSE, "DB %d: %lld keys (%lld volatile) in %lld slots HT.", j, used, vkeys, size); + serverLog(LL_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size); /* dictPrintStats(server.dict); */ } } @@ -1039,8 +1031,8 @@ int serverCron(struct aeEventLoop *eventLoop, PORT_LONGLONG id, void *clientData if (!server.sentinel_mode) { run_with_period(5000) { serverLog(LL_VERBOSE, - "%Iu clients connected (%Iu slaves), %Iu bytes in use", WIN_PORT_FIX /* %zu -> %Iu */ - listLength(server.clients) - listLength(server.slaves), + "%Iu clients connected (%Iu slaves), %Iu bytes in use", WIN_PORT_FIX /* %zu -> %Iu, %lu -> %Iu */ + listLength(server.clients)-listLength(server.slaves), listLength(server.slaves), zmalloc_used_memory()); } @@ -1089,81 +1081,78 @@ int serverCron(struct aeEventLoop *eventLoop, PORT_LONGLONG id, void *clientData int statloc; pid_t pid; - if ((pid = wait3(&statloc, WNOHANG, NULL)) != 0) { + if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) { int exitcode = WEXITSTATUS(statloc); int bysignal = 0; if (WIFSIGNALED(statloc)) bysignal = WTERMSIG(statloc); if (pid == -1) { - serverLog(LL_WARNING, "wait3() returned an error: %s. " + serverLog(LL_WARNING,"wait3() returned an error: %s. " "rdb_child_pid = %d, aof_child_pid = %d", strerror(errno), (int) server.rdb_child_pid, (int) server.aof_child_pid); - } - else if (pid == server.rdb_child_pid) { - backgroundSaveDoneHandler(exitcode, bysignal); + } else if (pid == server.rdb_child_pid) { + backgroundSaveDoneHandler(exitcode,bysignal); if (!bysignal && exitcode == 0) receiveChildInfo(); - } - else if (pid == server.aof_child_pid) { - backgroundRewriteDoneHandler(exitcode, bysignal); + } else if (pid == server.aof_child_pid) { + backgroundRewriteDoneHandler(exitcode,bysignal); if (!bysignal && exitcode == 0) receiveChildInfo(); - } - else { + } else { if (!ldbRemoveChild(pid)) { serverLog(LL_WARNING, "Warning, detected child with unmatched pid: %ld", - (PORT_LONG) pid); + (PORT_LONG)pid); } } updateDictResizePolicy(); closeChildInfoPipe(); } #endif - } - else { + } else { /* If there is not a background saving/rewrite in progress check if * we have to save/rewrite now. */ - for (j = 0; j < server.saveparamslen; j++) { - struct saveparam *sp = server.saveparams + j; + for (j = 0; j < server.saveparamslen; j++) { + struct saveparam *sp = server.saveparams+j; /* Save if we reached the given amount of changes, * the given amount of seconds, and if the latest bgsave was * successful or if, in case of an error, at least * CONFIG_BGSAVE_RETRY_DELAY seconds already elapsed. */ if (server.dirty >= sp->changes && - server.unixtime - server.lastsave > sp->seconds && - (server.unixtime - server.lastbgsave_try > - CONFIG_BGSAVE_RETRY_DELAY || - server.lastbgsave_status == C_OK)) + server.unixtime-server.lastsave > sp->seconds && + (server.unixtime-server.lastbgsave_try > + CONFIG_BGSAVE_RETRY_DELAY || + server.lastbgsave_status == C_OK)) { - serverLog(LL_NOTICE, "%d changes in %d seconds. Saving...", - sp->changes, (int) sp->seconds); + serverLog(LL_NOTICE,"%d changes in %d seconds. Saving...", + sp->changes, (int)sp->seconds); rdbSaveInfo rsi, *rsiptr; rsiptr = rdbPopulateSaveInfo(&rsi); - rdbSaveBackground(server.rdb_filename, rsiptr); + rdbSaveBackground(server.rdb_filename,rsiptr); break; } - } + } /* Trigger an AOF rewrite if needed. */ if (server.aof_state == AOF_ON && server.rdb_child_pid == -1 && - server.aof_child_pid == -1 && - server.aof_rewrite_perc && - server.aof_current_size > server.aof_rewrite_min_size) - { + server.aof_child_pid == -1 && + server.aof_rewrite_perc && + server.aof_current_size > server.aof_rewrite_min_size) + { PORT_LONGLONG base = server.aof_rewrite_base_size ? - server.aof_rewrite_base_size : 1; - PORT_LONGLONG growth = (server.aof_current_size * 100 / base) - 100; + server.aof_rewrite_base_size : 1; + PORT_LONGLONG growth = (server.aof_current_size*100/base) - 100; if (growth >= server.aof_rewrite_perc) { - serverLog(LL_NOTICE, "Starting automatic rewriting of AOF on %lld%% growth", growth); + serverLog(LL_NOTICE,"Starting automatic rewriting of AOF on %lld%% growth",growth); rewriteAppendOnlyFileBackground(); } - } + } } + /* AOF postponed flush: Try at every cron cycle if the slow fsync * completed. */ if (server.aof_flush_postponed_start) flushAppendOnlyFile(0); @@ -1211,17 +1200,17 @@ int serverCron(struct aeEventLoop *eventLoop, PORT_LONGLONG id, void *clientData * because we want to give priority to RDB savings for replication. */ if (server.rdb_child_pid == -1 && server.aof_child_pid == -1 && server.rdb_bgsave_scheduled && - (server.unixtime - server.lastbgsave_try > CONFIG_BGSAVE_RETRY_DELAY || - server.lastbgsave_status == C_OK)) + (server.unixtime-server.lastbgsave_try > CONFIG_BGSAVE_RETRY_DELAY || + server.lastbgsave_status == C_OK)) { rdbSaveInfo rsi, *rsiptr; rsiptr = rdbPopulateSaveInfo(&rsi); - if (rdbSaveBackground(server.rdb_filename, rsiptr) == C_OK) + if (rdbSaveBackground(server.rdb_filename,rsiptr) == C_OK) server.rdb_bgsave_scheduled = 0; } server.cronloops++; - return 1000 / server.hz; + return 1000/server.hz; } /* This function gets called every time Redis is entering the @@ -1252,9 +1241,9 @@ void beforeSleep(struct aeEventLoop *eventLoop) { if (server.get_ack_from_slaves) { robj *argv[3]; - argv[0] = createStringObject("REPLCONF", 8); - argv[1] = createStringObject("GETACK", 6); - argv[2] = createStringObject("*", 1); /* Not used argument. */ + argv[0] = createStringObject("REPLCONF",8); + argv[1] = createStringObject("GETACK",6); + argv[2] = createStringObject("*",1); /* Not used argument. */ replicationFeedSlaves(server.slaves, server.slaveseldb, argv, 3); decrRefCount(argv[0]); decrRefCount(argv[1]); @@ -1300,87 +1289,87 @@ void afterSleep(struct aeEventLoop *eventLoop) { void createSharedObjects(void) { int j; - shared.crlf = createObject(OBJ_STRING, sdsnew("\r\n")); - shared.ok = createObject(OBJ_STRING, sdsnew("+OK\r\n")); - shared.err = createObject(OBJ_STRING, sdsnew("-ERR\r\n")); - shared.emptybulk = createObject(OBJ_STRING, sdsnew("$0\r\n\r\n")); - shared.czero = createObject(OBJ_STRING, sdsnew(":0\r\n")); - shared.cone = createObject(OBJ_STRING, sdsnew(":1\r\n")); - shared.cnegone = createObject(OBJ_STRING, sdsnew(":-1\r\n")); - shared.nullbulk = createObject(OBJ_STRING, sdsnew("$-1\r\n")); - shared.nullmultibulk = createObject(OBJ_STRING, sdsnew("*-1\r\n")); - shared.emptymultibulk = createObject(OBJ_STRING, sdsnew("*0\r\n")); - shared.pong = createObject(OBJ_STRING, sdsnew("+PONG\r\n")); - shared.queued = createObject(OBJ_STRING, sdsnew("+QUEUED\r\n")); - shared.emptyscan = createObject(OBJ_STRING, sdsnew("*2\r\n$1\r\n0\r\n*0\r\n")); - shared.wrongtypeerr = createObject(OBJ_STRING, sdsnew( + shared.crlf = createObject(OBJ_STRING,sdsnew("\r\n")); + shared.ok = createObject(OBJ_STRING,sdsnew("+OK\r\n")); + shared.err = createObject(OBJ_STRING,sdsnew("-ERR\r\n")); + shared.emptybulk = createObject(OBJ_STRING,sdsnew("$0\r\n\r\n")); + shared.czero = createObject(OBJ_STRING,sdsnew(":0\r\n")); + shared.cone = createObject(OBJ_STRING,sdsnew(":1\r\n")); + shared.cnegone = createObject(OBJ_STRING,sdsnew(":-1\r\n")); + shared.nullbulk = createObject(OBJ_STRING,sdsnew("$-1\r\n")); + shared.nullmultibulk = createObject(OBJ_STRING,sdsnew("*-1\r\n")); + shared.emptymultibulk = createObject(OBJ_STRING,sdsnew("*0\r\n")); + shared.pong = createObject(OBJ_STRING,sdsnew("+PONG\r\n")); + shared.queued = createObject(OBJ_STRING,sdsnew("+QUEUED\r\n")); + shared.emptyscan = createObject(OBJ_STRING,sdsnew("*2\r\n$1\r\n0\r\n*0\r\n")); + shared.wrongtypeerr = createObject(OBJ_STRING,sdsnew( "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n")); - shared.nokeyerr = createObject(OBJ_STRING, sdsnew( + shared.nokeyerr = createObject(OBJ_STRING,sdsnew( "-ERR no such key\r\n")); - shared.syntaxerr = createObject(OBJ_STRING, sdsnew( + shared.syntaxerr = createObject(OBJ_STRING,sdsnew( "-ERR syntax error\r\n")); - shared.sameobjecterr = createObject(OBJ_STRING, sdsnew( + shared.sameobjecterr = createObject(OBJ_STRING,sdsnew( "-ERR source and destination objects are the same\r\n")); - shared.outofrangeerr = createObject(OBJ_STRING, sdsnew( + shared.outofrangeerr = createObject(OBJ_STRING,sdsnew( "-ERR index out of range\r\n")); - shared.noscripterr = createObject(OBJ_STRING, sdsnew( + shared.noscripterr = createObject(OBJ_STRING,sdsnew( "-NOSCRIPT No matching script. Please use EVAL.\r\n")); - shared.loadingerr = createObject(OBJ_STRING, sdsnew( + shared.loadingerr = createObject(OBJ_STRING,sdsnew( "-LOADING Redis is loading the dataset in memory\r\n")); - shared.slowscripterr = createObject(OBJ_STRING, sdsnew( + shared.slowscripterr = createObject(OBJ_STRING,sdsnew( "-BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.\r\n")); - shared.masterdownerr = createObject(OBJ_STRING, sdsnew( + shared.masterdownerr = createObject(OBJ_STRING,sdsnew( "-MASTERDOWN Link with MASTER is down and slave-serve-stale-data is set to 'no'.\r\n")); - shared.bgsaveerr = createObject(OBJ_STRING, sdsnew( + shared.bgsaveerr = createObject(OBJ_STRING,sdsnew( "-MISCONF Redis is configured to save RDB snapshots, but it is currently not able to persist on disk. Commands that may modify the data set are disabled, because this instance is configured to report errors during writes if RDB snapshotting fails (stop-writes-on-bgsave-error option). Please check the Redis logs for details about the RDB error.\r\n")); - shared.roslaveerr = createObject(OBJ_STRING, sdsnew( + shared.roslaveerr = createObject(OBJ_STRING,sdsnew( "-READONLY You can't write against a read only slave.\r\n")); - shared.noautherr = createObject(OBJ_STRING, sdsnew( + shared.noautherr = createObject(OBJ_STRING,sdsnew( "-NOAUTH Authentication required.\r\n")); - shared.oomerr = createObject(OBJ_STRING, sdsnew( + shared.oomerr = createObject(OBJ_STRING,sdsnew( "-OOM command not allowed when used memory > 'maxmemory'.\r\n")); - shared.execaborterr = createObject(OBJ_STRING, sdsnew( + shared.execaborterr = createObject(OBJ_STRING,sdsnew( "-EXECABORT Transaction discarded because of previous errors.\r\n")); - shared.noreplicaserr = createObject(OBJ_STRING, sdsnew( + shared.noreplicaserr = createObject(OBJ_STRING,sdsnew( "-NOREPLICAS Not enough good slaves to write.\r\n")); - shared.busykeyerr = createObject(OBJ_STRING, sdsnew( + shared.busykeyerr = createObject(OBJ_STRING,sdsnew( "-BUSYKEY Target key name already exists.\r\n")); - shared.space = createObject(OBJ_STRING, sdsnew(" ")); - shared.colon = createObject(OBJ_STRING, sdsnew(":")); - shared.plus = createObject(OBJ_STRING, sdsnew("+")); + shared.space = createObject(OBJ_STRING,sdsnew(" ")); + shared.colon = createObject(OBJ_STRING,sdsnew(":")); + shared.plus = createObject(OBJ_STRING,sdsnew("+")); for (j = 0; j < PROTO_SHARED_SELECT_CMDS; j++) { char dictid_str[64]; int dictid_len; - dictid_len = ll2string(dictid_str, sizeof(dictid_str), j); + dictid_len = ll2string(dictid_str,sizeof(dictid_str),j); shared.select[j] = createObject(OBJ_STRING, sdscatprintf(sdsempty(), "*2\r\n$6\r\nSELECT\r\n$%d\r\n%s\r\n", dictid_len, dictid_str)); } - shared.messagebulk = createStringObject("$7\r\nmessage\r\n", 13); - shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n", 14); - shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n", 15); - shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n", 18); - shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n", 17); - shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n", 19); - shared.del = createStringObject("DEL", 3); - shared.unlink = createStringObject("UNLINK", 6); - shared.rpop = createStringObject("RPOP", 4); - shared.lpop = createStringObject("LPOP", 4); - shared.lpush = createStringObject("LPUSH", 5); - shared.rpoplpush = createStringObject("RPOPLPUSH",9); + shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13); + shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14); + shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15); + shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18); + shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17); + shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19); + shared.del = createStringObject("DEL",3); + shared.unlink = createStringObject("UNLINK",6); + shared.rpop = createStringObject("RPOP",4); + shared.lpop = createStringObject("LPOP",4); + shared.lpush = createStringObject("LPUSH",5); + shared.rpoplpush = createStringObject("RPOPLPUSH",9); for (j = 0; j < OBJ_SHARED_INTEGERS; j++) { shared.integers[j] = - makeObjectShared(createObject(OBJ_STRING, (void*) (PORT_LONG) j)); + makeObjectShared(createObject(OBJ_STRING,(void*)(PORT_LONG)j)); shared.integers[j]->encoding = OBJ_ENCODING_INT; } for (j = 0; j < OBJ_SHARED_BULKHDR_LEN; j++) { shared.mbulkhdr[j] = createObject(OBJ_STRING, - sdscatprintf(sdsempty(), "*%d\r\n", j)); + sdscatprintf(sdsempty(),"*%d\r\n",j)); shared.bulkhdr[j] = createObject(OBJ_STRING, - sdscatprintf(sdsempty(), "$%d\r\n", j)); + sdscatprintf(sdsempty(),"$%d\r\n",j)); } /* The following two shared objects, minstring and maxstrings, are not * actually used for their value but as a special object meaning @@ -1393,11 +1382,11 @@ void createSharedObjects(void) { void initServerConfig(void) { int j; - pthread_mutex_init(&server.next_client_id_mutex, NULL); - pthread_mutex_init(&server.lruclock_mutex, NULL); - pthread_mutex_init(&server.unixtime_mutex, NULL); + pthread_mutex_init(&server.next_client_id_mutex,NULL); + pthread_mutex_init(&server.lruclock_mutex,NULL); + pthread_mutex_init(&server.unixtime_mutex,NULL); - getRandomHexChars(server.runid, CONFIG_RUN_ID_SIZE); + getRandomHexChars(server.runid,CONFIG_RUN_ID_SIZE); server.runid[CONFIG_RUN_ID_SIZE] = '\0'; changeReplicationId(); clearReplicationId2(); @@ -1416,7 +1405,7 @@ void initServerConfig(void) { server.dbnum = CONFIG_DEFAULT_DBNUM; server.verbosity = CONFIG_DEFAULT_VERBOSITY; WIN32_ONLY(setLogVerbosityLevel(server.verbosity);) - server.maxidletime = CONFIG_DEFAULT_CLIENT_TIMEOUT; + server.maxidletime = CONFIG_DEFAULT_CLIENT_TIMEOUT; server.tcpkeepalive = CONFIG_DEFAULT_TCP_KEEPALIVE; server.active_expire_enabled = 1; server.active_defrag_enabled = CONFIG_DEFAULT_ACTIVE_DEFRAG; @@ -1433,7 +1422,7 @@ void initServerConfig(void) { server.syslog_enabled = CONFIG_DEFAULT_SYSLOG_ENABLED; server.syslog_ident = zstrdup(CONFIG_DEFAULT_SYSLOG_IDENT); POSIX_ONLY(server.syslog_facility = LOG_LOCAL0;) - server.daemonize = CONFIG_DEFAULT_DAEMONIZE; + server.daemonize = CONFIG_DEFAULT_DAEMONIZE; server.supervised = 0; server.supervised_mode = SUPERVISED_NONE; server.aof_state = AOF_OFF; @@ -1490,9 +1479,9 @@ void initServerConfig(void) { server.cluster_announce_ip = CONFIG_DEFAULT_CLUSTER_ANNOUNCE_IP; server.cluster_announce_port = CONFIG_DEFAULT_CLUSTER_ANNOUNCE_PORT; server.cluster_announce_bus_port = CONFIG_DEFAULT_CLUSTER_ANNOUNCE_BUS_PORT; - server.migrate_cached_sockets = dictCreate(&migrateCacheDictType, NULL); + server.migrate_cached_sockets = dictCreate(&migrateCacheDictType,NULL); server.next_client_id = 1; /* Client IDs, start from 1 .*/ - server.loading_process_events_interval_bytes = (1024 * 1024 * 2); + server.loading_process_events_interval_bytes = (1024*1024*2); server.lazyfree_lazy_eviction = CONFIG_DEFAULT_LAZYFREE_LAZY_EVICTION; server.lazyfree_lazy_expire = CONFIG_DEFAULT_LAZYFREE_LAZY_EXPIRE; server.lazyfree_lazy_server_del = CONFIG_DEFAULT_LAZYFREE_LAZY_SERVER_DEL; @@ -1500,12 +1489,12 @@ void initServerConfig(void) { server.lua_time_limit = LUA_SCRIPT_TIME_LIMIT; unsigned int lruclock = getLRUClock(); - atomicSet(server.lruclock, lruclock); + atomicSet(server.lruclock,lruclock); resetServerSaveParams(); - appendServerSaveParams(60 * 60, 1); /* save after 1 hour and 1 change */ - appendServerSaveParams(300, 100); /* save after 5 minutes and 100 changes */ - appendServerSaveParams(60, 10000); /* save after 1 minute and 10000 changes */ + appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */ + appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */ + appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */ /* Replication related */ server.masterauth = NULL; @@ -1547,15 +1536,15 @@ void initServerConfig(void) { /* Double constants initialization */ R_Zero = 0.0; - R_PosInf = 1.0 / R_Zero; - R_NegInf = -1.0 / R_Zero; - R_Nan = R_Zero / R_Zero; + R_PosInf = 1.0/R_Zero; + R_NegInf = -1.0/R_Zero; + R_Nan = R_Zero/R_Zero; /* Command table -- we initiialize it here as it is part of the * initial configuration, since command names may be changed via * redis.conf using the rename-command directive. */ - server.commands = dictCreate(&commandTableDictType, NULL); - server.orig_commands = dictCreate(&commandTableDictType, NULL); + server.commands = dictCreate(&commandTableDictType,NULL); + server.orig_commands = dictCreate(&commandTableDictType,NULL); populateCommandTable(); server.delCommand = lookupCommandByCString("del"); server.multiCommand = lookupCommandByCString("multi"); @@ -1630,17 +1619,17 @@ int restartServer(int flags, mstime_t delay) { /* Close all file descriptors, with the exception of stdin, stdout, strerr * which are useful if we restart a Redis server which is not daemonized. */ - for (j = 3; j < (int) server.maxclients + 1024; j++) { + for (j = 3; j < (int)server.maxclients + 1024; j++) { /* Test the descriptor validity before closing it, otherwise * Valgrind issues a warning on close(). */ if (fcntl(j, IF_WIN32(1, F_GETFD), 0) != -1) close(j); } /* Execute the server with the original command line. */ - if (delay) usleep(delay * 1000); + if (delay) usleep(delay*1000); zfree(server.exec_argv[0]); server.exec_argv[0] = zstrdup(server.executable); - execve(server.executable, server.exec_argv, environ); + execve(server.executable,server.exec_argv,environ); /* If an error occurred here, there is nothing we can do, but exit. */ _exit(1); @@ -1658,15 +1647,14 @@ int restartServer(int flags, mstime_t delay) { * server.maxclients to the value that we can actually handle. */ void adjustOpenFilesLimit(void) { #ifndef _WIN32 - rlim_t maxfiles = server.maxclients + CONFIG_MIN_RESERVED_FDS; + rlim_t maxfiles = server.maxclients+CONFIG_MIN_RESERVED_FDS; struct rlimit limit; - if (getrlimit(RLIMIT_NOFILE, &limit) == -1) { - serverLog(LL_WARNING, "Unable to obtain the current NOFILE limit (%s), assuming 1024 and setting the max clients configuration accordingly.", + if (getrlimit(RLIMIT_NOFILE,&limit) == -1) { + serverLog(LL_WARNING,"Unable to obtain the current NOFILE limit (%s), assuming 1024 and setting the max clients configuration accordingly.", strerror(errno)); - server.maxclients = 1024 - CONFIG_MIN_RESERVED_FDS; - } - else { + server.maxclients = 1024-CONFIG_MIN_RESERVED_FDS; + } else { rlim_t oldlimit = limit.rlim_cur; /* Set the max number of files if the current limit is not enough @@ -1678,12 +1666,12 @@ void adjustOpenFilesLimit(void) { /* Try to set the file limit to match 'maxfiles' or at least * to the higher value supported less than maxfiles. */ bestlimit = maxfiles; - while (bestlimit > oldlimit) { + while(bestlimit > oldlimit) { rlim_t decr_step = 16; limit.rlim_cur = bestlimit; limit.rlim_max = bestlimit; - if (setrlimit(RLIMIT_NOFILE, &limit) != -1) break; + if (setrlimit(RLIMIT_NOFILE,&limit) != -1) break; setrlimit_error = errno; /* We failed to set file limit to 'bestlimit'. Try with a @@ -1698,12 +1686,12 @@ void adjustOpenFilesLimit(void) { if (bestlimit < maxfiles) { unsigned int old_maxclients = server.maxclients; - server.maxclients = bestlimit - CONFIG_MIN_RESERVED_FDS; + server.maxclients = bestlimit-CONFIG_MIN_RESERVED_FDS; /* maxclients is unsigned so may overflow: in order * to check if maxclients is now logically less than 1 * we test indirectly via bestlimit. */ if (bestlimit <= CONFIG_MIN_RESERVED_FDS) { - serverLog(LL_WARNING, "Your current 'ulimit -n' " + serverLog(LL_WARNING,"Your current 'ulimit -n' " "of %llu is not enough for the server to start. " "Please increase your open file limit to at least " "%llu. Exiting.", @@ -1711,21 +1699,20 @@ void adjustOpenFilesLimit(void) { (PORT_ULONGLONG) maxfiles); exit(1); } - serverLog(LL_WARNING, "You requested maxclients of %d " + serverLog(LL_WARNING,"You requested maxclients of %d " "requiring at least %llu max file descriptors.", old_maxclients, (PORT_ULONGLONG) maxfiles); - serverLog(LL_WARNING, "Server can't set maximum open files " + serverLog(LL_WARNING,"Server can't set maximum open files " "to %llu because of OS error: %s.", (PORT_ULONGLONG) maxfiles, strerror(setrlimit_error)); - serverLog(LL_WARNING, "Current maximum open files is %llu. " + serverLog(LL_WARNING,"Current maximum open files is %llu. " "maxclients has been reduced to %d to compensate for " "low ulimit. " "If you need higher maxclients increase 'ulimit -n'.", (PORT_ULONGLONG) bestlimit, server.maxclients); - } - else { - serverLog(LL_NOTICE, "Increased maximum number of open files " + } else { + serverLog(LL_NOTICE,"Increased maximum number of open files " "to %llu (it was originally set to %llu).", (PORT_ULONGLONG) maxfiles, (PORT_ULONGLONG) oldlimit); @@ -1739,13 +1726,13 @@ void adjustOpenFilesLimit(void) { * to the value of /proc/sys/net/core/somaxconn, or warn about it. */ void checkTcpBacklogSettings(void) { #ifdef HAVE_PROC_SOMAXCONN - FILE *fp = fopen("/proc/sys/net/core/somaxconn", "r"); + FILE *fp = fopen("/proc/sys/net/core/somaxconn","r"); char buf[1024]; if (!fp) return; - if (fgets(buf, sizeof(buf), fp) != NULL) { + if (fgets(buf,sizeof(buf),fp) != NULL) { int somaxconn = atoi(buf); if (somaxconn > 0 && somaxconn < server.tcp_backlog) { - serverLog(LL_WARNING, "WARNING: The TCP backlog setting of %d cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of %d.", server.tcp_backlog, somaxconn); + serverLog(LL_WARNING,"WARNING: The TCP backlog setting of %d cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of %d.", server.tcp_backlog, somaxconn); } } fclose(fp); @@ -1781,43 +1768,39 @@ int listenToPort(int port, int *fds, int *count) { int unsupported = 0; /* Bind * for both IPv6 and IPv4, we enter here only if * server.bindaddr_count == 0. */ - fds[*count] = anetTcp6Server(server.neterr, port, NULL, + fds[*count] = anetTcp6Server(server.neterr,port,NULL, server.tcp_backlog); if (fds[*count] != ANET_ERR) { - anetNonBlock(NULL, fds[*count]); + anetNonBlock(NULL,fds[*count]); (*count)++; - } - else if (errno == EAFNOSUPPORT) { + } else if (errno == EAFNOSUPPORT) { unsupported++; - serverLog(LL_WARNING, "Not listening to IPv6: unsupproted"); + serverLog(LL_WARNING,"Not listening to IPv6: unsupproted"); } if (*count == 1 || unsupported) { /* Bind the IPv4 address as well. */ - fds[*count] = anetTcpServer(server.neterr, port, NULL, + fds[*count] = anetTcpServer(server.neterr,port,NULL, server.tcp_backlog); if (fds[*count] != ANET_ERR) { - anetNonBlock(NULL, fds[*count]); + anetNonBlock(NULL,fds[*count]); (*count)++; - } - else if (errno == EAFNOSUPPORT) { + } else if (errno == EAFNOSUPPORT) { unsupported++; - serverLog(LL_WARNING, "Not listening to IPv4: unsupproted"); + serverLog(LL_WARNING,"Not listening to IPv4: unsupproted"); } } /* Exit the loop if we were able to bind * on IPv4 and IPv6, * otherwise fds[*count] will be ANET_ERR and we'll print an * error and return to the caller with an error. */ if (*count + unsupported == 2) break; - } - else if (strchr(server.bindaddr[j], ':')) { + } else if (strchr(server.bindaddr[j],':')) { /* Bind IPv6 address. */ - fds[*count] = anetTcp6Server(server.neterr, port, server.bindaddr[j], + fds[*count] = anetTcp6Server(server.neterr,port,server.bindaddr[j], server.tcp_backlog); - } - else { + } else { /* Bind IPv4 address. */ - fds[*count] = anetTcpServer(server.neterr, port, server.bindaddr[j], + fds[*count] = anetTcpServer(server.neterr,port,server.bindaddr[j], server.tcp_backlog); } if (fds[*count] == ANET_ERR) { @@ -1825,13 +1808,13 @@ int listenToPort(int port, int *fds, int *count) { "Creating Server TCP listening socket %s:%d: %s", server.bindaddr[j] ? server.bindaddr[j] : "*", port, server.neterr); - if (errno == ENOPROTOOPT || errno == EPROTONOSUPPORT || - errno == ESOCKTNOSUPPORT || errno == EPFNOSUPPORT || - errno == EAFNOSUPPORT || errno == EADDRNOTAVAIL) - continue; + if (errno == ENOPROTOOPT || errno == EPROTONOSUPPORT || + errno == ESOCKTNOSUPPORT || errno == EPFNOSUPPORT || + errno == EAFNOSUPPORT || errno == EADDRNOTAVAIL) + continue; return C_ERR; } - anetNonBlock(NULL, fds[*count]); + anetNonBlock(NULL,fds[*count]); (*count)++; } return C_OK; @@ -1865,7 +1848,7 @@ void resetServerStats(void) { server.inst_metric[j].idx = 0; server.inst_metric[j].last_sample_time = mstime(); server.inst_metric[j].last_sample_count = 0; - memset(server.inst_metric[j].samples, 0, + memset(server.inst_metric[j].samples,0, sizeof(server.inst_metric[j].samples)); } server.stat_net_input_bytes = 0; @@ -1876,7 +1859,7 @@ void resetServerStats(void) { void initServer(void) { int j; WIN32_ONLY(HMODULE lib;) - signal(SIGHUP, SIG_IGN); + signal(SIGHUP, SIG_IGN); signal(SIGPIPE, SIG_IGN); setupSignalHandlers(); @@ -1917,7 +1900,7 @@ void initServer(void) { createSharedObjects(); adjustOpenFilesLimit(); - server.el = aeCreateEventLoop(server.maxclients + CONFIG_FDSET_INCR); + server.el = aeCreateEventLoop(server.maxclients+CONFIG_FDSET_INCR); if (server.el == NULL) { serverLog(LL_WARNING, "Failed creating the event loop. Error message: '%s'", @@ -1928,19 +1911,19 @@ void initServer(void) { /* Open the TCP listening socket for the user commands. */ if (server.port != 0 && - listenToPort(server.port, server.ipfd, &server.ipfd_count) == C_ERR) + listenToPort(server.port,server.ipfd,&server.ipfd_count) == C_ERR) exit(1); /* Open the listening Unix domain socket. */ if (server.unixsocket != NULL) { unlink(server.unixsocket); /* don't care if this fails */ - server.sofd = anetUnixServer(server.neterr, server.unixsocket, + server.sofd = anetUnixServer(server.neterr,server.unixsocket, server.unixsocketperm, server.tcp_backlog); if (server.sofd == ANET_ERR) { serverLog(LL_WARNING, "Opening Unix socket: %s", server.neterr); exit(1); } - anetNonBlock(NULL, server.sofd); + anetNonBlock(NULL,server.sofd); } /* Abort if there are no listening sockets at all. */ @@ -1951,19 +1934,19 @@ void initServer(void) { /* Create the Redis databases, and initialize other internal state. */ for (j = 0; j < server.dbnum; j++) { - server.db[j].dict = dictCreate(&dbDictType, NULL); - server.db[j].expires = dictCreate(&keyptrDictType, NULL); - server.db[j].blocking_keys = dictCreate(&keylistDictType, NULL); - server.db[j].ready_keys = dictCreate(&objectKeyPointerValueDictType, NULL); - server.db[j].watched_keys = dictCreate(&keylistDictType, NULL); + server.db[j].dict = dictCreate(&dbDictType,NULL); + server.db[j].expires = dictCreate(&keyptrDictType,NULL); + server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL); + server.db[j].ready_keys = dictCreate(&objectKeyPointerValueDictType,NULL); + server.db[j].watched_keys = dictCreate(&keylistDictType,NULL); server.db[j].id = j; server.db[j].avg_ttl = 0; } evictionPoolAlloc(); /* Initialize the LRU keys pool. */ - server.pubsub_channels = dictCreate(&keylistDictType, NULL); + server.pubsub_channels = dictCreate(&keylistDictType,NULL); server.pubsub_patterns = listCreate(); - listSetFreeMethod(server.pubsub_patterns, freePubsubPattern); - listSetMatchMethod(server.pubsub_patterns, listMatchPubsubPattern); + listSetFreeMethod(server.pubsub_patterns,freePubsubPattern); + listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern); server.cronloops = 0; server.rdb_child_pid = -1; server.aof_child_pid = -1; @@ -2004,22 +1987,23 @@ void initServer(void) { * domain sockets. */ for (j = 0; j < server.ipfd_count; j++) { if (aeCreateFileEvent(server.el, server.ipfd[j], AE_READABLE, - acceptTcpHandler, NULL) == AE_ERR) - { - serverPanic( - "Unrecoverable error creating server.ipfd file event."); - } + acceptTcpHandler,NULL) == AE_ERR) + { + serverPanic( + "Unrecoverable error creating server.ipfd file event."); + } } - if (server.sofd > 0 && aeCreateFileEvent(server.el, server.sofd, AE_READABLE, - acceptUnixHandler, NULL) == AE_ERR) serverPanic("Unrecoverable error creating server.sofd file event."); + if (server.sofd > 0 && aeCreateFileEvent(server.el,server.sofd,AE_READABLE, + acceptUnixHandler,NULL) == AE_ERR) serverPanic("Unrecoverable error creating server.sofd file event."); + /* Register a readable event for the pipe used to awake the event loop * when a blocked client in a module needs attention. */ if (aeCreateFileEvent(server.el, server.module_blocked_pipe[0], AE_READABLE, - moduleBlockedClientPipeReadable, NULL) == AE_ERR) { - serverPanic( - "Error registering the readable event for the module " - "blocked clients subsystem."); + moduleBlockedClientPipeReadable,NULL) == AE_ERR) { + serverPanic( + "Error registering the readable event for the module " + "blocked clients subsystem."); } /* Open the AOF file if needed. */ @@ -2029,7 +2013,7 @@ void initServer(void) { O_WRONLY | O_APPEND | O_CREAT | _O_BINARY, _S_IREAD | _S_IWRITE); #else server.aof_fd = open(server.aof_filename, - O_WRONLY | O_APPEND | O_CREAT, 0644); + O_WRONLY|O_APPEND|O_CREAT,0644); #endif if (server.aof_fd == -1) { serverLog(LL_WARNING, "Can't open the append-only file: %s", @@ -2043,8 +2027,8 @@ void initServer(void) { * at 3 GB using maxmemory with 'noeviction' policy'. This avoids * useless crashes of the Redis instance for out of memory. */ if (server.arch_bits == 32 && server.maxmemory == 0) { - serverLog(LL_WARNING, "Warning: 32 bit instance detected but no memory limit set. Setting 3 GB maxmemory limit with 'noeviction' policy now."); - server.maxmemory = 3072LL * (1024 * 1024); /* 3 GB */ + serverLog(LL_WARNING,"Warning: 32 bit instance detected but no memory limit set. Setting 3 GB maxmemory limit with 'noeviction' policy now."); + server.maxmemory = 3072LL*(1024*1024); /* 3 GB */ server.maxmemory_policy = MAXMEMORY_NO_EVICTION; } @@ -2061,15 +2045,15 @@ void initServer(void) { * we have on top of redis.c file. */ void populateCommandTable(void) { int j; - int numcommands = sizeof(redisCommandTable) / sizeof(struct redisCommand); + int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand); for (j = 0; j < numcommands; j++) { - struct redisCommand *c = redisCommandTable + j; + struct redisCommand *c = redisCommandTable+j; char *f = c->sflags; int retval1, retval2; - while (*f != '\0') { - switch (*f) { + while(*f != '\0') { + switch(*f) { case 'w': c->flags |= CMD_WRITE; break; case 'r': c->flags |= CMD_READONLY; break; case 'm': c->flags |= CMD_DENYOOM; break; @@ -2102,12 +2086,13 @@ void resetCommandTableStats(void) { dictIterator *di; di = dictGetSafeIterator(server.commands); - while ((de = dictNext(di)) != NULL) { + while((de = dictNext(di)) != NULL) { c = (struct redisCommand *) dictGetVal(de); c->microseconds = 0; c->calls = 0; } dictReleaseIterator(di); + } /* ========================== Redis OP Array API ============================ */ @@ -2118,12 +2103,12 @@ void redisOpArrayInit(redisOpArray *oa) { } int redisOpArrayAppend(redisOpArray *oa, struct redisCommand *cmd, int dbid, - robj **argv, int argc, int target) + robj **argv, int argc, int target) { redisOp *op; - oa->ops = zrealloc(oa->ops, sizeof(redisOp)*(oa->numops + 1)); - op = oa->ops + oa->numops; + oa->ops = zrealloc(oa->ops,sizeof(redisOp)*(oa->numops+1)); + op = oa->ops+oa->numops; op->cmd = cmd; op->dbid = dbid; op->argv = argv; @@ -2134,12 +2119,12 @@ int redisOpArrayAppend(redisOpArray *oa, struct redisCommand *cmd, int dbid, } void redisOpArrayFree(redisOpArray *oa) { - while (oa->numops) { + while(oa->numops) { int j; redisOp *op; oa->numops--; - op = oa->ops + oa->numops; + op = oa->ops+oa->numops; for (j = 0; j < op->argc; j++) decrRefCount(op->argv[j]); zfree(op->argv); @@ -2172,7 +2157,7 @@ struct redisCommand *lookupCommandByCString(char *s) { struct redisCommand *lookupCommandOrOriginal(sds name) { struct redisCommand *cmd = dictFetchValue(server.commands, name); - if (!cmd) cmd = dictFetchValue(server.orig_commands, name); + if (!cmd) cmd = dictFetchValue(server.orig_commands,name); return cmd; } @@ -2188,12 +2173,12 @@ struct redisCommand *lookupCommandOrOriginal(sds name) { * alsoPropagate(), preventCommandPropagation(), forceCommandPropagation(). */ void propagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, - int flags) + int flags) { if (server.aof_state != AOF_OFF && flags & PROPAGATE_AOF) - feedAppendOnlyFile(cmd, dbid, argv, argc); + feedAppendOnlyFile(cmd,dbid,argv,argc); if (flags & PROPAGATE_REPL) - replicationFeedSlaves(server.slaves, dbid, argv, argc); + replicationFeedSlaves(server.slaves,dbid,argv,argc); } /* Used inside commands to schedule the propagation of additional commands @@ -2209,7 +2194,7 @@ void propagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, * stack allocated). The function autoamtically increments ref count of * passed objects, so the caller does not need to. */ void alsoPropagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, - int target) + int target) { robj **argvcopy; int j; @@ -2221,7 +2206,7 @@ void alsoPropagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, argvcopy[j] = argv[j]; incrRefCount(argv[j]); } - redisOpArrayAppend(&server.also_propagate, cmd, dbid, argvcopy, argc, target); + redisOpArrayAppend(&server.also_propagate,cmd,dbid,argvcopy,argc,target); } /* It is possible to call the function forceCommandPropagation() inside a @@ -2294,14 +2279,14 @@ void call(client *c, int flags) { * not generated from reading an AOF. */ if (listLength(server.monitors) && !server.loading && - !(c->cmd->flags & (CMD_SKIP_MONITOR | CMD_ADMIN))) + !(c->cmd->flags & (CMD_SKIP_MONITOR|CMD_ADMIN))) { - replicationFeedMonitors(c, server.monitors, c->db->id, c->argv, c->argc); + replicationFeedMonitors(c,server.monitors,c->db->id,c->argv,c->argc); } /* Initialization: clear the flags that must be set by the command on * demand, and initialize the array for additional commands propagation. */ - c->flags &= ~(CLIENT_FORCE_AOF | CLIENT_FORCE_REPL | CLIENT_PREVENT_PROP); + c->flags &= ~(CLIENT_FORCE_AOF|CLIENT_FORCE_REPL|CLIENT_PREVENT_PROP); redisOpArray prev_also_propagate = server.also_propagate; redisOpArrayInit(&server.also_propagate); @@ -2309,8 +2294,8 @@ void call(client *c, int flags) { dirty = server.dirty; start = ustime(); c->cmd->proc(c); - duration = ustime() - start; - dirty = server.dirty - dirty; + duration = ustime()-start; + dirty = server.dirty-dirty; if (dirty < 0) dirty = 0; /* When EVAL is called loading the AOF we don't want commands called @@ -2332,9 +2317,9 @@ void call(client *c, int flags) { * per-command statistics that we show in INFO commandstats. */ if (flags & CMD_CALL_SLOWLOG && c->cmd->proc != execCommand) { char *latency_event = (c->cmd->flags & CMD_FAST) ? - "fast-command" : "command"; - latencyAddSampleIfNeeded(latency_event, duration / 1000); - slowlogPushEntryIfNeeded(c, c->argv, c->argc, duration); + "fast-command" : "command"; + latencyAddSampleIfNeeded(latency_event,duration/1000); + slowlogPushEntryIfNeeded(c,c->argv,c->argc,duration); } if (flags & CMD_CALL_STATS) { c->lastcmd->microseconds += duration; @@ -2349,7 +2334,7 @@ void call(client *c, int flags) { /* Check if the command operated changes in the data set. If so * set for replication / AOF propagation. */ - if (dirty) propagate_flags |= (PROPAGATE_AOF | PROPAGATE_REPL); + if (dirty) propagate_flags |= (PROPAGATE_AOF|PROPAGATE_REPL); /* If the client forced AOF / replication of the command, set * the flags regardless of the command effects on the data set. */ @@ -2361,23 +2346,23 @@ void call(client *c, int flags) { * or if we don't have the call() flags to do so. */ if (c->flags & CLIENT_PREVENT_REPL_PROP || !(flags & CMD_CALL_PROPAGATE_REPL)) - propagate_flags &= ~PROPAGATE_REPL; + propagate_flags &= ~PROPAGATE_REPL; if (c->flags & CLIENT_PREVENT_AOF_PROP || !(flags & CMD_CALL_PROPAGATE_AOF)) - propagate_flags &= ~PROPAGATE_AOF; + propagate_flags &= ~PROPAGATE_AOF; /* Call propagate() only if at least one of AOF / replication * propagation is needed. Note that modules commands handle replication * in an explicit way, so we never replicate them automatically. */ if (propagate_flags != PROPAGATE_NONE && !(c->cmd->flags & CMD_MODULE)) - propagate(c->cmd, c->db->id, c->argv, c->argc, propagate_flags); + propagate(c->cmd,c->db->id,c->argv,c->argc,propagate_flags); } /* Restore the old replication flags, since call() can be executed * recursively. */ - c->flags &= ~(CLIENT_FORCE_AOF | CLIENT_FORCE_REPL | CLIENT_PREVENT_PROP); + c->flags &= ~(CLIENT_FORCE_AOF|CLIENT_FORCE_REPL|CLIENT_PREVENT_PROP); c->flags |= client_old_flags & - (CLIENT_FORCE_AOF | CLIENT_FORCE_REPL | CLIENT_PREVENT_PROP); + (CLIENT_FORCE_AOF|CLIENT_FORCE_REPL|CLIENT_PREVENT_PROP); /* Handle the alsoPropagate() API to handle commands that want to propagate * multiple separated commands. Note that alsoPropagate() is not affected @@ -2394,7 +2379,7 @@ void call(client *c, int flags) { if (!(flags&CMD_CALL_PROPAGATE_AOF)) target &= ~PROPAGATE_AOF; if (!(flags&CMD_CALL_PROPAGATE_REPL)) target &= ~PROPAGATE_REPL; if (target) - propagate(rop->cmd, rop->dbid, rop->argv, rop->argc, target); + propagate(rop->cmd,rop->dbid,rop->argv,rop->argc,target); } } redisOpArrayFree(&server.also_propagate); @@ -2416,8 +2401,8 @@ int processCommand(client *c) { * go through checking for replication and QUIT will cause trouble * when FORCE_REPLICATION is enabled and would be implemented in * a regular command proc. */ - if (!strcasecmp(c->argv[0]->ptr, "quit")) { - addReply(c, shared.ok); + if (!strcasecmp(c->argv[0]->ptr,"quit")) { + addReply(c,shared.ok); c->flags |= CLIENT_CLOSE_AFTER_REPLY; return C_ERR; } @@ -2435,11 +2420,10 @@ int processCommand(client *c) { (char*)c->argv[0]->ptr, args); sdsfree(args); return C_OK; - } - else if ((c->cmd->arity > 0 && c->cmd->arity != c->argc) || - (c->argc < -c->cmd->arity)) { + } else if ((c->cmd->arity > 0 && c->cmd->arity != c->argc) || + (c->argc < -c->cmd->arity)) { flagTransaction(c); - addReplyErrorFormat(c, "wrong number of arguments for '%s' command", + addReplyErrorFormat(c,"wrong number of arguments for '%s' command", c->cmd->name); return C_OK; } @@ -2448,7 +2432,7 @@ int processCommand(client *c) { if (server.requirepass && !c->authenticated && c->cmd->proc != authCommand) { flagTransaction(c); - addReply(c, shared.noautherr); + addReply(c,shared.noautherr); return C_OK; } @@ -2459,22 +2443,21 @@ int processCommand(client *c) { if (server.cluster_enabled && !(c->flags & CLIENT_MASTER) && !(c->flags & CLIENT_LUA && - server.lua_caller->flags & CLIENT_MASTER) && + server.lua_caller->flags & CLIENT_MASTER) && !(c->cmd->getkeys_proc == NULL && c->cmd->firstkey == 0 && - c->cmd->proc != execCommand)) + c->cmd->proc != execCommand)) { int hashslot; int error_code; - clusterNode *n = getNodeByQuery(c, c->cmd, c->argv, c->argc, - &hashslot, &error_code); + clusterNode *n = getNodeByQuery(c,c->cmd,c->argv,c->argc, + &hashslot,&error_code); if (n == NULL || n != server.cluster->myself) { if (c->cmd->proc == execCommand) { discardTransaction(c); - } - else { + } else { flagTransaction(c); } - clusterRedirectClient(c, n, hashslot, error_code); + clusterRedirectClient(c,n,hashslot,error_code); return C_OK; } } @@ -2502,12 +2485,12 @@ int processCommand(client *c) { /* Don't accept write commands if there are problems persisting on disk * and if this is a master instance. */ if (((server.stop_writes_on_bgsave_err && - server.saveparamslen > 0 && - server.lastbgsave_status == C_ERR) || - server.aof_last_write_status == C_ERR) && + server.saveparamslen > 0 && + server.lastbgsave_status == C_ERR) || + server.aof_last_write_status == C_ERR) && server.masterhost == NULL && (c->cmd->flags & CMD_WRITE || - c->cmd->proc == pingCommand)) + c->cmd->proc == pingCommand)) { flagTransaction(c); if (server.aof_last_write_status == C_OK) @@ -2515,8 +2498,8 @@ int processCommand(client *c) { else addReplySds(c, sdscatprintf(sdsempty(), - "-MISCONF Errors writing to the AOF file: %s\r\n", - strerror(server.aof_last_write_errno))); + "-MISCONF Errors writing to the AOF file: %s\r\n", + strerror(server.aof_last_write_errno))); return C_OK; } @@ -2550,7 +2533,7 @@ int processCommand(client *c) { c->cmd->proc != unsubscribeCommand && c->cmd->proc != psubscribeCommand && c->cmd->proc != punsubscribeCommand) { - addReplyError(c, "only (P)SUBSCRIBE / (P)UNSUBSCRIBE / PING / QUIT allowed in this context"); + addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / PING / QUIT allowed in this context"); return C_OK; } @@ -2574,14 +2557,14 @@ int processCommand(client *c) { /* Lua script too slow? Only allow a limited number of commands. */ if (server.lua_timedout && - c->cmd->proc != authCommand && - c->cmd->proc != replconfCommand && + c->cmd->proc != authCommand && + c->cmd->proc != replconfCommand && !(c->cmd->proc == shutdownCommand && - c->argc == 2 && - tolower(((char*) c->argv[1]->ptr)[0]) == 'n') && + c->argc == 2 && + tolower(((char*)c->argv[1]->ptr)[0]) == 'n') && !(c->cmd->proc == scriptCommand && - c->argc == 2 && - tolower(((char*) c->argv[1]->ptr)[0]) == 'k')) + c->argc == 2 && + tolower(((char*)c->argv[1]->ptr)[0]) == 'k')) { flagTransaction(c); addReply(c, shared.slowscripterr); @@ -2594,10 +2577,9 @@ int processCommand(client *c) { c->cmd->proc != multiCommand && c->cmd->proc != watchCommand) { queueMultiCommand(c); - addReply(c, shared.queued); - } - else { - call(c, CMD_CALL_FULL); + addReply(c,shared.queued); + } else { + call(c,CMD_CALL_FULL); c->woff = server.master_repl_offset; if (listLength(server.ready_keys)) handleClientsBlockedOnLists(); @@ -2617,7 +2599,7 @@ void closeListeningSockets(int unlink_unix_socket) { if (server.cluster_enabled) for (j = 0; j < server.cfd_count; j++) close(server.cfd[j]); if (unlink_unix_socket && server.unixsocket) { - serverLog(LL_NOTICE, "Removing the unix socket file."); + serverLog(LL_NOTICE,"Removing the unix socket file."); unlink(server.unixsocket); /* don't care if this fails */ } } @@ -2626,7 +2608,7 @@ int prepareForShutdown(int flags) { int save = flags & SHUTDOWN_SAVE; int nosave = flags & SHUTDOWN_NOSAVE; - serverLog(LL_WARNING, "User requested shutdown..."); + serverLog(LL_WARNING,"User requested shutdown..."); /* Kill all the Lua debugger forked sessions. */ ldbKillForkedSessions(); @@ -2635,8 +2617,8 @@ int prepareForShutdown(int flags) { We want to avoid race conditions, for instance our saving child may overwrite the synchronous saving did by SHUTDOWN. */ if (server.rdb_child_pid != -1) { - serverLog(LL_WARNING, "There is a child saving an .rdb. Killing it!"); - IF_WIN32(AbortForkOperation(), kill(server.rdb_child_pid, SIGUSR1)); + serverLog(LL_WARNING,"There is a child saving an .rdb. Killing it!"); + IF_WIN32(AbortForkOperation(), kill(server.rdb_child_pid,SIGUSR1)); rdbRemoveTempFile(server.rdb_child_pid); } @@ -2652,34 +2634,34 @@ int prepareForShutdown(int flags) { } serverLog(LL_WARNING, "There is a child rewriting the AOF. Killing it!"); - IF_WIN32(AbortForkOperation(), kill(server.aof_child_pid, SIGUSR1)); + IF_WIN32(AbortForkOperation(), kill(server.aof_child_pid,SIGUSR1)); } /* Append only file: flush buffers and fsync() the AOF at exit */ - serverLog(LL_NOTICE, "Calling fsync() on the AOF file."); + serverLog(LL_NOTICE,"Calling fsync() on the AOF file."); flushAppendOnlyFile(1); aof_fsync(server.aof_fd); } /* Create a new RDB file before exiting. */ if ((server.saveparamslen > 0 && !nosave) || save) { - serverLog(LL_NOTICE, "Saving the final RDB snapshot before exiting."); + serverLog(LL_NOTICE,"Saving the final RDB snapshot before exiting."); /* Snapshotting. Perform a SYNC SAVE and exit */ rdbSaveInfo rsi, *rsiptr; rsiptr = rdbPopulateSaveInfo(&rsi); - if (rdbSave(server.rdb_filename, rsiptr) != C_OK) { + if (rdbSave(server.rdb_filename,rsiptr) != C_OK) { /* Ooops.. error saving! The best we can do is to continue * operating. Note that if there was a background saving process, * in the next cron() Redis will be notified that the background * saving aborted, handling special stuff like slaves pending for * synchronization... */ - serverLog(LL_WARNING, "Error trying to save the DB, can't exit."); + serverLog(LL_WARNING,"Error trying to save the DB, can't exit."); return C_ERR; } } /* Remove the pid file if possible and needed. */ if (server.daemonize || server.pidfile) { - serverLog(LL_NOTICE, "Removing the pid file."); + serverLog(LL_NOTICE,"Removing the pid file."); unlink(server.pidfile); } @@ -2689,7 +2671,7 @@ int prepareForShutdown(int flags) { /* Close the listening sockets. Apparently this allows faster restarts. */ closeListeningSockets(1); - serverLog(LL_WARNING, "%s is now ready to exit, bye bye...", + serverLog(LL_WARNING,"%s is now ready to exit, bye bye...", server.sentinel_mode ? "Sentinel" : "Redis"); return C_OK; } @@ -2712,8 +2694,8 @@ int time_independent_strcmp(char *a, char *b) { * relative to the length of the user provided string, so no information * leak is possible in the following two lines of code. */ unsigned int alen = (unsigned int) strlen(a); WIN_PORT_FIX /* cast (unsigned int) */ - unsigned int blen = (unsigned int) strlen(b); WIN_PORT_FIX /* cast (unsigned int) */ - unsigned int j; + unsigned int blen = (unsigned int) strlen(b); WIN_PORT_FIX /* cast (unsigned int) */ + unsigned int j; int diff = 0; /* We can't compare strings longer than our static buffers. @@ -2721,12 +2703,12 @@ int time_independent_strcmp(char *a, char *b) { * so there is no info leak. */ if (alen > sizeof(bufa) || blen > sizeof(bufb)) return 1; - memset(bufa, 0, sizeof(bufa)); /* Constant time. */ - memset(bufb, 0, sizeof(bufb)); /* Constant time. */ + memset(bufa,0,sizeof(bufa)); /* Constant time. */ + memset(bufb,0,sizeof(bufb)); /* Constant time. */ /* Again the time of the following two copies is proportional to * len(a) + len(b) so no info is leaked. */ - memcpy(bufa, a, alen); - memcpy(bufb, b, blen); + memcpy(bufa,a,alen); + memcpy(bufb,b,blen); /* Always compare all the chars in the two buffers without * conditional expressions. */ @@ -2740,15 +2722,13 @@ int time_independent_strcmp(char *a, char *b) { void authCommand(client *c) { if (!server.requirepass) { - addReplyError(c, "Client sent AUTH, but no password is set"); - } - else if (!time_independent_strcmp(c->argv[1]->ptr, server.requirepass)) { - c->authenticated = 1; - addReply(c, shared.ok); - } - else { - c->authenticated = 0; - addReplyError(c, "invalid password"); + addReplyError(c,"Client sent AUTH, but no password is set"); + } else if (!time_independent_strcmp(c->argv[1]->ptr, server.requirepass)) { + c->authenticated = 1; + addReply(c,shared.ok); + } else { + c->authenticated = 0; + addReplyError(c,"invalid password"); } } @@ -2757,29 +2737,28 @@ void authCommand(client *c) { void pingCommand(client *c) { /* The command takes zero or one arguments. */ if (c->argc > 2) { - addReplyErrorFormat(c, "wrong number of arguments for '%s' command", + addReplyErrorFormat(c,"wrong number of arguments for '%s' command", c->cmd->name); return; } if (c->flags & CLIENT_PUBSUB) { - addReply(c, shared.mbulkhdr[2]); - addReplyBulkCBuffer(c, "pong", 4); + addReply(c,shared.mbulkhdr[2]); + addReplyBulkCBuffer(c,"pong",4); if (c->argc == 1) - addReplyBulkCBuffer(c, "", 0); + addReplyBulkCBuffer(c,"",0); else - addReplyBulk(c, c->argv[1]); - } - else { + addReplyBulk(c,c->argv[1]); + } else { if (c->argc == 1) - addReply(c, shared.pong); + addReply(c,shared.pong); else - addReplyBulk(c, c->argv[1]); + addReplyBulk(c,c->argv[1]); } } void echoCommand(client *c) { - addReplyBulk(c, c->argv[1]); + addReplyBulk(c,c->argv[1]); } void timeCommand(client *c) { @@ -2787,10 +2766,10 @@ void timeCommand(client *c) { /* gettimeofday() can only fail if &tv is a bad address so we * don't check for errors. */ - gettimeofday(&tv, NULL); - addReplyMultiBulkLen(c, 2); - addReplyBulkLongLong(c, tv.tv_sec); - addReplyBulkLongLong(c, tv.tv_usec); + gettimeofday(&tv,NULL); + addReplyMultiBulkLen(c,2); + addReplyBulkLongLong(c,tv.tv_sec); + addReplyBulkLongLong(c,tv.tv_usec); } /* Helper function for addReplyCommand() to output flags. */ @@ -2806,8 +2785,7 @@ int addReplyCommandFlag(client *c, struct redisCommand *cmd, int f, char *reply) void addReplyCommand(client *c, struct redisCommand *cmd) { if (!cmd) { addReply(c, shared.nullbulk); - } - else { + } else { /* We are adding: command name, arg count, flags, first, last, offset */ addReplyMultiBulkLen(c, 6); addReplyBulkCString(c, cmd->name); @@ -2815,19 +2793,19 @@ void addReplyCommand(client *c, struct redisCommand *cmd) { int flagcount = 0; void *flaglen = addDeferredMultiBulkLength(c); - flagcount += addReplyCommandFlag(c, cmd, CMD_WRITE, "write"); - flagcount += addReplyCommandFlag(c, cmd, CMD_READONLY, "readonly"); - flagcount += addReplyCommandFlag(c, cmd, CMD_DENYOOM, "denyoom"); - flagcount += addReplyCommandFlag(c, cmd, CMD_ADMIN, "admin"); - flagcount += addReplyCommandFlag(c, cmd, CMD_PUBSUB, "pubsub"); - flagcount += addReplyCommandFlag(c, cmd, CMD_NOSCRIPT, "noscript"); - flagcount += addReplyCommandFlag(c, cmd, CMD_RANDOM, "random"); - flagcount += addReplyCommandFlag(c, cmd, CMD_SORT_FOR_SCRIPT, "sort_for_script"); - flagcount += addReplyCommandFlag(c, cmd, CMD_LOADING, "loading"); - flagcount += addReplyCommandFlag(c, cmd, CMD_STALE, "stale"); - flagcount += addReplyCommandFlag(c, cmd, CMD_SKIP_MONITOR, "skip_monitor"); - flagcount += addReplyCommandFlag(c, cmd, CMD_ASKING, "asking"); - flagcount += addReplyCommandFlag(c, cmd, CMD_FAST, "fast"); + flagcount += addReplyCommandFlag(c,cmd,CMD_WRITE, "write"); + flagcount += addReplyCommandFlag(c,cmd,CMD_READONLY, "readonly"); + flagcount += addReplyCommandFlag(c,cmd,CMD_DENYOOM, "denyoom"); + flagcount += addReplyCommandFlag(c,cmd,CMD_ADMIN, "admin"); + flagcount += addReplyCommandFlag(c,cmd,CMD_PUBSUB, "pubsub"); + flagcount += addReplyCommandFlag(c,cmd,CMD_NOSCRIPT, "noscript"); + flagcount += addReplyCommandFlag(c,cmd,CMD_RANDOM, "random"); + flagcount += addReplyCommandFlag(c,cmd,CMD_SORT_FOR_SCRIPT,"sort_for_script"); + flagcount += addReplyCommandFlag(c,cmd,CMD_LOADING, "loading"); + flagcount += addReplyCommandFlag(c,cmd,CMD_STALE, "stale"); + flagcount += addReplyCommandFlag(c,cmd,CMD_SKIP_MONITOR, "skip_monitor"); + flagcount += addReplyCommandFlag(c,cmd,CMD_ASKING, "asking"); + flagcount += addReplyCommandFlag(c,cmd,CMD_FAST, "fast"); if ((cmd->getkeys_proc && !(cmd->flags & CMD_MODULE)) || cmd->flags & CMD_MODULE_GETKEYS) { @@ -2854,38 +2832,33 @@ void commandCommand(client *c) { addReplyCommand(c, dictGetVal(de)); } dictReleaseIterator(di); - } - else if (!strcasecmp(c->argv[1]->ptr, "info")) { + } else if (!strcasecmp(c->argv[1]->ptr, "info")) { int i; - addReplyMultiBulkLen(c, c->argc - 2); + addReplyMultiBulkLen(c, c->argc-2); for (i = 2; i < c->argc; i++) { addReplyCommand(c, dictFetchValue(server.commands, c->argv[i]->ptr)); } - } - else if (!strcasecmp(c->argv[1]->ptr, "count") && c->argc == 2) { + } else if (!strcasecmp(c->argv[1]->ptr, "count") && c->argc == 2) { addReplyLongLong(c, dictSize(server.commands)); - } - else if (!strcasecmp(c->argv[1]->ptr, "getkeys") && c->argc >= 3) { + } else if (!strcasecmp(c->argv[1]->ptr,"getkeys") && c->argc >= 3) { struct redisCommand *cmd = lookupCommand(c->argv[2]->ptr); int *keys, numkeys, j; if (!cmd) { - addReplyErrorFormat(c, "Invalid command specified"); + addReplyErrorFormat(c,"Invalid command specified"); return; - } - else if ((cmd->arity > 0 && cmd->arity != c->argc - 2) || - ((c->argc - 2) < -cmd->arity)) + } else if ((cmd->arity > 0 && cmd->arity != c->argc-2) || + ((c->argc-2) < -cmd->arity)) { - addReplyError(c, "Invalid number of arguments specified for command"); + addReplyError(c,"Invalid number of arguments specified for command"); return; } - keys = getKeysFromCommand(cmd, c->argv + 2, c->argc - 2, &numkeys); - addReplyMultiBulkLen(c, numkeys); - for (j = 0; j < numkeys; j++) addReplyBulk(c, c->argv[keys[j] + 2]); + keys = getKeysFromCommand(cmd,c->argv+2,c->argc-2,&numkeys); + addReplyMultiBulkLen(c,numkeys); + for (j = 0; j < numkeys; j++) addReplyBulk(c,c->argv[keys[j]+2]); getKeysFreeResult(keys); - } - else { + } else { addReplyError(c, "Unknown subcommand or wrong number of arguments."); return; } @@ -2898,32 +2871,26 @@ void bytesToHuman(char *s, PORT_ULONGLONG n) { if (n < 1024) { /* Bytes */ - sprintf(s, "%lluB", n); + sprintf(s,"%lluB",n); return; - } - else if (n < (1024 * 1024)) { - d = (double) n / (1024); - sprintf(s, "%.2fK", d); - } - else if (n < (1024LL * 1024 * 1024)) { - d = (double) n / (1024 * 1024); - sprintf(s, "%.2fM", d); - } - else if (n < (1024LL * 1024 * 1024 * 1024)) { - d = (double) n / (1024LL * 1024 * 1024); - sprintf(s, "%.2fG", d); - } - else if (n < (1024LL * 1024 * 1024 * 1024 * 1024)) { - d = (double) n / (1024LL * 1024 * 1024 * 1024); - sprintf(s, "%.2fT", d); - } - else if (n < (1024LL * 1024 * 1024 * 1024 * 1024 * 1024)) { - d = (double) n / (1024LL * 1024 * 1024 * 1024 * 1024); - sprintf(s, "%.2fP", d); - } - else { + } else if (n < (1024*1024)) { + d = (double)n/(1024); + sprintf(s,"%.2fK",d); + } else if (n < (1024LL*1024*1024)) { + d = (double)n/(1024*1024); + sprintf(s,"%.2fM",d); + } else if (n < (1024LL*1024*1024*1024)) { + d = (double)n/(1024LL*1024*1024); + sprintf(s,"%.2fG",d); + } else if (n < (1024LL*1024*1024*1024*1024)) { + d = (double)n/(1024LL*1024*1024*1024); + sprintf(s,"%.2fT",d); + } else if (n < (1024LL*1024*1024*1024*1024*1024)) { + d = (double)n/(1024LL*1024*1024*1024*1024); + sprintf(s,"%.2fP",d); + } else { /* Let's hope we never need this */ - sprintf(s, "%lluB", n); + sprintf(s,"%lluB",n); } } @@ -2932,7 +2899,7 @@ void bytesToHuman(char *s, PORT_ULONGLONG n) { * on memory corruption problems. */ sds genRedisInfoString(char *section) { sds info = sdsempty(); - time_t uptime = server.unixtime - server.stat_starttime; + time_t uptime = server.unixtime-server.stat_starttime; int j; struct rusage self_ru, c_ru; PORT_ULONG lol, bib; @@ -2940,103 +2907,103 @@ sds genRedisInfoString(char *section) { int sections = 0; if (section == NULL) section = "default"; - allsections = strcasecmp(section, "all") == 0; - defsections = strcasecmp(section, "default") == 0; + allsections = strcasecmp(section,"all") == 0; + defsections = strcasecmp(section,"default") == 0; getrusage(RUSAGE_SELF, &self_ru); getrusage(RUSAGE_CHILDREN, &c_ru); - getClientsMaxBuffers(&lol, &bib); + getClientsMaxBuffers(&lol,&bib); /* Server */ - if (allsections || defsections || !strcasecmp(section, "server")) { + if (allsections || defsections || !strcasecmp(section,"server")) { POSIX_ONLY(static int call_uname = 1;) - POSIX_ONLY(static struct utsname name;) - char *mode; + POSIX_ONLY(static struct utsname name;) + char *mode; if (server.cluster_enabled) mode = "cluster"; else if (server.sentinel_mode) mode = "sentinel"; else mode = "standalone"; - if (sections++) info = sdscat(info, "\r\n"); + if (sections++) info = sdscat(info,"\r\n"); - POSIX_ONLY(if (call_uname) { - ) +#ifndef _WIN32 + if (call_uname) { /* Uname can be slow and is always the same output. Cache it. */ - POSIX_ONLY(uname(&name);) - POSIX_ONLY(call_uname = 0;) - POSIX_ONLY( - }) + uname(&name); + call_uname = 0; + } +#endif - unsigned int lruclock; - atomicGet(server.lruclock, lruclock); - info = sdscatprintf(info, - "# Server\r\n" - "redis_version:%s\r\n" - "redis_git_sha1:%s\r\n" - "redis_git_dirty:%d\r\n" - "redis_build_id:%llx\r\n" - "redis_mode:%s\r\n" - "os:%s %s %s\r\n" - "arch_bits:%d\r\n" - "multiplexing_api:%s\r\n" - "atomicvar_api:%s\r\n" - POSIX_ONLY("gcc_version:%d.%d.%d\r\n") - "process_id:%Id\r\n" WIN_PORT_FIX /* %ld -> %Id */ - "run_id:%s\r\n" - "tcp_port:%d\r\n" - "uptime_in_seconds:%lld\r\n" WIN_PORT_FIX /* %jd -> %lld */ - "uptime_in_days:%lld\r\n" WIN_PORT_FIX /* %jd -> %lld */ - "hz:%d\r\n" - "lru_clock:%Id\r\n" WIN_PORT_FIX /* %ld -> %Id */ - "executable:%s\r\n" - "config_file:%s\r\n", - REDIS_VERSION, - redisGitSHA1(), - strtol(redisGitDirty(), NULL, 10) > 0, - (PORT_ULONGLONG) redisBuildId(), - mode, + unsigned int lruclock; + atomicGet(server.lruclock,lruclock); + info = sdscatprintf(info, + "# Server\r\n" + "redis_version:%s\r\n" + "redis_git_sha1:%s\r\n" + "redis_git_dirty:%d\r\n" + "redis_build_id:%llx\r\n" + "redis_mode:%s\r\n" + "os:%s %s %s\r\n" + "arch_bits:%d\r\n" + "multiplexing_api:%s\r\n" + "atomicvar_api:%s\r\n" + POSIX_ONLY("gcc_version:%d.%d.%d\r\n") + "process_id:%Id\r\n" WIN_PORT_FIX /* %ld -> %Id */ + "run_id:%s\r\n" + "tcp_port:%d\r\n" + "uptime_in_seconds:%lld\r\n" WIN_PORT_FIX /* %jd -> %lld */ + "uptime_in_days:%lld\r\n" WIN_PORT_FIX /* %jd -> %lld */ + "hz:%d\r\n" + "lru_clock:%Id\r\n" WIN_PORT_FIX /* %ld -> %Id */ + "executable:%s\r\n" + "config_file:%s\r\n", + REDIS_VERSION, + redisGitSHA1(), + strtol(redisGitDirty(),NULL,10) > 0, + (PORT_ULONGLONG) redisBuildId(), + mode, #ifdef _WIN32 "Windows", "", "", #else - name.sysname, name.release, name.machine, + name.sysname, name.release, name.machine, #endif - server.arch_bits, - aeGetApiName(), - REDIS_ATOMIC_API, + server.arch_bits, + aeGetApiName(), + REDIS_ATOMIC_API, #ifndef _WIN32 #ifdef __GNUC__ - __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__, + __GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__, #else - 0, 0, 0, + 0,0,0, #endif #endif - (PORT_LONG) getpid(), - server.runid, - server.port, - (intmax_t) uptime, - (intmax_t) (uptime / (3600 * 24)), - server.hz, - (PORT_ULONG) lruclock, - server.executable ? server.executable : "", - server.configfile ? server.configfile : ""); + (PORT_LONG) getpid(), + server.runid, + server.port, + (intmax_t)uptime, + (intmax_t)(uptime/(3600*24)), + server.hz, + (PORT_ULONG) lruclock, + server.executable ? server.executable : "", + server.configfile ? server.configfile : ""); } /* Clients */ - if (allsections || defsections || !strcasecmp(section, "clients")) { - if (sections++) info = sdscat(info, "\r\n"); + if (allsections || defsections || !strcasecmp(section,"clients")) { + if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Clients\r\n" "connected_clients:%Iu\r\n" WIN_PORT_FIX /* %lu -> %Iu */ "client_longest_output_list:%Iu\r\n" WIN_PORT_FIX /* %lu -> %Iu */ "client_biggest_input_buf:%Iu\r\n" WIN_PORT_FIX /* %lu -> %Iu */ "blocked_clients:%d\r\n", - listLength(server.clients) - listLength(server.slaves), + listLength(server.clients)-listLength(server.slaves), lol, bib, server.bpop_blocked_clients); } /* Memory */ - if (allsections || defsections || !strcasecmp(section, "memory")) { + if (allsections || defsections || !strcasecmp(section,"memory")) { char hmem[64]; char peak_hmem[64]; char total_system_hmem[64]; @@ -3046,7 +3013,7 @@ sds genRedisInfoString(char *section) { size_t zmalloc_used = zmalloc_used_memory(); size_t total_system_mem = server.system_memory_size; const char *evict_policy = evictPolicyToString(); - PORT_LONGLONG memory_lua = (PORT_LONGLONG) lua_gc(server.lua, LUA_GCCOUNT, 0) * 1024; + PORT_LONGLONG memory_lua = (PORT_LONGLONG) lua_gc(server.lua,LUA_GCCOUNT,0)*1024; struct redisMemOverhead *mh = getMemoryOverheadData(); /* Peak memory is updated from time to time by serverCron() so it @@ -3056,14 +3023,14 @@ sds genRedisInfoString(char *section) { if (zmalloc_used > server.stat_peak_memory) server.stat_peak_memory = zmalloc_used; - bytesToHuman(hmem, zmalloc_used); - bytesToHuman(peak_hmem, server.stat_peak_memory); - bytesToHuman(total_system_hmem, total_system_mem); - bytesToHuman(used_memory_lua_hmem, memory_lua); - bytesToHuman(used_memory_rss_hmem, server.resident_set_size); - bytesToHuman(maxmemory_hmem, server.maxmemory); + bytesToHuman(hmem,zmalloc_used); + bytesToHuman(peak_hmem,server.stat_peak_memory); + bytesToHuman(total_system_hmem,total_system_mem); + bytesToHuman(used_memory_lua_hmem,memory_lua); + bytesToHuman(used_memory_rss_hmem,server.resident_set_size); + bytesToHuman(maxmemory_hmem,server.maxmemory); - if (sections++) info = sdscat(info, "\r\n"); + if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Memory\r\n" "used_memory:%Iu\r\n" WIN_PORT_FIX /* %zu -> %Iu */ @@ -3099,7 +3066,7 @@ sds genRedisInfoString(char *section) { mh->startup_allocated, mh->dataset, mh->dataset_perc, - (PORT_ULONG) total_system_mem, + (PORT_ULONG)total_system_mem, total_system_hmem, memory_lua, used_memory_lua_hmem, @@ -3115,8 +3082,8 @@ sds genRedisInfoString(char *section) { } /* Persistence */ - if (allsections || defsections || !strcasecmp(section, "persistence")) { - if (sections++) info = sdscat(info, "\r\n"); + if (allsections || defsections || !strcasecmp(section,"persistence")) { + if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Persistence\r\n" "loading:%d\r\n" @@ -3138,19 +3105,19 @@ sds genRedisInfoString(char *section) { server.loading, server.dirty, server.rdb_child_pid != -1, - (intmax_t) server.lastsave, + (intmax_t)server.lastsave, (server.lastbgsave_status == C_OK) ? "ok" : "err", - (intmax_t) server.rdb_save_time_last, - (intmax_t) ((server.rdb_child_pid == -1) ? - -1 : time(NULL) - server.rdb_save_time_start), + (intmax_t)server.rdb_save_time_last, + (intmax_t)((server.rdb_child_pid == -1) ? + -1 : time(NULL)-server.rdb_save_time_start), server.stat_rdb_cow_bytes, server.aof_state != AOF_OFF, server.aof_child_pid != -1, server.aof_rewrite_scheduled, - (intmax_t) server.aof_rewrite_time_last, - (intmax_t) ((server.aof_child_pid == -1) ? - -1 : time(NULL) - server.aof_rewrite_time_start), - (server.aof_lastbgrewrite_status == C_OK) ? "ok" : "err", + (intmax_t)server.aof_rewrite_time_last, + (intmax_t)((server.aof_child_pid == -1) ? + -1 : time(NULL)-server.aof_rewrite_time_start), + (server.aof_lastbgrewrite_status == C_OK) ? "ok" : "err", (server.aof_last_write_status == C_OK) ? "ok" : "err", server.stat_aof_cow_bytes); @@ -3175,19 +3142,18 @@ sds genRedisInfoString(char *section) { if (server.loading) { double perc; time_t eta, elapsed; - off_t remaining_bytes = server.loading_total_bytes - - server.loading_loaded_bytes; + off_t remaining_bytes = server.loading_total_bytes- + server.loading_loaded_bytes; - perc = ((double) server.loading_loaded_bytes / - (server.loading_total_bytes + 1)) * 100; + perc = ((double)server.loading_loaded_bytes / + (server.loading_total_bytes+1)) * 100; - elapsed = time(NULL) - server.loading_start_time; + elapsed = time(NULL)-server.loading_start_time; if (elapsed == 0) { eta = 1; /* A fake 1 second figure if we don't have enough info */ - } - else { - eta = (elapsed*remaining_bytes) / (server.loading_loaded_bytes + 1); + } else { + eta = (elapsed*remaining_bytes)/(server.loading_loaded_bytes+1); } info = sdscatprintf(info, @@ -3200,14 +3166,14 @@ sds genRedisInfoString(char *section) { (PORT_ULONGLONG) server.loading_total_bytes, (PORT_ULONGLONG) server.loading_loaded_bytes, perc, - (intmax_t) eta + (intmax_t)eta ); } } /* Stats */ - if (allsections || defsections || !strcasecmp(section, "stats")) { - if (sections++) info = sdscat(info, "\r\n"); + if (allsections || defsections || !strcasecmp(section,"stats")) { + if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Stats\r\n" "total_connections_received:%lld\r\n" @@ -3241,8 +3207,8 @@ sds genRedisInfoString(char *section) { getInstantaneousMetric(STATS_METRIC_COMMAND), server.stat_net_input_bytes, server.stat_net_output_bytes, - (float) getInstantaneousMetric(STATS_METRIC_NET_INPUT) / 1024, - (float) getInstantaneousMetric(STATS_METRIC_NET_OUTPUT) / 1024, + (float)getInstantaneousMetric(STATS_METRIC_NET_INPUT)/1024, + (float)getInstantaneousMetric(STATS_METRIC_NET_OUTPUT)/1024, server.stat_rejected_conn, server.stat_sync_full, server.stat_sync_partial_ok, @@ -3265,8 +3231,8 @@ sds genRedisInfoString(char *section) { } /* Replication */ - if (allsections || defsections || !strcasecmp(section, "replication")) { - if (sections++) info = sdscat(info, "\r\n"); + if (allsections || defsections || !strcasecmp(section,"replication")) { + if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Replication\r\n" "role:%s\r\n", @@ -3286,12 +3252,12 @@ sds genRedisInfoString(char *section) { "master_last_io_seconds_ago:%d\r\n" "master_sync_in_progress:%d\r\n" "slave_repl_offset:%lld\r\n" - , server.masterhost, + ,server.masterhost, server.masterport, (server.repl_state == REPL_STATE_CONNECTED) ? - "up" : "down", + "up" : "down", server.master ? - ((int) (server.unixtime - server.master->lastinteraction)) : -1, + ((int)(server.unixtime-server.master->lastinteraction)) : -1, server.repl_state == REPL_STATE_TRANSFER, slave_repl_offset ); @@ -3302,14 +3268,14 @@ sds genRedisInfoString(char *section) { "master_sync_last_io_seconds_ago:%d\r\n" , (PORT_LONGLONG) (server.repl_transfer_size - server.repl_transfer_read), - (int) (server.unixtime - server.repl_transfer_lastio) + (int)(server.unixtime-server.repl_transfer_lastio) ); } if (server.repl_state != REPL_STATE_CONNECTED) { info = sdscatprintf(info, "master_link_down_since_seconds:%jd\r\n", - (intmax_t) server.unixtime - server.repl_down_since); + (intmax_t)server.unixtime-server.repl_down_since); } info = sdscatprintf(info, "slave_priority:%d\r\n" @@ -3336,8 +3302,8 @@ sds genRedisInfoString(char *section) { listNode *ln; listIter li; - listRewind(server.slaves, &li); - while ((ln = listNext(&li))) { + listRewind(server.slaves,&li); + while((ln = listNext(&li))) { client *slave = listNodeValue(ln); char *state = NULL; char ip[NET_IP_STR_LEN], *slaveip = slave->slave_ip; @@ -3345,11 +3311,11 @@ sds genRedisInfoString(char *section) { PORT_LONG lag = 0; if (slaveip[0] == '\0') { - if (anetPeerToString(slave->fd, ip, sizeof(ip), &port) == -1) + if (anetPeerToString(slave->fd,ip,sizeof(ip),&port) == -1) continue; slaveip = ip; } - switch (slave->replstate) { + switch(slave->replstate) { case SLAVE_STATE_WAIT_BGSAVE_START: case SLAVE_STATE_WAIT_BGSAVE_END: state = "wait_bgsave"; @@ -3365,11 +3331,11 @@ sds genRedisInfoString(char *section) { if (slave->replstate == SLAVE_STATE_ONLINE) lag = (PORT_LONG) (time(NULL) - slave->repl_ack_time); WIN_PORT_FIX /* cast (PORT_LONG) */ - info = sdscatprintf(info, - "slave%d:ip=%s,port=%d,state=%s," - "offset=%lld,lag=%Id\r\n", WIN_PORT_FIX /* %ld -> %Id */ - slaveid, slaveip, slave->slave_listening_port, state, - slave->repl_ack_off, lag); + info = sdscatprintf(info, + "slave%d:ip=%s,port=%d,state=%s," + "offset=%lld,lag=%Id\r\n", WIN_PORT_FIX /* %ld -> %Id */ + slaveid,slaveip,slave->slave_listening_port,state, + slave->repl_ack_off, lag); slaveid++; } } @@ -3393,52 +3359,52 @@ sds genRedisInfoString(char *section) { } /* CPU */ - if (allsections || defsections || !strcasecmp(section, "cpu")) { - if (sections++) info = sdscat(info, "\r\n"); + if (allsections || defsections || !strcasecmp(section,"cpu")) { + if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, - "# CPU\r\n" - "used_cpu_sys:%.2f\r\n" - "used_cpu_user:%.2f\r\n" - "used_cpu_sys_children:%.2f\r\n" - "used_cpu_user_children:%.2f\r\n", - (float) self_ru.ru_stime.tv_sec + (float) self_ru.ru_stime.tv_usec / 1000000, - (float) self_ru.ru_utime.tv_sec + (float) self_ru.ru_utime.tv_usec / 1000000, - (float) c_ru.ru_stime.tv_sec + (float) c_ru.ru_stime.tv_usec / 1000000, - (float) c_ru.ru_utime.tv_sec + (float) c_ru.ru_utime.tv_usec / 1000000); + "# CPU\r\n" + "used_cpu_sys:%.2f\r\n" + "used_cpu_user:%.2f\r\n" + "used_cpu_sys_children:%.2f\r\n" + "used_cpu_user_children:%.2f\r\n", + (float)self_ru.ru_stime.tv_sec+(float)self_ru.ru_stime.tv_usec/1000000, + (float)self_ru.ru_utime.tv_sec+(float)self_ru.ru_utime.tv_usec/1000000, + (float)c_ru.ru_stime.tv_sec+(float)c_ru.ru_stime.tv_usec/1000000, + (float)c_ru.ru_utime.tv_sec+(float)c_ru.ru_utime.tv_usec/1000000); } /* Command statistics */ - if (allsections || !strcasecmp(section, "commandstats")) { - if (sections++) info = sdscat(info, "\r\n"); + if (allsections || !strcasecmp(section,"commandstats")) { + if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Commandstats\r\n"); struct redisCommand *c; dictEntry *de; dictIterator *di; di = dictGetSafeIterator(server.commands); - while ((de = dictNext(di)) != NULL) { + while((de = dictNext(di)) != NULL) { c = (struct redisCommand *) dictGetVal(de); if (!c->calls) continue; info = sdscatprintf(info, "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n", c->name, c->calls, c->microseconds, - (c->calls == 0) ? 0 : ((float) c->microseconds / c->calls)); + (c->calls == 0) ? 0 : ((float)c->microseconds/c->calls)); } dictReleaseIterator(di); } /* Cluster */ - if (allsections || defsections || !strcasecmp(section, "cluster")) { - if (sections++) info = sdscat(info, "\r\n"); + if (allsections || defsections || !strcasecmp(section,"cluster")) { + if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, - "# Cluster\r\n" - "cluster_enabled:%d\r\n", - server.cluster_enabled); + "# Cluster\r\n" + "cluster_enabled:%d\r\n", + server.cluster_enabled); } /* Key space */ - if (allsections || defsections || !strcasecmp(section, "keyspace")) { - if (sections++) info = sdscat(info, "\r\n"); + if (allsections || defsections || !strcasecmp(section,"keyspace")) { + if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Keyspace\r\n"); for (j = 0; j < server.dbnum; j++) { PORT_LONGLONG keys, vkeys; @@ -3459,7 +3425,7 @@ void infoCommand(client *c) { char *section = c->argc == 2 ? c->argv[1]->ptr : "default"; if (c->argc > 2) { - addReply(c, shared.syntaxerr); + addReply(c,shared.syntaxerr); return; } addReplyBulkSds(c, genRedisInfoString(section)); @@ -3469,20 +3435,20 @@ void monitorCommand(client *c) { /* ignore MONITOR if already slave or in monitor mode */ if (c->flags & CLIENT_SLAVE) return; - c->flags |= (CLIENT_SLAVE | CLIENT_MONITOR); - listAddNodeTail(server.monitors, c); - addReply(c, shared.ok); + c->flags |= (CLIENT_SLAVE|CLIENT_MONITOR); + listAddNodeTail(server.monitors,c); + addReply(c,shared.ok); } /* =================================== Main! ================================ */ #ifdef __linux__ int linuxOvercommitMemoryValue(void) { - FILE *fp = fopen("/proc/sys/vm/overcommit_memory", "r"); + FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r"); char buf[64]; if (!fp) return -1; - if (fgets(buf, 64, fp) == NULL) { + if (fgets(buf,64,fp) == NULL) { fclose(fp); return -1; } @@ -3493,10 +3459,10 @@ int linuxOvercommitMemoryValue(void) { void linuxMemoryWarnings(void) { if (linuxOvercommitMemoryValue() == 0) { - serverLog(LL_WARNING, "WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect."); + serverLog(LL_WARNING,"WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect."); } if (THPIsEnabled()) { - serverLog(LL_WARNING, "WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled."); + serverLog(LL_WARNING,"WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled."); } } #endif /* __linux__ */ @@ -3507,9 +3473,9 @@ void createPidFile(void) { if (!server.pidfile) server.pidfile = zstrdup(CONFIG_DEFAULT_PID_FILE); /* Try to write the pid file in a best-effort way. */ - FILE *fp = fopen(server.pidfile, "w"); + FILE *fp = fopen(server.pidfile,"w"); if (fp) { - fprintf(fp, "%d\n", (int) getpid()); + fprintf(fp,"%d\n",(int)getpid()); fclose(fp); } } @@ -3536,7 +3502,7 @@ void daemonize(void) { } void version(void) { - printf("Redis server v=%s sha=%s:%d malloc=%s bits=%d build=%llx\n", /* TODO: verify %llx */ + printf("Redis server v=%s sha=%s:%d malloc=%s bits=%d build=%llx\n", REDIS_VERSION, redisGitSHA1(), atoi(redisGitDirty()) > 0, @@ -3547,25 +3513,25 @@ void version(void) { } void usage(void) { - fprintf(stderr, "Usage: ./redis-server [/path/to/redis.conf] [options]\n"); - fprintf(stderr, " ./redis-server - (read config from stdin)\n"); - fprintf(stderr, " ./redis-server -v or --version\n"); - fprintf(stderr, " ./redis-server -h or --help\n"); - fprintf(stderr, " ./redis-server --test-memory \n\n"); - fprintf(stderr, "Examples:\n"); - fprintf(stderr, " ./redis-server (run the server with default conf)\n"); - fprintf(stderr, " ./redis-server /etc/redis/6379.conf\n"); - fprintf(stderr, " ./redis-server --port 7777\n"); - fprintf(stderr, " ./redis-server --port 7777 --slaveof 127.0.0.1 8888\n"); - fprintf(stderr, " ./redis-server /etc/myredis.conf --loglevel verbose\n\n"); - fprintf(stderr, "Sentinel mode:\n"); - fprintf(stderr, " ./redis-server /etc/sentinel.conf --sentinel\n"); + fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf] [options]\n"); + fprintf(stderr," ./redis-server - (read config from stdin)\n"); + fprintf(stderr," ./redis-server -v or --version\n"); + fprintf(stderr," ./redis-server -h or --help\n"); + fprintf(stderr," ./redis-server --test-memory \n\n"); + fprintf(stderr,"Examples:\n"); + fprintf(stderr," ./redis-server (run the server with default conf)\n"); + fprintf(stderr," ./redis-server /etc/redis/6379.conf\n"); + fprintf(stderr," ./redis-server --port 7777\n"); + fprintf(stderr," ./redis-server --port 7777 --slaveof 127.0.0.1 8888\n"); + fprintf(stderr," ./redis-server /etc/myredis.conf --loglevel verbose\n\n"); + fprintf(stderr,"Sentinel mode:\n"); + fprintf(stderr," ./redis-server /etc/sentinel.conf --sentinel\n"); exit(1); } void redisAsciiArt(void) { #include "asciilogo.h" - char *buf = zmalloc(1024 * 16); + char *buf = zmalloc(1024*16); char *mode; if (server.cluster_enabled) mode = "cluster"; @@ -3576,26 +3542,25 @@ void redisAsciiArt(void) { * tty AND syslog logging is disabled. Also show logo if the user * forced us to do so via redis.conf. */ int show_logo = ((!server.syslog_enabled && - server.logfile[0] == '\0' && - isatty(fileno(stdout))) || - server.always_show_logo); + server.logfile[0] == '\0' && + isatty(fileno(stdout))) || + server.always_show_logo); if (!show_logo) { serverLog(LL_NOTICE, "Running mode=%s, port=%d.", mode, server.port ); - } - else { - snprintf(buf, 1024 * 16, ascii_logo, + } else { + snprintf(buf,1024*16,ascii_logo, REDIS_VERSION, redisGitSHA1(), - strtol(redisGitDirty(), NULL, 10) > 0, + strtol(redisGitDirty(),NULL,10) > 0, (sizeof(PORT_LONG) == 8) ? "64" : "32", mode, server.port, (PORT_LONG) getpid() ); - serverLogRaw(LL_NOTICE | LL_RAW, buf); + serverLogRaw(LL_NOTICE|LL_RAW,buf); } zfree(buf); } @@ -3622,8 +3587,7 @@ static void sigShutdownHandler(int sig) { serverLogFromHandler(LL_WARNING, "You insist... exiting now."); rdbRemoveTempFile(getpid()); exit(1); /* Exit with an error since this was not a clean shutdown. */ - } - else if (server.loading) { + } else if (server.loading) { exit(0); } @@ -3661,9 +3625,9 @@ void memtest(size_t megabytes, int passes); int checkForSentinelMode(int argc, char **argv) { int j; - if (strstr(argv[0], "redis-sentinel") != NULL) return 1; + if (strstr(argv[0],"redis-sentinel") != NULL) return 1; for (j = 1; j < argc; j++) - if (!strcmp(argv[j], "--sentinel")) return 1; + if (!strcmp(argv[j],"--sentinel")) return 1; return 0; } @@ -3672,33 +3636,32 @@ void loadDataFromDisk(void) { PORT_LONGLONG start = ustime(); if (server.aof_state == AOF_ON) { if (loadAppendOnlyFile(server.aof_filename) == C_OK) - serverLog(LL_NOTICE, "DB loaded from append only file: %.3f seconds", (float) (ustime() - start) / 1000000); - } - else { + serverLog(LL_NOTICE,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start)/1000000); + } else { rdbSaveInfo rsi = RDB_SAVE_INFO_INIT; - if (rdbLoad(server.rdb_filename, &rsi) == C_OK) { - serverLog(LL_NOTICE, "DB loaded from disk: %.3f seconds", - (float) (ustime() - start) / 1000000); + if (rdbLoad(server.rdb_filename,&rsi) == C_OK) { + serverLog(LL_NOTICE,"DB loaded from disk: %.3f seconds", + (float)(ustime()-start)/1000000); /* Restore the replication ID / offset from the RDB file. */ if (server.masterhost && rsi.repl_id_is_set && rsi.repl_offset != -1 && /* Note that older implementations may save a repl_stream_db - * of -1 inside the RDB file. */ + * of -1 inside the RDB file in a wrong way, see more information + * in function rdbPopulateSaveInfo. */ rsi.repl_stream_db != -1) { - memcpy(server.replid, rsi.repl_id, sizeof(server.replid)); + memcpy(server.replid,rsi.repl_id,sizeof(server.replid)); server.master_repl_offset = rsi.repl_offset; /* If we are a slave, create a cached master from this * information, in order to allow partial resynchronizations * with masters. */ replicationCacheMasterUsingMyself(); - selectDb(server.cached_master, rsi.repl_stream_db); + selectDb(server.cached_master,rsi.repl_stream_db); } - } - else if (errno != ENOENT) { - serverLog(LL_WARNING, "Fatal error loading the DB: %s. Exiting.", IF_WIN32(wsa_strerror(errno), strerror(errno))); + } else if (errno != ENOENT) { + serverLog(LL_WARNING,"Fatal error loading the DB: %s. Exiting.", IF_WIN32(wsa_strerror(errno), strerror(errno))); exit(1); } } @@ -3706,8 +3669,8 @@ void loadDataFromDisk(void) { void redisOutOfMemoryHandler(size_t allocation_size) { WIN32_ONLY(bugReportStart();) - serverLog(LL_WARNING, "Out Of Memory allocating %Iu bytes.", WIN_PORT_FIX /* %zu -> %Iu */ - allocation_size); + serverLog(LL_WARNING,"Out Of Memory allocating %Iu bytes.", WIN_PORT_FIX /* %zu -> %Iu */ + allocation_size); IF_WIN32(abort(), serverPanic("Redis aborting for OUT OF MEMORY")); } @@ -3737,7 +3700,7 @@ int redisSupervisedUpstart(void) { if (!upstart_job) { serverLog(LL_WARNING, - "upstart supervision requested, but UPSTART_JOB not found"); + "upstart supervision requested, but UPSTART_JOB not found"); return 0; } @@ -3760,7 +3723,7 @@ int redisSupervisedSystemd(void) { if (!notify_socket) { serverLog(LL_WARNING, - "systemd supervision requested, but NOTIFY_SOCKET not found"); + "systemd supervision requested, but NOTIFY_SOCKET not found"); return 0; } @@ -3771,13 +3734,13 @@ int redisSupervisedSystemd(void) { serverLog(LL_NOTICE, "supervised by systemd, will signal readiness"); if ((fd = socket(AF_UNIX, SOCK_DGRAM, 0)) == -1) { serverLog(LL_WARNING, - "Can't connect to systemd socket %s", notify_socket); + "Can't connect to systemd socket %s", notify_socket); return 0; } memset(&su, 0, sizeof(su)); su.sun_family = AF_UNIX; - strncpy(su.sun_path, notify_socket, sizeof(su.sun_path) - 1); + strncpy (su.sun_path, notify_socket, sizeof(su.sun_path) -1); su.sun_path[sizeof(su.sun_path) - 1] = '\0'; if (notify_socket[0] == '@') @@ -3816,21 +3779,19 @@ int redisIsSupervised(int mode) { if (upstart_job) { redisSupervisedUpstart(); - } - else if (notify_socket) { + } else if (notify_socket) { redisSupervisedSystemd(); } - } - else if (mode == SUPERVISED_UPSTART) { + } else if (mode == SUPERVISED_UPSTART) { return redisSupervisedUpstart(); - } - else if (mode == SUPERVISED_SYSTEMD) { + } else if (mode == SUPERVISED_SYSTEMD) { return redisSupervisedSystemd(); } return 0; } + int main(int argc, char **argv) { struct timeval tv; int j; @@ -3839,29 +3800,21 @@ int main(int argc, char **argv) { if (argc == 3 && !strcasecmp(argv[1], "test")) { if (!strcasecmp(argv[2], "ziplist")) { return ziplistTest(argc, argv); - } - else if (!strcasecmp(argv[2], "quicklist")) { + } else if (!strcasecmp(argv[2], "quicklist")) { quicklistTest(argc, argv); - } - else if (!strcasecmp(argv[2], "intset")) { + } else if (!strcasecmp(argv[2], "intset")) { return intsetTest(argc, argv); - } - else if (!strcasecmp(argv[2], "zipmap")) { + } else if (!strcasecmp(argv[2], "zipmap")) { return zipmapTest(argc, argv); - } - else if (!strcasecmp(argv[2], "sha1test")) { + } else if (!strcasecmp(argv[2], "sha1test")) { return sha1Test(argc, argv); - } - else if (!strcasecmp(argv[2], "util")) { + } else if (!strcasecmp(argv[2], "util")) { return utilTest(argc, argv); - } - else if (!strcasecmp(argv[2], "sds")) { + } else if (!strcasecmp(argv[2], "sds")) { return sdsTest(argc, argv); - } - else if (!strcasecmp(argv[2], "endianconv")) { + } else if (!strcasecmp(argv[2], "endianconv")) { return endianconvTest(argc, argv); - } - else if (!strcasecmp(argv[2], "crc64")) { + } else if (!strcasecmp(argv[2], "crc64")) { return crc64Test(argc, argv); } @@ -3873,7 +3826,7 @@ int main(int argc, char **argv) { #ifdef INIT_SETPROCTITLE_REPLACEMENT spt_init(argc, argv); #endif - setlocale(LC_COLLATE, ""); + setlocale(LC_COLLATE,""); zmalloc_set_oom_handler(redisOutOfMemoryHandler); #ifdef _WIN32 @@ -3884,19 +3837,19 @@ int main(int argc, char **argv) { pthread_mutex_init(&moduleGIL, NULL); #endif - srand((unsigned int) time(NULL) ^ getpid()); WIN_PORT_FIX /* cast (unsigned int) */ - gettimeofday(&tv, NULL); + srand((unsigned int)time(NULL)^getpid()); WIN_PORT_FIX /* cast (unsigned int) */ + gettimeofday(&tv,NULL); char hashseed[16]; - getRandomHexChars(hashseed, sizeof(hashseed)); - dictSetHashFunctionSeed((uint8_t*) hashseed); - server.sentinel_mode = checkForSentinelMode(argc, argv); + getRandomHexChars(hashseed,sizeof(hashseed)); + dictSetHashFunctionSeed((uint8_t*)hashseed); + server.sentinel_mode = checkForSentinelMode(argc,argv); initServerConfig(); moduleInitModulesSystem(); /* Store the executable path and arguments in a safe place in order * to be able to restart the server later. */ server.executable = getAbsolutePath(argv[0]); - server.exec_argv = zmalloc(sizeof(char*)*(argc + 1)); + server.exec_argv = zmalloc(sizeof(char*)*(argc+1)); server.exec_argv[argc] = NULL; for (j = 0; j < argc; j++) server.exec_argv[j] = zstrdup(argv[j]); @@ -3911,16 +3864,16 @@ int main(int argc, char **argv) { /* Check if we need to start in redis-check-rdb/aof mode. We just execute * the program main. However the program is part of the Redis executable * so that we can easily execute an RDB check on loading errors. */ - if (strstr(argv[0], "redis-check-rdb") != NULL) + if (strstr(argv[0],"redis-check-rdb") != NULL) #ifdef _WIN32 return #endif - redis_check_rdb_main(argc, argv, NULL); - else if (strstr(argv[0], "redis-check-aof") != NULL) + redis_check_rdb_main(argc,argv,NULL); + else if (strstr(argv[0],"redis-check-aof") != NULL) #ifdef _WIN32 return #endif - redis_check_aof_main(argc, argv); + redis_check_aof_main(argc,argv); if (argc >= 2) { j = 1; /* First option to parse in argv[] */ @@ -3936,10 +3889,9 @@ int main(int argc, char **argv) { if (argc == 3) { memtest(atoi(argv[2]), IF_WIN32(5, 50)); exit(0); - } - else { - fprintf(stderr, "Please specify the amount of memory to test in megabytes.\n"); - fprintf(stderr, "Example: ./redis-server --test-memory 4096\n\n"); + } else { + fprintf(stderr,"Please specify the amount of memory to test in megabytes.\n"); + fprintf(stderr,"Example: ./redis-server --test-memory 4096\n\n"); exit(1); } } @@ -3959,7 +3911,7 @@ int main(int argc, char **argv) { * configuration file. For instance --port 6380 will generate the * string "port 6380\n" to be parsed after the actual file name * is parsed, if any. */ - while (j != argc) { + while(j != argc) { if (argv[j][0] == '-' && argv[j][1] == '-') { /* Option name */ if (!strcmp(argv[j], "--check-rdb")) { @@ -3967,14 +3919,13 @@ int main(int argc, char **argv) { j++; continue; } - if (sdslen(options)) options = sdscat(options, "\n"); - options = sdscat(options, argv[j] + 2); - options = sdscat(options, " "); - } - else { + if (sdslen(options)) options = sdscat(options,"\n"); + options = sdscat(options,argv[j]+2); + options = sdscat(options," "); + } else { /* Option argument */ - options = sdscatrepr(options, argv[j], strlen(argv[j])); - options = sdscat(options, " "); + options = sdscatrepr(options,argv[j],strlen(argv[j])); + options = sdscat(options," "); } j++; } @@ -3986,23 +3937,22 @@ int main(int argc, char **argv) { exit(1); } resetServerSaveParams(); - loadServerConfig(configfile, options); + loadServerConfig(configfile,options); sdsfree(options); } serverLog(LL_WARNING, "oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo"); serverLog(LL_WARNING, "Redis version=%s, bits=%d, commit=%s, modified=%d, pid=%d, just started", - REDIS_VERSION, - (sizeof(PORT_LONG) == 8) ? 64 : 32, - redisGitSHA1(), - strtol(redisGitDirty(), NULL, 10) > 0, - (int) getpid()); + REDIS_VERSION, + (sizeof(PORT_LONG) == 8) ? 64 : 32, + redisGitSHA1(), + strtol(redisGitDirty(),NULL,10) > 0, + (int)getpid()); if (argc == 1) { serverLog(LL_WARNING, "Warning: no config file specified, using the default config. In order to specify a config file use %s /path/to/%s.conf", argv[0], server.sentinel_mode ? "sentinel" : "redis"); - } - else { + } else { serverLog(LL_WARNING, "Configuration loaded"); } @@ -4018,10 +3968,10 @@ int main(int argc, char **argv) { if (!server.sentinel_mode) { /* Things not needed when running in Sentinel mode. */ - serverLog(LL_WARNING, "Server initialized"); -#ifdef __linux__ + serverLog(LL_WARNING,"Server initialized"); + #ifdef __linux__ linuxMemoryWarnings(); -#endif + #endif moduleLoadFromQueue(); loadDataFromDisk(); if (server.cluster_enabled) { @@ -4033,24 +3983,23 @@ int main(int argc, char **argv) { } } if (server.ipfd_count > 0) - serverLog(LL_NOTICE, "Ready to accept connections"); + serverLog(LL_NOTICE,"Ready to accept connections"); if (server.sofd > 0) - serverLog(LL_NOTICE, "The server is now ready to accept connections at %s", server.unixsocket); - } - else { + serverLog(LL_NOTICE,"The server is now ready to accept connections at %s", server.unixsocket); + } else { sentinelIsRunning(); } /* Warning the user about suspicious maxmemory setting. */ - if (server.maxmemory > 0 && server.maxmemory < 1024 * 1024) { - serverLog(LL_WARNING, "WARNING: You specified a maxmemory value that is less than 1MB (current value is %llu bytes). Are you sure this is what you really want?", server.maxmemory); + if (server.maxmemory > 0 && server.maxmemory < 1024*1024) { + serverLog(LL_WARNING,"WARNING: You specified a maxmemory value that is less than 1MB (current value is %llu bytes). Are you sure this is what you really want?", server.maxmemory); } - aeSetBeforeSleepProc(server.el, beforeSleep); - aeSetAfterSleepProc(server.el, afterSleep); + aeSetBeforeSleepProc(server.el,beforeSleep); + aeSetAfterSleepProc(server.el,afterSleep); aeMain(server.el); aeDeleteEventLoop(server.el); return 0; } -/* The End */ \ No newline at end of file +/* The End */ diff --git a/src/server.h b/src/server.h index 84d172cf..366b252a 100644 --- a/src/server.h +++ b/src/server.h @@ -52,14 +52,14 @@ #include POSIX_ONLY(#include ) #include -POSIX_ONLY(#include ) #ifndef _WIN32 +#include #include +#include +#include #else #include "Win32_Interop\Win32_PThread.h" #endif -POSIX_ONLY(#include ) -POSIX_ONLY(#include ) #include #include @@ -195,7 +195,7 @@ POSIX_ONLY(#define LOG_MAX_LEN 1024) /* Default maximum length of syslog mess #define PROTO_REPLY_CHUNK_BYTES (16*1024) /* 16k output buffer */ #define PROTO_INLINE_MAX_SIZE (1024*64) /* Max size of inline reads */ #define PROTO_MBULK_BIG_ARG (1024*32) -#define LONG_STR_SIZE 21 /* Bytes needed for PORT_LONG -> str + '\0' */ +#define LONG_STR_SIZE 21 /* Bytes needed for long -> str + '\0' */ #define AOF_AUTOSYNC_BYTES (1024*1024*32) /* fdatasync every 32MB */ /* When configuring the server eventloop, we setup it so that the total number @@ -439,7 +439,7 @@ POSIX_ONLY(#define CONFIG_DEFAULT_VERBOSITY LL_NOTICE) #define NOTIFY_ZSET (1<<7) /* z */ #define NOTIFY_EXPIRED (1<<8) /* x */ #define NOTIFY_EVICTED (1<<9) /* e */ -#define NOTIFY_ALL (NOTIFY_GENERIC | NOTIFY_STRING | NOTIFY_LIST | NOTIFY_SET | NOTIFY_HASH | NOTIFY_ZSET | NOTIFY_EXPIRED | NOTIFY_EVICTED) /* A */ +#define NOTIFY_ALL (NOTIFY_GENERIC | NOTIFY_STRING | NOTIFY_LIST | NOTIFY_SET | NOTIFY_HASH | NOTIFY_ZSET | NOTIFY_EXPIRED | NOTIFY_EVICTED) /* A flag */ /* Get the first bind addr or NULL */ #define NET_FIRST_BIND_ADDR (server.bindaddr_count ? server.bindaddr[0] : NULL) @@ -737,7 +737,7 @@ typedef struct client { dict *pubsub_channels; /* channels a client is interested in (SUBSCRIBE) */ list *pubsub_patterns; /* patterns a client is interested in (SUBSCRIBE) */ sds peerid; /* Cached peer ID. */ - listNode *client_list_node; /* list node in client list */ + listNode *client_list_node; /* list node in client list */ WIN32_ONLY(char replFileCopy[_MAX_PATH];) /* Response buffer */ @@ -904,7 +904,7 @@ struct redisServer { int active_defrag_running; /* Active defragmentation running (holds current scan aggressiveness) */ char *requirepass; /* Pass for AUTH command, or NULL */ char *pidfile; /* PID file path */ - int arch_bits; /* 32 or 64 depending on sizeof(PORT_LONG) */ + int arch_bits; /* 32 or 64 depending on sizeof(long) */ int cronloops; /* Number of times the cron function run */ char runid[CONFIG_RUN_ID_SIZE+1]; /* ID always different at every exec. */ int sentinel_mode; /* True if this instance is a Sentinel. */ @@ -1425,7 +1425,7 @@ void addReplyStatusFormat(client *c, const char *fmt, ...); void listTypeTryConversion(robj *subject, robj *value); void listTypePush(robj *subject, robj *value, int where); robj *listTypePop(robj *subject, int where); -PORT_ULONG listTypeLength(robj *subject); +PORT_ULONG listTypeLength(const robj *subject); listTypeIterator *listTypeInitIterator(robj *subject, PORT_LONG index, unsigned char direction); void listTypeReleaseIterator(listTypeIterator *li); int listTypeNext(listTypeIterator *li, listTypeEntry *entry); diff --git a/src/setproctitle.c b/src/setproctitle.c index f44253e1..6563242d 100644 --- a/src/setproctitle.c +++ b/src/setproctitle.c @@ -39,7 +39,11 @@ #include /* errno program_invocation_name program_invocation_short_name */ #if !defined(HAVE_SETPROCTITLE) -#define HAVE_SETPROCTITLE (defined __NetBSD__ || defined __FreeBSD__ || defined __OpenBSD__) +#if (defined __NetBSD__ || defined __FreeBSD__ || defined __OpenBSD__) +#define HAVE_SETPROCTITLE 1 +#else +#define HAVE_SETPROCTITLE 0 +#endif #endif diff --git a/src/slowlog.c b/src/slowlog.c index e2d9d84b..e8b14f86 100644 --- a/src/slowlog.c +++ b/src/slowlog.c @@ -61,7 +61,7 @@ slowlogEntry *slowlogCreateEntry(client *c, robj **argv, int argc, PORT_LONGLONG sdscatprintf(sdsempty(),"... (%d more arguments)", argc-slargc+1)); } else { - /* Trim too PORT_LONG strings as well... */ + /* Trim too long strings as well... */ if (argv[j]->type == OBJ_STRING && sdsEncodedObject(argv[j]) && sdslen(argv[j]->ptr) > SLOWLOG_ENTRY_MAX_STRING) diff --git a/src/t_hash.c b/src/t_hash.c index 2d37e221..786f9643 100644 --- a/src/t_hash.c +++ b/src/t_hash.c @@ -287,8 +287,8 @@ int hashTypeDelete(robj *o, sds field) { if (fptr != NULL) { fptr = ziplistFind(fptr, (unsigned char*)field, (unsigned int)sdslen(field), 1); WIN_PORT_FIX /* cast (unsigned int) */ if (fptr != NULL) { - zl = ziplistDelete(zl,&fptr); - zl = ziplistDelete(zl,&fptr); + zl = ziplistDelete(zl,&fptr); /* Delete the key. */ + zl = ziplistDelete(zl,&fptr); /* Delete the value. */ o->ptr = zl; deleted = 1; } diff --git a/src/t_list.c b/src/t_list.c index ffb700e2..a2a77ca0 100644 --- a/src/t_list.c +++ b/src/t_list.c @@ -213,7 +213,7 @@ void pushGenericCommand(client *c, int where) { listTypePush(lobj,c->argv[j],where); pushed++; } - addReplyLongLong(c, (lobj ? listTypeLength(lobj) : (robj*)0)); + addReplyLongLong(c, (lobj ? listTypeLength(lobj) : 0)); if (pushed) { char *event = (where == LIST_HEAD) ? "lpush" : "rpush"; @@ -596,9 +596,9 @@ void rpoplpushCommand(client *c) { signalModifiedKey(c->db,touchedkey); decrRefCount(touchedkey); server.dirty++; - if (c->cmd->proc == brpoplpushCommand) { - rewriteClientCommandVector(c,3,shared.rpoplpush,c->argv[1],c->argv[2]); - } + if (c->cmd->proc == brpoplpushCommand) { + rewriteClientCommandVector(c,3,shared.rpoplpush,c->argv[1],c->argv[2]); + } } } diff --git a/src/t_set.c b/src/t_set.c index ddbfee51..39395dcb 100644 --- a/src/t_set.c +++ b/src/t_set.c @@ -407,7 +407,7 @@ void spopWithCountCommand(client *c) { /* Get the count argument */ if (getLongFromObjectOrReply(c,c->argv[2],&l,NULL) != C_OK) return; if (l >= 0) { - count = (unsigned) l; + count = (PORT_ULONG) l; } else { addReply(c,shared.outofrangeerr); return; @@ -626,7 +626,7 @@ void srandmemberWithCountCommand(client *c) { if (getLongFromObjectOrReply(c,c->argv[2],&l,NULL) != C_OK) return; if (l >= 0) { - count = (unsigned) l; + count = (PORT_ULONG) l; } else { /* A negative count means: return the same elements multiple times * (i.e. don't remove the extracted element after every extraction). */ diff --git a/src/t_zset.c b/src/t_zset.c index f8869235..9f9117cb 100644 --- a/src/t_zset.c +++ b/src/t_zset.c @@ -601,8 +601,8 @@ int zslIsInLexRange(zskiplist *zsl, zlexrangespec *range) { zskiplistNode *x; /* Test for ranges that will always be empty. */ - int cmp = sdscmplex(range->min,range->max); - if (cmp > 0 || (cmp == 0 && (range->minex || range->maxex))) + int cmp = sdscmplex(range->min,range->max); + if (cmp > 0 || (cmp == 0 && (range->minex || range->maxex))) return 0; x = zsl->tail; if (x == NULL || !zslLexValueGteMin(x->ele,range)) @@ -715,7 +715,7 @@ int zzlCompareElements(unsigned char *eptr, unsigned char *cstr, unsigned int cl serverAssert(ziplistGet(eptr,&vstr,&vlen,&vlong)); if (vstr == NULL) { - /* Store string representation of PORT_LONGLONG in buf. */ + /* Store string representation of long long in buf. */ vlen = ll2string((char*)vbuf,sizeof(vbuf),vlong); vstr = vbuf; } @@ -875,8 +875,8 @@ int zzlIsInLexRange(unsigned char *zl, zlexrangespec *range) { unsigned char *p; /* Test for ranges that will always be empty. */ - int cmp = sdscmplex(range->min,range->max); - if (cmp > 0 || (cmp == 0 && (range->minex || range->maxex))) + int cmp = sdscmplex(range->min,range->max); + if (cmp > 0 || (cmp == 0 && (range->minex || range->maxex))) return 0; p = ziplistIndex(zl,-2); /* Last element. */ @@ -1794,10 +1794,10 @@ typedef struct { /* Use dirty flags for pointers that need to be cleaned up in the next - * iteration over the zsetopval. The dirty flag for the PORT_LONGLONG value is - * special, since PORT_LONGLONG values don't need cleanup. Instead, it means that - * we already checked that "ell" holds a PORT_LONGLONG, or tried to convert another - * representation into a PORT_LONGLONG value. When this was successful, + * iteration over the zsetopval. The dirty flag for the long long value is + * special, since long long values don't need cleanup. Instead, it means that + * we already checked that "ell" holds a long long, or tried to convert another + * representation into a long long value. When this was successful, * OPVAL_VALID_LL is set as well. */ #define OPVAL_DIRTY_SDS 1 #define OPVAL_DIRTY_LL 2 @@ -1981,7 +1981,7 @@ int zuiLongLongFromValue(zsetopval *val) { if (string2ll((char*)val->estr,val->elen,&val->ell)) val->flags |= OPVAL_VALID_LL; } else { - /* The PORT_LONGLONG was already set, flag as valid. */ + /* The long long was already set, flag as valid. */ val->flags |= OPVAL_VALID_LL; } } @@ -2858,10 +2858,10 @@ void genericZrangebylexCommand(client *c, int reverse) { while (remaining) { if (remaining >= 3 && !strcasecmp(c->argv[pos]->ptr,"limit")) { if ((getLongFromObjectOrReply(c, c->argv[pos+1], &offset, NULL) != C_OK) || - (getLongFromObjectOrReply(c,c->argv[pos + 2],&limit,NULL) != C_OK)) { - zslFreeLexRange(&range); - return; - } + (getLongFromObjectOrReply(c, c->argv[pos+2], &limit, NULL) != C_OK)) { + zslFreeLexRange(&range); + return; + } pos += 3; remaining -= 3; } else { zslFreeLexRange(&range); diff --git a/src/util.c b/src/util.c index 5981b78d..dd6296ef 100644 --- a/src/util.c +++ b/src/util.c @@ -56,7 +56,7 @@ POSIX_ONLY(#include ) int stringmatchlen(const char *pattern, int patternLen, const char *string, int stringLen, int nocase) { - while (patternLen && stringLen) { + while(patternLen && stringLen) { switch(pattern[0]) { case '*': while (pattern[1] == '*') { @@ -272,7 +272,7 @@ uint32_t sdigits10(int64_t v) { } } -/* Convert a PORT_LONGLONG into a string. Returns the number of +/* Convert a long long into a string. Returns the number of * characters needed to represent the number. * If the buffer is not big enough to store the string, 0 is returned. * @@ -337,17 +337,17 @@ int ll2string(char *dst, size_t dstlen, PORT_LONGLONG svalue) { return length; } -/* Convert a string into a PORT_LONGLONG. Returns 1 if the string could be parsed - * into a (non-overflowing) PORT_LONGLONG, 0 otherwise. The value will be set to +/* Convert a string into a long long. Returns 1 if the string could be parsed + * into a (non-overflowing) long long, 0 otherwise. The value will be set to * the parsed value when appropriate. * * Note that this function demands that the string strictly represents - * a PORT_LONGLONG: no spaces or other characters before or after the string + * a long long: no spaces or other characters before or after the string * representing the number are accepted, nor zeroes at the start if not * for the string "0" representing the zero number. * * Because of its strictness, it is safe to use this function to check if - * you can convert a string into a PORT_LONGLONG, and obtain back the string + * you can convert a string into a long long, and obtain back the string * from the number without any loss in the string representation. */ int string2ll(const char *s, size_t slen, PORT_LONGLONG *value) { const char *p = s; @@ -479,12 +479,12 @@ int d2string(char *buf, size_t len, double value) { } else { #if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL) /* Check if the float is in a safe range to be casted into a - * PORT_LONGLONG. We are assuming that PORT_LONGLONG is 64 bit here. + * long long. We are assuming that long long is 64 bit here. * Also we are assuming that there are no implementations around where * double has precision < 52 bit. * * Under this assumptions we test if a double is inside an interval - * where casting to PORT_LONGLONG is safe. Then using two castings we + * where casting to long long is safe. Then using two castings we * make sure the decimal part is zero. If all this is true we use * integer printing function that is much faster. */ double min = -4503599627370495; /* (2^52)-1 */ @@ -499,7 +499,7 @@ int d2string(char *buf, size_t len, double value) { return (int)len; WIN_PORT_FIX /* cast (int) */ } -/* Convert a PORT_LONGDOUBLE into a string. If humanfriendly is non-zero +/* Convert a long double into a string. If humanfriendly is non-zero * it does not use exponential format and trims trailing zeroes at the end, * however this results in loss of precision. Otherwise exp format is used * and the output of snprintf() is not modified. diff --git a/src/ziplist.c b/src/ziplist.c index 6f17401e..5d9e643a 100644 --- a/src/ziplist.c +++ b/src/ziplist.c @@ -444,7 +444,7 @@ unsigned int zipStorePrevEntryLength(unsigned char *p, unsigned int len) { if ((prevlensize) == 1) { \ (prevlen) = (ptr)[0]; \ } else if ((prevlensize) == 5) { \ - assert(sizeof((prevlensize)) == 4); \ + assert(sizeof((prevlen)) == 4); \ memcpy(&(prevlen), ((char*)(ptr)) + 1, 4); \ memrev32ifbe(&prevlen); \ } \ @@ -1284,13 +1284,13 @@ static unsigned char *createIntList() { return zl; } -PORT_LONGLONG usec(void) { +static PORT_LONGLONG usec(void) { #ifdef _WIN32 return GetHighResRelativeTime(1000000); #else struct timeval tv; gettimeofday(&tv,NULL); - return (((PORT_LONGLONG)tv.tv_sec)*1000000)+tv.tv_usec; + return (((long long)tv.tv_sec)*1000000)+tv.tv_usec; #endif } diff --git a/src/zipmap.c b/src/zipmap.c index 905c3173..459d9f0e 100644 --- a/src/zipmap.c +++ b/src/zipmap.c @@ -169,8 +169,8 @@ static unsigned char *zipmapLookupRaw(unsigned char *zm, unsigned char *key, uns return k; } -static unsigned int zipmapRequiredLength(unsigned int klen, unsigned int vlen) { WIN_PORT_FIX /* PORT_ULONG -> unsigned int */ - unsigned int l; +static PORT_ULONG zipmapRequiredLength(unsigned int klen, unsigned int vlen) { WIN_PORT_FIX /* PORT_ULONG -> unsigned int */ + PORT_ULONG l; l = klen+vlen+3; if (klen >= ZIPMAP_BIGLEN) l += 4; diff --git a/src/zmalloc.c b/src/zmalloc.c index c6aaf219..fc848955 100644 --- a/src/zmalloc.c +++ b/src/zmalloc.c @@ -75,31 +75,6 @@ POSIX_ONLY(#include ) #define free(ptr) je_free(ptr) #define mallocx(size,flags) je_mallocx(size,flags) #define dallocx(ptr,flags) je_dallocx(ptr,flags) -#elif defined(USE_DLMALLOC) -#define malloc(size) g_malloc(size) -#define calloc(count,size) g_calloc(count,size) -#define realloc(ptr,size) g_realloc(ptr,size) -#define free(ptr) g_free(ptr) -#endif - -#if defined(__ATOMIC_RELAXED) -#define update_zmalloc_stat_add(__n) __atomic_add_fetch(&used_memory, (__n), __ATOMIC_RELAXED) -#define update_zmalloc_stat_sub(__n) __atomic_sub_fetch(&used_memory, (__n), __ATOMIC_RELAXED) -#elif defined(HAVE_ATOMIC) -#define update_zmalloc_stat_add(__n) __sync_add_and_fetch(&used_memory, (__n)) -#define update_zmalloc_stat_sub(__n) __sync_sub_and_fetch(&used_memory, (__n)) -#else -#define update_zmalloc_stat_add(__n) do { \ - pthread_mutex_lock(&used_memory_mutex); \ - used_memory += (__n); \ - pthread_mutex_unlock(&used_memory_mutex); \ -} while(0) - -#define update_zmalloc_stat_sub(__n) do { \ - pthread_mutex_lock(&used_memory_mutex); \ - used_memory -= (__n); \ - pthread_mutex_unlock(&used_memory_mutex); \ -} while(0) #endif #define update_zmalloc_stat_alloc(__n) do { \ @@ -115,7 +90,6 @@ POSIX_ONLY(#include ) } while(0) static size_t used_memory = 0; -static int zmalloc_thread_safe = 0; #ifdef _WIN32 pthread_mutex_t used_memory_mutex; #else @@ -213,7 +187,7 @@ void *zrealloc(void *ptr, size_t size) { size_t zmalloc_size(void *ptr) { void *realptr = (char*)ptr-PREFIX_SIZE; size_t size = *((size_t*)realptr); - /* Assume at least that all the allocations are padded at sizeof(PORT_LONG) by + /* Assume at least that all the allocations are padded at sizeof(long) by * the underlying allocator. */ if (size&(sizeof(PORT_LONG)-1)) size += sizeof(PORT_LONG)-(size&(sizeof(PORT_LONG)-1)); return size+PREFIX_SIZE; @@ -252,24 +226,6 @@ size_t zmalloc_used_memory(void) { return um; } -#ifdef _WIN32 -void zmalloc_free_used_memory_mutex(void) { - /* Windows fix: Callabe mutex destroy. */ - if (zmalloc_thread_safe) - pthread_mutex_destroy(&used_memory_mutex); -} -void zmalloc_enable_thread_safeness(void) { - if (!zmalloc_thread_safe) - pthread_mutex_init(&used_memory_mutex,0); - - zmalloc_thread_safe = 1; -} -#else -void zmalloc_enable_thread_safeness(void) { - zmalloc_thread_safe = 1; -} -#endif - void zmalloc_set_oom_handler(void (*oom_handler)(size_t)) { zmalloc_oom_handler = oom_handler; } diff --git a/src/zmalloc.h b/src/zmalloc.h index d5924e4e..4bb09858 100644 --- a/src/zmalloc.h +++ b/src/zmalloc.h @@ -96,7 +96,6 @@ size_t zmalloc_get_private_dirty(PORT_LONG pid); size_t zmalloc_get_smap_bytes_by_field(char *field, PORT_LONG pid); size_t zmalloc_get_memory_size(void); void zlibc_free(void *ptr); -WIN32_ONLY(void zmalloc_free_used_memory_mutex(void);) #ifdef HAVE_DEFRAG void zfree_no_tcache(void *ptr);