Commit e9bb30fd authored by antirez's avatar antirez
Browse files

Experimental: new keyspace and expire algorithm.

This is an alpha quality implementation of a new keyspace representation
and a new expire algorithm for Redis.

This work is described here:

    https://gist.github.com/antirez/b2eb293819666ee104c7fcad71986eb7
parent fd0ee469
......@@ -923,7 +923,7 @@ int rioWriteBulkObject(rio *r, robj *obj) {
/* Emit the commands needed to rebuild a list object.
* The function returns 0 on error, 1 on success. */
int rewriteListObject(rio *r, robj *key, robj *o) {
int rewriteListObject(rio *r, rkey *key, robj *o) {
long long count = 0, items = listTypeLength(o);
if (o->encoding == OBJ_ENCODING_QUICKLIST) {
......@@ -937,7 +937,7 @@ int rewriteListObject(rio *r, robj *key, robj *o) {
AOF_REWRITE_ITEMS_PER_CMD : items;
if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
if (rioWriteBulkString(r,"RPUSH",5) == 0) return 0;
if (rioWriteBulkObject(r,key) == 0) return 0;
if (rioWriteBulkString(r,key->name,key->len) == 0) return 0;
}
if (entry.value) {
......@@ -957,7 +957,7 @@ int rewriteListObject(rio *r, robj *key, robj *o) {
/* Emit the commands needed to rebuild a set object.
* The function returns 0 on error, 1 on success. */
int rewriteSetObject(rio *r, robj *key, robj *o) {
int rewriteSetObject(rio *r, rkey *key, robj *o) {
long long count = 0, items = setTypeSize(o);
if (o->encoding == OBJ_ENCODING_INTSET) {
......@@ -971,7 +971,7 @@ int rewriteSetObject(rio *r, robj *key, robj *o) {
if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
if (rioWriteBulkString(r,"SADD",4) == 0) return 0;
if (rioWriteBulkObject(r,key) == 0) return 0;
if (rioWriteBulkString(r,key->name,key->len) == 0) return 0;
}
if (rioWriteBulkLongLong(r,llval) == 0) return 0;
if (++count == AOF_REWRITE_ITEMS_PER_CMD) count = 0;
......@@ -989,7 +989,7 @@ int rewriteSetObject(rio *r, robj *key, robj *o) {
if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
if (rioWriteBulkString(r,"SADD",4) == 0) return 0;
if (rioWriteBulkObject(r,key) == 0) return 0;
if (rioWriteBulkString(r,key->name,key->len) == 0) return 0;
}
if (rioWriteBulkString(r,ele,sdslen(ele)) == 0) return 0;
if (++count == AOF_REWRITE_ITEMS_PER_CMD) count = 0;
......@@ -1004,7 +1004,7 @@ int rewriteSetObject(rio *r, robj *key, robj *o) {
/* Emit the commands needed to rebuild a sorted set object.
* The function returns 0 on error, 1 on success. */
int rewriteSortedSetObject(rio *r, robj *key, robj *o) {
int rewriteSortedSetObject(rio *r, rkey *key, robj *o) {
long long count = 0, items = zsetLength(o);
if (o->encoding == OBJ_ENCODING_ZIPLIST) {
......@@ -1030,7 +1030,7 @@ int rewriteSortedSetObject(rio *r, robj *key, robj *o) {
if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
if (rioWriteBulkString(r,"ZADD",4) == 0) return 0;
if (rioWriteBulkObject(r,key) == 0) return 0;
if (rioWriteBulkString(r,key->name,key->len) == 0) return 0;
}
if (rioWriteBulkDouble(r,score) == 0) return 0;
if (vstr != NULL) {
......@@ -1057,7 +1057,7 @@ int rewriteSortedSetObject(rio *r, robj *key, robj *o) {
if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
if (rioWriteBulkString(r,"ZADD",4) == 0) return 0;
if (rioWriteBulkObject(r,key) == 0) return 0;
if (rioWriteBulkString(r,key->name,key->len) == 0) return 0;
}
if (rioWriteBulkDouble(r,*score) == 0) return 0;
if (rioWriteBulkString(r,ele,sdslen(ele)) == 0) return 0;
......@@ -1099,7 +1099,7 @@ static int rioWriteHashIteratorCursor(rio *r, hashTypeIterator *hi, int what) {
/* Emit the commands needed to rebuild a hash object.
* The function returns 0 on error, 1 on success. */
int rewriteHashObject(rio *r, robj *key, robj *o) {
int rewriteHashObject(rio *r, rkey *key, robj *o) {
hashTypeIterator *hi;
long long count = 0, items = hashTypeLength(o);
......@@ -1111,7 +1111,7 @@ int rewriteHashObject(rio *r, robj *key, robj *o) {
if (rioWriteBulkCount(r,'*',2+cmd_items*2) == 0) return 0;
if (rioWriteBulkString(r,"HMSET",5) == 0) return 0;
if (rioWriteBulkObject(r,key) == 0) return 0;
if (rioWriteBulkString(r,key->name,key->len) == 0) return 0;
}
if (rioWriteHashIteratorCursor(r, hi, OBJ_HASH_KEY) == 0) return 0;
......@@ -1140,14 +1140,14 @@ int rioWriteBulkStreamID(rio *r,streamID *id) {
* add the message described by 'nack' having the id 'rawid', into the pending
* list of the specified consumer. All this in the context of the specified
* key and group. */
int rioWriteStreamPendingEntry(rio *r, robj *key, const char *groupname, size_t groupname_len, streamConsumer *consumer, unsigned char *rawid, streamNACK *nack) {
int rioWriteStreamPendingEntry(rio *r, rkey *key, const char *groupname, size_t groupname_len, streamConsumer *consumer, unsigned char *rawid, streamNACK *nack) {
/* XCLAIM <key> <group> <consumer> 0 <id> TIME <milliseconds-unix-time>
RETRYCOUNT <count> JUSTID FORCE. */
streamID id;
streamDecodeID(rawid,&id);
if (rioWriteBulkCount(r,'*',12) == 0) return 0;
if (rioWriteBulkString(r,"XCLAIM",6) == 0) return 0;
if (rioWriteBulkObject(r,key) == 0) return 0;
if (rioWriteBulkString(r,key->name,key->len) == 0) return 0;
if (rioWriteBulkString(r,groupname,groupname_len) == 0) return 0;
if (rioWriteBulkString(r,consumer->name,sdslen(consumer->name)) == 0) return 0;
if (rioWriteBulkString(r,"0",1) == 0) return 0;
......@@ -1163,7 +1163,7 @@ int rioWriteStreamPendingEntry(rio *r, robj *key, const char *groupname, size_t
/* Emit the commands needed to rebuild a stream object.
* The function returns 0 on error, 1 on success. */
int rewriteStreamObject(rio *r, robj *key, robj *o) {
int rewriteStreamObject(rio *r, rkey *key, robj *o) {
stream *s = o->ptr;
streamIterator si;
streamIteratorStart(&si,s,NULL,NULL,0);
......@@ -1179,7 +1179,7 @@ int rewriteStreamObject(rio *r, robj *key, robj *o) {
/* Emit the XADD <key> <id> ...fields... command. */
if (rioWriteBulkCount(r,'*',3+numfields*2) == 0) return 0;
if (rioWriteBulkString(r,"XADD",4) == 0) return 0;
if (rioWriteBulkObject(r,key) == 0) return 0;
if (rioWriteBulkString(r,key->name,key->len) == 0) return 0;
if (rioWriteBulkStreamID(r,&id) == 0) return 0;
while(numfields--) {
unsigned char *field, *value;
......@@ -1195,7 +1195,7 @@ int rewriteStreamObject(rio *r, robj *key, robj *o) {
* for the Stream type. */
if (rioWriteBulkCount(r,'*',7) == 0) return 0;
if (rioWriteBulkString(r,"XADD",4) == 0) return 0;
if (rioWriteBulkObject(r,key) == 0) return 0;
if (rioWriteBulkString(r,key->name,key->len) == 0) return 0;
if (rioWriteBulkString(r,"MAXLEN",6) == 0) return 0;
if (rioWriteBulkString(r,"0",1) == 0) return 0;
if (rioWriteBulkStreamID(r,&s->last_id) == 0) return 0;
......@@ -1207,7 +1207,7 @@ int rewriteStreamObject(rio *r, robj *key, robj *o) {
* in case of XDEL lastid. */
if (rioWriteBulkCount(r,'*',3) == 0) return 0;
if (rioWriteBulkString(r,"XSETID",6) == 0) return 0;
if (rioWriteBulkObject(r,key) == 0) return 0;
if (rioWriteBulkString(r,key->name,key->len) == 0) return 0;
if (rioWriteBulkStreamID(r,&s->last_id) == 0) return 0;
......@@ -1222,7 +1222,7 @@ int rewriteStreamObject(rio *r, robj *key, robj *o) {
if (rioWriteBulkCount(r,'*',5) == 0) return 0;
if (rioWriteBulkString(r,"XGROUP",6) == 0) return 0;
if (rioWriteBulkString(r,"CREATE",6) == 0) return 0;
if (rioWriteBulkObject(r,key) == 0) return 0;
if (rioWriteBulkString(r,key->name,key->len) == 0) return 0;
if (rioWriteBulkString(r,(char*)ri.key,ri.key_len) == 0) return 0;
if (rioWriteBulkStreamID(r,&group->last_id) == 0) return 0;
......@@ -1262,12 +1262,14 @@ int rewriteStreamObject(rio *r, robj *key, robj *o) {
/* Call the module type callback in order to rewrite a data type
* that is exported by a module and is not handled by Redis itself.
* The function returns 0 on error, 1 on success. */
int rewriteModuleObject(rio *r, robj *key, robj *o) {
int rewriteModuleObject(rio *r, rkey *key, robj *o) {
RedisModuleIO io;
moduleValue *mv = o->ptr;
moduleType *mt = mv->type;
moduleInitIOContext(io,mt,r,key);
mt->aof_rewrite(&io,key,mv->value);
robj *keyname = createStringObject(key->name,key->len);
moduleInitIOContext(io,mt,r,keyname);
mt->aof_rewrite(&io,keyname,mv->value);
decrRefCount(keyname);
if (io.ctx) {
moduleFreeContext(io.ctx);
zfree(io.ctx);
......@@ -1309,15 +1311,14 @@ int rewriteAppendOnlyFileRio(rio *aof) {
/* Iterate this DB writing every entry */
while((de = dictNext(di)) != NULL) {
sds keystr;
robj key, *o;
rkey *key;
robj *o;
long long expiretime;
keystr = dictGetKey(de);
key = dictGetKey(de);
o = dictGetVal(de);
initStaticStringObject(key,keystr);
expiretime = getExpire(db,&key);
expiretime = getExpire(key);
/* Save the key and associated value */
if (o->type == OBJ_STRING) {
......@@ -1325,20 +1326,21 @@ int rewriteAppendOnlyFileRio(rio *aof) {
char cmd[]="*3\r\n$3\r\nSET\r\n";
if (rioWrite(aof,cmd,sizeof(cmd)-1) == 0) goto werr;
/* Key and value */
if (rioWriteBulkObject(aof,&key) == 0) goto werr;
if (rioWriteBulkString(aof,key->name,key->len) == 0)
goto werr;
if (rioWriteBulkObject(aof,o) == 0) goto werr;
} else if (o->type == OBJ_LIST) {
if (rewriteListObject(aof,&key,o) == 0) goto werr;
if (rewriteListObject(aof,key,o) == 0) goto werr;
} else if (o->type == OBJ_SET) {
if (rewriteSetObject(aof,&key,o) == 0) goto werr;
if (rewriteSetObject(aof,key,o) == 0) goto werr;
} else if (o->type == OBJ_ZSET) {
if (rewriteSortedSetObject(aof,&key,o) == 0) goto werr;
if (rewriteSortedSetObject(aof,key,o) == 0) goto werr;
} else if (o->type == OBJ_HASH) {
if (rewriteHashObject(aof,&key,o) == 0) goto werr;
if (rewriteHashObject(aof,key,o) == 0) goto werr;
} else if (o->type == OBJ_STREAM) {
if (rewriteStreamObject(aof,&key,o) == 0) goto werr;
if (rewriteStreamObject(aof,key,o) == 0) goto werr;
} else if (o->type == OBJ_MODULE) {
if (rewriteModuleObject(aof,&key,o) == 0) goto werr;
if (rewriteModuleObject(aof,key,o) == 0) goto werr;
} else {
serverPanic("Unknown object type");
}
......@@ -1346,7 +1348,8 @@ int rewriteAppendOnlyFileRio(rio *aof) {
if (expiretime != -1) {
char cmd[]="*3\r\n$9\r\nPEXPIREAT\r\n";
if (rioWrite(aof,cmd,sizeof(cmd)-1) == 0) goto werr;
if (rioWriteBulkObject(aof,&key) == 0) goto werr;
if (rioWriteBulkString(aof,key->name,key->len) == 0)
goto werr;
if (rioWriteBulkLongLong(aof,expiretime) == 0) goto werr;
}
/* Read some diff from the parent process from time to time. */
......
......@@ -85,7 +85,7 @@ struct bio_job {
void *bioProcessBackgroundJobs(void *arg);
void lazyfreeFreeObjectFromBioThread(robj *o);
void lazyfreeFreeDatabaseFromBioThread(dict *ht1, dict *ht2);
void lazyfreeFreeDatabaseFromBioThread(dict *ht, rax *tree);
void lazyfreeFreeSlotsMapFromBioThread(zskiplist *sl);
/* Make sure we have enough stack to perform all the things we do in the
......
......@@ -477,7 +477,7 @@ int getBitfieldTypeFromArgument(client *c, robj *o, int *sign, int *bits) {
* an error is sent to the client. */
robj *lookupStringForBitCommand(client *c, size_t maxbit) {
size_t byte = maxbit >> 3;
robj *o = lookupKeyWrite(c->db,c->argv[1]);
robj *o = lookupKeyWrite(c->db,c->argv[1],NULL);
if (o == NULL) {
o = createObject(OBJ_STRING,sdsnewlen(NULL, byte+1));
......@@ -571,7 +571,7 @@ void getbitCommand(client *c) {
if (getBitOffsetFromArgument(c,c->argv[2],&bitoffset,0,0) != C_OK)
return;
if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
if ((o = lookupKeyReadOrReply(c,c->argv[1],NULL,shared.czero)) == NULL ||
checkType(c,o,OBJ_STRING)) return;
byte = bitoffset >> 3;
......@@ -625,7 +625,7 @@ void bitopCommand(client *c) {
len = zmalloc(sizeof(long) * numkeys);
objects = zmalloc(sizeof(robj*) * numkeys);
for (j = 0; j < numkeys; j++) {
o = lookupKeyRead(c->db,c->argv[j+3]);
o = lookupKeyRead(c->db,c->argv[j+3],NULL);
/* Handle non-existing keys as empty strings. */
if (o == NULL) {
objects[j] = NULL;
......@@ -773,7 +773,7 @@ void bitcountCommand(client *c) {
char llbuf[LONG_STR_SIZE];
/* Lookup, check for type, and return 0 for non existing keys. */
if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
if ((o = lookupKeyReadOrReply(c,c->argv[1],NULL,shared.czero)) == NULL ||
checkType(c,o,OBJ_STRING)) return;
p = getObjectReadOnlyString(o,&strlen,llbuf);
......@@ -834,7 +834,7 @@ void bitposCommand(client *c) {
/* If the key does not exist, from our point of view it is an infinite
* array of 0 bits. If the user is looking for the fist clear bit return 0,
* If the user is looking for the first set bit, return -1. */
if ((o = lookupKeyRead(c->db,c->argv[1])) == NULL) {
if ((o = lookupKeyRead(c->db,c->argv[1],NULL)) == NULL) {
addReplyLongLong(c, bit ? -1 : 0);
return;
}
......@@ -993,7 +993,7 @@ void bitfieldCommand(client *c) {
if (readonly) {
/* Lookup for read is ok if key doesn't exit, but errors
* if it's not a string. */
o = lookupKeyRead(c->db,c->argv[1]);
o = lookupKeyRead(c->db,c->argv[1],NULL);
if (o != NULL && checkType(c,o,OBJ_STRING)) {
zfree(ops);
return;
......
......@@ -270,7 +270,7 @@ void handleClientsBlockedOnKeys(void) {
dictDelete(rl->db->ready_keys,rl->key);
/* Serve clients blocked on list key. */
robj *o = lookupKeyWrite(rl->db,rl->key);
robj *o = lookupKeyWrite(rl->db,rl->key,NULL);
if (o != NULL && o->type == OBJ_LIST) {
dictEntry *de;
......
......@@ -4776,7 +4776,7 @@ NULL
/* Generates a DUMP-format representation of the object 'o', adding it to the
* io stream pointed by 'rio'. This function can't fail. */
void createDumpPayload(rio *payload, robj *o, robj *key) {
void createDumpPayload(rio *payload, robj *o, rkey *key) {
unsigned char buf[2];
uint64_t crc;
......@@ -4833,16 +4833,17 @@ int verifyDumpPayload(unsigned char *p, size_t len) {
* complement of RESTORE and can be useful for different applications. */
void dumpCommand(client *c) {
robj *o, *dumpobj;
rkey *key;
rio payload;
/* Check if the key is here. */
if ((o = lookupKeyRead(c->db,c->argv[1])) == NULL) {
if ((o = lookupKeyRead(c->db,c->argv[1],&key)) == NULL) {
addReplyNull(c);
return;
}
/* Create the DUMP encoded representation. */
createDumpPayload(&payload,o,c->argv[1]);
createDumpPayload(&payload,o,key);
/* Transfer to the client */
dumpobj = createObject(OBJ_STRING,payload.io.buffer.ptr);
......@@ -4893,7 +4894,7 @@ void restoreCommand(client *c) {
}
/* Make sure this key does not already exist here... */
if (!replace && lookupKeyWrite(c->db,c->argv[1]) != NULL) {
if (!replace && lookupKeyWrite(c->db,c->argv[1],NULL) != NULL) {
addReply(c,shared.busykeyerr);
return;
}
......@@ -4925,12 +4926,12 @@ void restoreCommand(client *c) {
if (replace) dbDelete(c->db,c->argv[1]);
/* Create the key and set the TTL if any */
dbAdd(c->db,c->argv[1],obj);
rkey *key = dbAdd(c->db,c->argv[1],obj);
if (ttl) {
if (!absttl) ttl+=mstime();
setExpire(c,c->db,c->argv[1],ttl);
setExpire(c,c->db,key,ttl);
}
objectSetLRUOrLFU(obj,lfu_freq,lru_idle,lru_clock);
objectSetLRUOrLFU(key,lfu_freq,lru_idle,lru_clock);
signalModifiedKey(c->db,c->argv[1]);
addReply(c,shared.ok);
server.dirty++;
......@@ -5066,7 +5067,8 @@ void migrateCommand(client *c) {
long timeout;
long dbid;
robj **ov = NULL; /* Objects to migrate. */
robj **kv = NULL; /* Key names. */
robj **knv = NULL; /* Key names. */
rkey **kov = NULL; /* Key objects. */
robj **newargv = NULL; /* Used to rewrite the command as DEL ... keys ... */
rio cmd, payload;
int may_retry = 1;
......@@ -5121,18 +5123,21 @@ void migrateCommand(client *c) {
* this case, since often this is due to a normal condition like the key
* expiring in the meantime. */
ov = zrealloc(ov,sizeof(robj*)*num_keys);
kv = zrealloc(kv,sizeof(robj*)*num_keys);
knv = zrealloc(knv,sizeof(robj*)*num_keys);
kov = zrealloc(kov,sizeof(rkey*)*num_keys);
int oi = 0;
for (j = 0; j < num_keys; j++) {
if ((ov[oi] = lookupKeyRead(c->db,c->argv[first_key+j])) != NULL) {
kv[oi] = c->argv[first_key+j];
rkey *ko;
if ((ov[oi] = lookupKeyRead(c->db,c->argv[first_key+j],&ko)) != NULL) {
knv[oi] = c->argv[first_key+j];
kov[oi] = ko;
oi++;
}
}
num_keys = oi;
if (num_keys == 0) {
zfree(ov); zfree(kv);
zfree(ov); zfree(knv); zfree(kov);
addReplySds(c,sdsnew("+NOKEY\r\n"));
return;
}
......@@ -5143,7 +5148,7 @@ try_again:
/* Connect */
cs = migrateGetSocket(c,c->argv[1],c->argv[2],timeout);
if (cs == NULL) {
zfree(ov); zfree(kv);
zfree(ov); zfree(knv); zfree(kov);
return; /* error sent to the client by migrateGetSocket() */
}
......@@ -5173,7 +5178,7 @@ try_again:
/* Create RESTORE payload and generate the protocol to call the command. */
for (j = 0; j < num_keys; j++) {
long long ttl = 0;
long long expireat = getExpire(c->db,kv[j]);
long long expireat = getExpire(kov[j]);
if (expireat != -1) {
ttl = expireat-mstime();
......@@ -5186,7 +5191,9 @@ try_again:
/* Relocate valid (non expired) keys into the array in successive
* positions to remove holes created by the keys that were present
* in the first lookup but are now expired after the second lookup. */
kv[non_expired++] = kv[j];
knv[non_expired] = knv[j];
kov[non_expired] = kov[j];
non_expired++;
serverAssertWithInfo(c,NULL,
rioWriteBulkCount(&cmd,'*',replace ? 5 : 4));
......@@ -5196,14 +5203,14 @@ try_again:
rioWriteBulkString(&cmd,"RESTORE-ASKING",14));
else
serverAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,"RESTORE",7));
serverAssertWithInfo(c,NULL,sdsEncodedObject(kv[j]));
serverAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,kv[j]->ptr,
sdslen(kv[j]->ptr)));
serverAssertWithInfo(c,NULL,sdsEncodedObject(knv[j]));
serverAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,knv[j]->ptr,
sdslen(knv[j]->ptr)));
serverAssertWithInfo(c,NULL,rioWriteBulkLongLong(&cmd,ttl));
/* Emit the payload argument, that is the serialized object using
* the DUMP format. */
createDumpPayload(&payload,ov[j],kv[j]);
createDumpPayload(&payload,ov[j],kov[j]);
serverAssertWithInfo(c,NULL,
rioWriteBulkString(&cmd,payload.io.buffer.ptr,
sdslen(payload.io.buffer.ptr)));
......@@ -5283,13 +5290,13 @@ try_again:
} else {
if (!copy) {
/* No COPY option: remove the local key, signal the change. */
dbDelete(c->db,kv[j]);
signalModifiedKey(c->db,kv[j]);
dbDelete(c->db,knv[j]);
signalModifiedKey(c->db,knv[j]);
server.dirty++;
/* Populate the argument vector to replace the old one. */
newargv[del_idx++] = kv[j];
incrRefCount(kv[j]);
newargv[del_idx++] = knv[j];
incrRefCount(knv[j]);
}
}
}
......@@ -5347,7 +5354,7 @@ try_again:
}
sdsfree(cmd.io.buffer.ptr);
zfree(ov); zfree(kv); zfree(newargv);
zfree(ov); zfree(knv); zfree(kov); zfree(newargv);
return;
/* On socket errors we try to close the cached socket and try again.
......@@ -5374,7 +5381,7 @@ socket_err:
}
/* Cleanup we want to do if no retry is attempted. */
zfree(ov); zfree(kv);
zfree(ov); zfree(knv); zfree(kov);
addReplySds(c,
sdscatprintf(sdsempty(),
"-IOERR error or timeout %s to target instance\r\n",
......@@ -5554,7 +5561,7 @@ clusterNode *getNodeByQuery(client *c, struct redisCommand *cmd, robj **argv, in
/* Migarting / Improrting slot? Count keys we don't have. */
if ((migrating_slot || importing_slot) &&
lookupKeyRead(&server.db[0],thiskey) == NULL)
lookupKeyRead(&server.db[0],thiskey,NULL) == NULL)
{
missing_keys++;
}
......
......@@ -1650,19 +1650,23 @@ void dictListDestructor(void *privdata, void *val);
void rewriteConfigSentinelOption(struct rewriteConfigState *state);
dictType optionToLineDictType = {
dictSdsCaseHash, /* hash function */
dictSdsCaseHash, /* lookup hash function */
dictSdsCaseHash, /* store hash function */
NULL, /* key dup */
NULL, /* val dup */
dictSdsKeyCaseCompare, /* key compare */
dictSdsKeyCaseCompare, /* lookup key compare */
dictSdsKeyCaseCompare, /* stored key compare */
dictSdsDestructor, /* key destructor */
dictListDestructor /* val destructor */
};
dictType optionSetDictType = {
dictSdsCaseHash, /* hash function */
dictSdsCaseHash, /* lookup hash function */
dictSdsCaseHash, /* store hash function */
NULL, /* key dup */
NULL, /* val dup */
dictSdsKeyCaseCompare, /* key compare */
dictSdsKeyCaseCompare, /* lookup key compare */
dictSdsKeyCaseCompare, /* stored key compare */
dictSdsDestructor, /* key destructor */
NULL /* val destructor */
};
......
This diff is collapsed.
......@@ -118,10 +118,10 @@ void mixStringObjectDigest(unsigned char *digest, robj *o) {
* Note that this function does not reset the initial 'digest' passed, it
* will continue mixing this object digest to anything that was already
* present. */
void xorObjectDigest(redisDb *db, robj *keyobj, unsigned char *digest, robj *o) {
void xorObjectDigest(rkey *key, unsigned char *digest, robj *o) {
uint32_t aux = htonl(o->type);
mixDigest(digest,&aux,sizeof(aux));
long long expiretime = getExpire(db,keyobj);
long long expiretime = getExpire(key);
char buf[128];
/* Save the key and associated value */
......@@ -277,21 +277,19 @@ void computeDatasetDigest(unsigned char *final) {
/* Iterate this DB writing every entry */
while((de = dictNext(di)) != NULL) {
sds key;
robj *keyobj, *o;
rkey *key;
robj *o;
memset(digest,0,20); /* This key-val digest */
key = dictGetKey(de);
keyobj = createStringObject(key,sdslen(key));
mixDigest(digest,key,sdslen(key));
mixDigest(digest,key->name,key->len);
o = dictGetVal(de);
xorObjectDigest(db,keyobj,digest,o);
xorObjectDigest(key,digest,o);
/* We can finally xor the key-val digest to the final digest */
xorDigest(final,digest,20);
decrRefCount(keyobj);
}
dictReleaseIterator(di);
}
......@@ -385,6 +383,7 @@ NULL
addReply(c,shared.ok);
} else if (!strcasecmp(c->argv[1]->ptr,"object") && c->argc == 3) {
dictEntry *de;
rkey *key;
robj *val;
char *strenc;
......@@ -392,6 +391,7 @@ NULL
addReply(c,shared.nokeyerr);
return;
}
key = dictGetKey(de);
val = dictGetVal(de);
strenc = strEncoding(val->encoding);
......@@ -434,7 +434,7 @@ NULL
"lru:%d lru_seconds_idle:%llu%s",
(void*)val, val->refcount,
strenc, rdbSavedObjectLen(val),
val->lru, estimateObjectIdleTime(val)/1000, extra);
key->lru, estimateObjectIdleTime(key)/1000, extra);
} else if (!strcasecmp(c->argv[1]->ptr,"sdslen") && c->argc == 3) {
dictEntry *de;
robj *val;
......@@ -463,7 +463,7 @@ NULL
} else if (!strcasecmp(c->argv[1]->ptr,"ziplist") && c->argc == 3) {
robj *o;
if ((o = objectCommandLookupOrReply(c,c->argv[2],shared.nokeyerr))
if ((o = objectCommandLookupOrReply(c,c->argv[2],NULL,shared.nokeyerr))
== NULL) return;
if (o->encoding != OBJ_ENCODING_ZIPLIST) {
......@@ -489,7 +489,7 @@ NULL
if (c->argc == 5)
if (getLongFromObjectOrReply(c, c->argv[4], &valsize, NULL) != C_OK)
return;
if (lookupKeyWrite(c->db,key) != NULL) {
if (lookupKeyWrite(c->db,key,NULL) != NULL) {
decrRefCount(key);
continue;
}
......@@ -521,8 +521,10 @@ NULL
for (int j = 2; j < c->argc; j++) {
unsigned char digest[20];
memset(digest,0,20); /* Start with a clean result */
robj *o = lookupKeyReadWithFlags(c->db,c->argv[j],LOOKUP_NOTOUCH);
if (o) xorObjectDigest(c->db,c->argv[j],digest,o);
rkey *key;
robj *o = lookupKeyReadWithFlags(c->db,c->argv[j],&key,
LOOKUP_NOTOUCH);
if (o) xorObjectDigest(key,digest,o);
sds d = sdsempty();
for (int i = 0; i < 20; i++) d = sdscatprintf(d, "%02x",digest[i]);
......@@ -634,16 +636,12 @@ NULL
dictGetStats(buf,sizeof(buf),server.db[dbid].dict);
stats = sdscat(stats,buf);
stats = sdscatprintf(stats,"[Expires HT]\n");
dictGetStats(buf,sizeof(buf),server.db[dbid].expires);
stats = sdscat(stats,buf);
addReplyBulkSds(c,stats);
} else if (!strcasecmp(c->argv[1]->ptr,"htstats-key") && c->argc == 3) {
robj *o;
dict *ht = NULL;
if ((o = objectCommandLookupOrReply(c,c->argv[2],shared.nokeyerr))
if ((o = objectCommandLookupOrReply(c,c->argv[2],NULL,shared.nokeyerr))
== NULL) return;
/* Get the hash table reference from the object, if possible. */
......
......@@ -775,7 +775,7 @@ long defragKey(redisDb *db, dictEntry *de) {
/* Dirty code:
* I can't search in db->expires for that key after i already released
* the pointer it holds it won't be able to do the string compare */
uint64_t hash = dictGetHash(db->dict, de->key);
uint64_t hash = dictGetEntryHash(db->dict, de);
replaceSateliteDictKeyPtrAndOrDefragDictEntry(db->expires, keysds, newsds, hash, &defragged);
}
......
......@@ -206,7 +206,7 @@ int dictRehash(dict *d, int n) {
nextde = de->next;
/* Get the index in the new hash table */
h = dictHashKey(d, de->key) & d->ht[1].sizemask;
h = dictHashStoredKey(d, de->key) & d->ht[1].sizemask;
de->next = d->ht[1].table[h];
d->ht[1].table[h] = de;
d->ht[0].used--;
......@@ -299,7 +299,7 @@ dictEntry *dictAddRaw(dict *d, void *key, dictEntry **existing)
/* Get the index of the new element, or -1 if
* the element already exists. */
if ((index = _dictKeyIndex(d, key, dictHashKey(d,key), existing)) == -1)
if ((index = _dictKeyIndex(d,key,dictHashStoredKey(d,key),existing)) == -1)
return NULL;
/* Allocate the memory and store the new entry.
......@@ -369,14 +369,14 @@ static dictEntry *dictGenericDelete(dict *d, const void *key, int nofree) {
if (d->ht[0].used == 0 && d->ht[1].used == 0) return NULL;
if (dictIsRehashing(d)) _dictRehashStep(d);
h = dictHashKey(d, key);
h = dictHashLookupKey(d, key);
for (table = 0; table <= 1; table++) {
idx = h & d->ht[table].sizemask;
he = d->ht[table].table[idx];
prevHe = NULL;
while(he) {
if (key==he->key || dictCompareKeys(d, key, he->key)) {
if (key==he->key || dictCompareLookupKeys(d, key, he->key)) {
/* Unlink the element from the list */
if (prevHe)
prevHe->next = he->next;
......@@ -480,12 +480,12 @@ dictEntry *dictFind(dict *d, const void *key)
if (d->ht[0].used + d->ht[1].used == 0) return NULL; /* dict is empty */
if (dictIsRehashing(d)) _dictRehashStep(d);
h = dictHashKey(d, key);
h = dictHashLookupKey(d, key);
for (table = 0; table <= 1; table++) {
idx = h & d->ht[table].sizemask;
he = d->ht[table].table[idx];
while(he) {
if (key==he->key || dictCompareKeys(d, key, he->key))
if (key==he->key || dictCompareLookupKeys(d, key, he->key))
return he;
he = he->next;
}
......@@ -998,7 +998,7 @@ static long _dictKeyIndex(dict *d, const void *key, uint64_t hash, dictEntry **e
/* Search if this slot does not already contain the given key */
he = d->ht[table].table[idx];
while(he) {
if (key==he->key || dictCompareKeys(d, key, he->key)) {
if (key==he->key || dictCompareStoredKeys(d, key, he->key)) {
if (existing) *existing = he;
return -1;
}
......@@ -1024,15 +1024,28 @@ void dictDisableResize(void) {
dict_can_resize = 0;
}
/* Compute the hash of the specified key (using the lookup hash function)
* and returns it to the caller. This is useful in order to later call
* dictFindEntryRefByPtrAndHash(). */
uint64_t dictGetHash(dict *d, const void *key) {
return dictHashKey(d, key);
return dictHashLookupKey(d, key);
}
/* Compute the hash of the specified dict entry (using the stored keys hash
* function) and returns it to the caller. This is useful in order to later
* call dictFindEntryRefByPtrAndHash(). */
uint64_t dictGetEntryHash(dict *d, const dictEntry *de) {
return dictHashStoredKey(d, de->key);
}
/* Finds the dictEntry reference by using pointer and pre-calculated hash.
* oldkey is a dead pointer and should not be accessed.
* the hash value should be provided using dictGetHash.
* no string / key comparison is performed.
* return value is the reference to the dictEntry if found, or NULL if not found. */
* the hash value should be provided using dictGetHash() or dictGetEntryHash()
* depending on the object type (if the one we lookup the hash table with, or
* the one stored in the dict entry).
* No string / key comparison is performed.
* Return value is the reference to the dictEntry if found, or NULL if not
* found. */
dictEntry **dictFindEntryRefByPtrAndHash(dict *d, const void *oldptr, uint64_t hash) {
dictEntry *he, **heref;
unsigned long idx, table;
......@@ -1159,10 +1172,12 @@ void freeCallback(void *privdata, void *val) {
}
dictType BenchmarkDictType = {
hashCallback,
hashCallback,
NULL,
NULL,
compareCallback,
compareCallback,
freeCallback,
NULL
};
......
......@@ -44,6 +44,8 @@
/* Unused arguments generate annoying warnings... */
#define DICT_NOTUSED(V) ((void) V)
/* An entry (a key basically) as stored inside the hash table. Note that
* there is a 'next' pointer, since we use chaining to resolve conflicts. */
typedef struct dictEntry {
void *key;
union {
......@@ -55,11 +57,33 @@ typedef struct dictEntry {
struct dictEntry *next;
} dictEntry;
/* The hash table type.
*
* There are two hash functions both for key hashing and comparison, one set is
* used for looking up the key and the other set to store it.
*
* Most of the times each set will be the same function pointer, but sometimes
* we want the ability to store a key in a given way inside the hash function,
* and lookup it in some other way without resorting to any kind of conversion.
* For instance the key may be stored as a structure also representing other
* things, but the lookup happens via just a pointer to a null terminated
* string. The dual hash design allows for such usage. In that case we'll have
* a lookupHashFunction that will expect a null terminated C string, and a
* storeHashFunction that will instead expect the structure.
* Similarly the two comparison functions will work differently. The
* lookupKeyCompare will treat the first argument as a pointer to a C string
* and the other as a structure (this way we can directly lookup the structure
* key using the C string). While the storedKeyCompare() will check if two
* pointers to the key in structure form are the same.
*
* Every actual hash table have a pointer to its type. */
typedef struct dictType {
uint64_t (*hashFunction)(const void *key);
uint64_t (*lookupHashFunction)(const void *key);
uint64_t (*storedHashFunction)(const void *key);
void *(*keyDup)(void *privdata, const void *key);
void *(*valDup)(void *privdata, const void *obj);
int (*keyCompare)(void *privdata, const void *key1, const void *key2);
int (*lookupKeyCompare)(void *privdata, const void *key1, const void *key2);
int (*storedKeyCompare)(void *privdata, const void *key1, const void *key2);
void (*keyDestructor)(void *privdata, void *key);
void (*valDestructor)(void *privdata, void *obj);
} dictType;
......@@ -132,12 +156,18 @@ typedef void (dictScanBucketFunction)(void *privdata, dictEntry **bucketref);
(entry)->key = (_key_); \
} while(0)
#define dictCompareKeys(d, key1, key2) \
(((d)->type->keyCompare) ? \
(d)->type->keyCompare((d)->privdata, key1, key2) : \
#define dictCompareLookupKeys(d, key1, key2) \
(((d)->type->lookupKeyCompare) ? \
(d)->type->lookupKeyCompare((d)->privdata, key1, key2) : \
(key1) == (key2))
#define dictCompareStoredKeys(d, key1, key2) \
(((d)->type->storedKeyCompare) ? \
(d)->type->storedKeyCompare((d)->privdata, key1, key2) : \
(key1) == (key2))
#define dictHashKey(d, key) (d)->type->hashFunction(key)
#define dictHashLookupKey(d, key) (d)->type->lookupHashFunction(key)
#define dictHashStoredKey(d, key) (d)->type->storedHashFunction(key)
#define dictGetKey(he) ((he)->key)
#define dictGetVal(he) ((he)->v.val)
#define dictGetSignedIntegerVal(he) ((he)->v.s64)
......@@ -180,6 +210,7 @@ void dictSetHashFunctionSeed(uint8_t *seed);
uint8_t *dictGetHashFunctionSeed(void);
unsigned long dictScan(dict *d, unsigned long v, dictScanFunction *fn, dictScanBucketFunction *bucketfn, void *privdata);
uint64_t dictGetHash(dict *d, const void *key);
uint64_t dictGetEntryHash(dict *d, const dictEntry *de);
dictEntry **dictFindEntryRefByPtrAndHash(dict *d, const void *oldptr, uint64_t hash);
/* Hash table types */
......
......@@ -87,12 +87,12 @@ unsigned int LRU_CLOCK(void) {
/* Given an object returns the min number of milliseconds the object was never
* requested, using an approximated LRU algorithm. */
unsigned long long estimateObjectIdleTime(robj *o) {
unsigned long long estimateObjectIdleTime(rkey *key) {
unsigned long long lruclock = LRU_CLOCK();
if (lruclock >= o->lru) {
return (lruclock - o->lru) * LRU_CLOCK_RESOLUTION;
if (lruclock >= key->lru) {
return (lruclock - key->lru) * LRU_CLOCK_RESOLUTION;
} else {
return (lruclock + (LRU_CLOCK_MAX - o->lru)) *
return (lruclock + (LRU_CLOCK_MAX - key->lru)) *
LRU_CLOCK_RESOLUTION;
}
}
......@@ -166,7 +166,7 @@ void evictionPoolPopulate(int dbid, dict *sampledict, dict *keydict, struct evic
count = dictGetSomeKeys(sampledict,samples,server.maxmemory_samples);
for (j = 0; j < count; j++) {
unsigned long long idle;
sds key;
rkey *key;
robj *o;
dictEntry *de;
......@@ -185,7 +185,7 @@ void evictionPoolPopulate(int dbid, dict *sampledict, dict *keydict, struct evic
* idle just because the code initially handled LRU, but is in fact
* just a score where an higher score means better candidate. */
if (server.maxmemory_policy & MAXMEMORY_FLAG_LRU) {
idle = estimateObjectIdleTime(o);
idle = estimateObjectIdleTime(key);
} else if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) {
/* When we use an LRU policy, we sort the keys by idle time
* so that we expire keys starting from greater idle time.
......@@ -194,10 +194,10 @@ void evictionPoolPopulate(int dbid, dict *sampledict, dict *keydict, struct evic
* first. So inside the pool we put objects using the inverted
* frequency subtracting the actual frequency to the maximum
* frequency of 255. */
idle = 255-LFUDecrAndReturn(o);
idle = 255-LFUDecrAndReturn(key);
} else if (server.maxmemory_policy == MAXMEMORY_VOLATILE_TTL) {
/* In this case the sooner the expire the better. */
idle = ULLONG_MAX - (long)dictGetVal(de);
idle = key->expire;
} else {
serverPanic("Unknown eviction policy in evictionPoolPopulate()");
}
......@@ -243,9 +243,9 @@ void evictionPoolPopulate(int dbid, dict *sampledict, dict *keydict, struct evic
* because allocating and deallocating this object is costly
* (according to the profiler, not my fantasy. Remember:
* premature optimizbla bla bla bla. */
int klen = sdslen(key);
int klen = key->len;
if (klen > EVPOOL_CACHED_SDS_SIZE) {
pool[k].key = sdsdup(key);
pool[k].key = sdsnewlen(key->name,key->len);
} else {
memcpy(pool[k].cached,key,klen+1);
sdssetlen(pool[k].cached,klen);
......@@ -332,9 +332,9 @@ uint8_t LFULogIncr(uint8_t counter) {
* This function is used in order to scan the dataset for the best object
* to fit: as we check for the candidate, we incrementally decrement the
* counter of the scanned objects if needed. */
unsigned long LFUDecrAndReturn(robj *o) {
unsigned long ldt = o->lru >> 8;
unsigned long counter = o->lru & 255;
unsigned long LFUDecrAndReturn(rkey *k) {
unsigned long ldt = k->lru >> 8;
unsigned long counter = k->lru & 255;
unsigned long num_periods = server.lfu_decay_time ? LFUTimeElapsed(ldt) / server.lfu_decay_time : 0;
if (num_periods)
counter = (num_periods > counter) ? 0 : counter - num_periods;
......@@ -488,8 +488,13 @@ int freeMemoryIfNeeded(void) {
* every DB. */
for (i = 0; i < server.dbnum; i++) {
db = server.db+i;
#if 0
dict = (server.maxmemory_policy & MAXMEMORY_FLAG_ALLKEYS) ?
db->dict : db->expires;
#else
dict = db->dict;
#warning "Implement the volatile policy correctly"
#endif
if ((keys = dictSize(dict)) != 0) {
evictionPoolPopulate(i, dict, db->dict, pool);
total_keys += keys;
......@@ -506,8 +511,11 @@ int freeMemoryIfNeeded(void) {
de = dictFind(server.db[pool[k].dbid].dict,
pool[k].key);
} else {
#warning "Implement the volatile policy correctly"
#if 0
de = dictFind(server.db[pool[k].dbid].expires,
pool[k].key);
#endif
}
/* Remove the entry from the pool. */
......@@ -538,8 +546,13 @@ int freeMemoryIfNeeded(void) {
for (i = 0; i < server.dbnum; i++) {
j = (++next_db) % server.dbnum;
db = server.db+j;
#if 0
dict = (server.maxmemory_policy == MAXMEMORY_ALLKEYS_RANDOM) ?
db->dict : db->expires;
#else
#warning "Implement the volatile policy correctly"
dict = db->dict;
#endif
if (dictSize(dict) != 0) {
de = dictGetRandomKey(dict);
bestkey = dictGetKey(de);
......
This diff is collapsed.
......@@ -466,8 +466,8 @@ void georadiusGeneric(client *c, int flags) {
/* Look up the requested zset */
robj *zobj = NULL;
if ((zobj = lookupKeyReadOrReply(c, key, shared.null[c->resp])) == NULL ||
checkType(c, zobj, OBJ_ZSET)) {
if ((zobj = lookupKeyReadOrReply(c, key, NULL, shared.null[c->resp]))
== NULL || checkType(c, zobj, OBJ_ZSET)) {
return;
}
......@@ -701,7 +701,7 @@ void geohashCommand(client *c) {
int j;
/* Look up the requested zset */
robj *zobj = lookupKeyRead(c->db, c->argv[1]);
robj *zobj = lookupKeyRead(c->db, c->argv[1], NULL);
if (zobj && checkType(c, zobj, OBJ_ZSET)) return;
/* Geohash elements one after the other, using a null bulk reply for
......@@ -754,7 +754,7 @@ void geoposCommand(client *c) {
int j;
/* Look up the requested zset */
robj *zobj = lookupKeyRead(c->db, c->argv[1]);
robj *zobj = lookupKeyRead(c->db, c->argv[1], NULL);
if (zobj && checkType(c, zobj, OBJ_ZSET)) return;
/* Report elements one after the other, using a null bulk reply for
......@@ -797,7 +797,7 @@ void geodistCommand(client *c) {
/* Look up the requested zset */
robj *zobj = NULL;
if ((zobj = lookupKeyReadOrReply(c, c->argv[1], shared.null[c->resp]))
if ((zobj = lookupKeyReadOrReply(c, c->argv[1], NULL, shared.null[c->resp]))
== NULL || checkType(c, zobj, OBJ_ZSET)) return;
/* Get the scores. We need both otherwise NULL is returned. */
......
......@@ -50,7 +50,7 @@ void addReplyGopherItem(client *c, const char *type, const char *descr,
* protocol. */
void processGopherRequest(client *c) {
robj *keyname = c->argc == 0 ? createStringObject("/",1) : c->argv[0];
robj *o = lookupKeyRead(c->db,keyname);
robj *o = lookupKeyRead(c->db,keyname,NULL);
/* If there is no such key, return with a Gopher error. */
if (o == NULL || o->type != OBJ_STRING) {
......
......@@ -1179,7 +1179,7 @@ invalid:
/* PFADD var ele ele ele ... ele => :0 or :1 */
void pfaddCommand(client *c) {
robj *o = lookupKeyWrite(c->db,c->argv[1]);
robj *o = lookupKeyWrite(c->db,c->argv[1],NULL);
struct hllhdr *hdr;
int updated = 0, j;
......@@ -1238,7 +1238,7 @@ void pfcountCommand(client *c) {
registers = max + HLL_HDR_SIZE;
for (j = 1; j < c->argc; j++) {
/* Check type and size. */
robj *o = lookupKeyRead(c->db,c->argv[j]);
robj *o = lookupKeyRead(c->db,c->argv[j],NULL);
if (o == NULL) continue; /* Assume empty HLL for non existing var.*/
if (isHLLObjectOrReply(c,o) != C_OK) return;
......@@ -1259,7 +1259,7 @@ void pfcountCommand(client *c) {
*
* The user specified a single key. Either return the cached value
* or compute one and update the cache. */
o = lookupKeyWrite(c->db,c->argv[1]);
o = lookupKeyWrite(c->db,c->argv[1],NULL);
if (o == NULL) {
/* No key? Cardinality is zero since no element was added, otherwise
* we would have a key as HLLADD creates it as a side effect. */
......@@ -1320,7 +1320,7 @@ void pfmergeCommand(client *c) {
memset(max,0,sizeof(max));
for (j = 1; j < c->argc; j++) {
/* Check type and size. */
robj *o = lookupKeyRead(c->db,c->argv[j]);
robj *o = lookupKeyRead(c->db,c->argv[j],NULL);
if (o == NULL) continue; /* Assume empty HLL for non existing var. */
if (isHLLObjectOrReply(c,o) != C_OK) return;
......@@ -1338,7 +1338,7 @@ void pfmergeCommand(client *c) {
}
/* Create / unshare the destination key's value if needed. */
robj *o = lookupKeyWrite(c->db,c->argv[1]);
robj *o = lookupKeyWrite(c->db,c->argv[1],NULL);
if (o == NULL) {
/* Create the key with a string value of the exact length to
* hold our HLL data structure. sdsnewlen() when NULL is passed
......@@ -1497,7 +1497,7 @@ void pfdebugCommand(client *c) {
robj *o;
int j;
o = lookupKeyWrite(c->db,c->argv[2]);
o = lookupKeyWrite(c->db,c->argv[2],NULL);
if (o == NULL) {
addReplyError(c,"The specified key does not exist");
return;
......
......@@ -48,10 +48,12 @@ uint64_t dictStringHash(const void *key) {
void dictVanillaFree(void *privdata, void *val);
dictType latencyTimeSeriesDictType = {
dictStringHash, /* hash function */
dictStringHash, /* lookup hash function */
dictStringHash, /* stored hash function */
NULL, /* key dup */
NULL, /* val dup */
dictStringKeyCompare, /* key compare */
dictStringKeyCompare, /* lookup key compare */
dictStringKeyCompare, /* stored key compare */
dictVanillaFree, /* key destructor */
dictVanillaFree /* val destructor */
};
......
......@@ -51,19 +51,19 @@ size_t lazyfreeGetFreeEffort(robj *obj) {
* a lazy free list instead of being freed synchronously. The lazy free list
* will be reclaimed in a different bio.c thread. */
#define LAZYFREE_THRESHOLD 64
int dbAsyncDelete(redisDb *db, robj *key) {
/* Deleting an entry from the expires dict will not free the sds of
* the key, because it is shared with the main dictionary. */
if (dictSize(db->expires) > 0) dictDelete(db->expires,key->ptr);
int dbAsyncDelete(redisDb *db, robj *keyname) {
/* If the value is composed of a few allocations, to free in a lazy way
* is actually just slower... So under a certain limit we just free
* the object synchronously. */
dictEntry *de = dictUnlink(db->dict,key->ptr);
dictEntry *de = dictUnlink(db->dict,keyname->ptr);
if (de) {
rkey *key = dictGetKey(de);
robj *val = dictGetVal(de);
size_t free_effort = lazyfreeGetFreeEffort(val);
/* Remove the entry from the expire tree since this is fast anyway. */
if (key->flags & KEY_FLAG_EXPIRE) removeExpireFromTree(db,key);
/* If releasing the object is too much work, do it in the background
* by adding the object to the lazy free list.
* Note that if the object is shared, to reclaim it now it is not
......@@ -83,7 +83,7 @@ int dbAsyncDelete(redisDb *db, robj *key) {
* field to NULL in order to lazy free it later. */
if (de) {
dictFreeUnlinkedEntry(db->dict,de);
if (server.cluster_enabled) slotToKeyDel(key);
if (server.cluster_enabled) slotToKeyDel(keyname);
return 1;
} else {
return 0;
......@@ -105,11 +105,11 @@ void freeObjAsync(robj *o) {
* create a new empty set of hash tables and scheduling the old ones for
* lazy freeing. */
void emptyDbAsync(redisDb *db) {
dict *oldht1 = db->dict, *oldht2 = db->expires;
void *hashtable = db->dict, *tree = db->expires;
db->dict = dictCreate(&dbDictType,NULL);
db->expires = dictCreate(&keyptrDictType,NULL);
atomicIncr(lazyfree_objects,dictSize(oldht1));
bioCreateBackgroundJob(BIO_LAZY_FREE,NULL,oldht1,oldht2);
db->expires = raxNew();
atomicIncr(lazyfree_objects,dictSize((dict*)hashtable));
bioCreateBackgroundJob(BIO_LAZY_FREE,NULL,hashtable,tree);
}
/* Empty the slots-keys map of Redis CLuster by creating a new empty one
......@@ -136,10 +136,10 @@ void lazyfreeFreeObjectFromBioThread(robj *o) {
* when the database was logically deleted. 'sl' is a skiplist used by
* Redis Cluster in order to take the hash slots -> keys mapping. This
* may be NULL if Redis Cluster is disabled. */
void lazyfreeFreeDatabaseFromBioThread(dict *ht1, dict *ht2) {
size_t numkeys = dictSize(ht1);
dictRelease(ht1);
dictRelease(ht2);
void lazyfreeFreeDatabaseFromBioThread(dict *hashtable, rax *tree) {
size_t numkeys = dictSize(hashtable);
dictRelease(hashtable);
raxFree(tree);
atomicDecr(lazyfree_objects,numkeys);
}
......
......@@ -148,7 +148,8 @@ typedef struct RedisModuleCtx RedisModuleCtx;
struct RedisModuleKey {
RedisModuleCtx *ctx;
redisDb *db;
robj *key; /* Key name object. */
rkey *keyobj; /* Key object stored at the dictionary. */
robj *keyname; /* Key name object. */
robj *value; /* Value object, or NULL if the key was not found. */
void *iter; /* Iterator. */
int mode; /* Opening mode. */
......@@ -436,7 +437,7 @@ int moduleCreateEmptyKey(RedisModuleKey *key, int type) {
break;
default: return REDISMODULE_ERR;
}
dbAdd(key->db,key->key,obj);
key->keyobj = dbAdd(key->db,key->keyname,obj);
key->value = obj;
return REDISMODULE_OK;
}
......@@ -465,7 +466,7 @@ int moduleDelKeyIfEmpty(RedisModuleKey *key) {
}
if (isempty) {
dbDelete(key->db,key->key);
dbDelete(key->db,key->keyname);
key->value = NULL;
return 1;
} else {
......@@ -1519,11 +1520,12 @@ int RM_SelectDb(RedisModuleCtx *ctx, int newid) {
void *RM_OpenKey(RedisModuleCtx *ctx, robj *keyname, int mode) {
RedisModuleKey *kp;
robj *value;
rkey *keyobj;
if (mode & REDISMODULE_WRITE) {
value = lookupKeyWrite(ctx->client->db,keyname);
value = lookupKeyWrite(ctx->client->db,keyname,&keyobj);
} else {
value = lookupKeyRead(ctx->client->db,keyname);
value = lookupKeyRead(ctx->client->db,keyname,&keyobj);
if (value == NULL) {
return NULL;
}
......@@ -1533,8 +1535,9 @@ void *RM_OpenKey(RedisModuleCtx *ctx, robj *keyname, int mode) {
kp = zmalloc(sizeof(*kp));
kp->ctx = ctx;
kp->db = ctx->client->db;
kp->key = keyname;
kp->keyname = keyname;
incrRefCount(keyname);
kp->keyobj = keyobj;
kp->value = value;
kp->iter = NULL;
kp->mode = mode;
......@@ -1546,10 +1549,10 @@ void *RM_OpenKey(RedisModuleCtx *ctx, robj *keyname, int mode) {
/* Close a key handle. */
void RM_CloseKey(RedisModuleKey *key) {
if (key == NULL) return;
if (key->mode & REDISMODULE_WRITE) signalModifiedKey(key->db,key->key);
if (key->mode & REDISMODULE_WRITE) signalModifiedKey(key->db,key->keyname);
/* TODO: if (key->iter) RM_KeyIteratorStop(kp); */
RM_ZsetRangeStop(key);
decrRefCount(key->key);
decrRefCount(key->keyname);
autoMemoryFreed(key->ctx,REDISMODULE_AM_KEY,key);
zfree(key);
}
......@@ -1595,13 +1598,13 @@ size_t RM_ValueLength(RedisModuleKey *key) {
int RM_DeleteKey(RedisModuleKey *key) {
if (!(key->mode & REDISMODULE_WRITE)) return REDISMODULE_ERR;
if (key->value) {
dbDelete(key->db,key->key);
dbDelete(key->db,key->keyname);
key->value = NULL;
}
return REDISMODULE_OK;
}
/* If the key is open for writing, unlink it (that is delete it in a
/* If the key is open for writing, unlink it (that is delete it in a
* non-blocking way, not reclaiming memory immediately) and setup the key to
* accept new writes as an empty key (that will be created on demand).
* On success REDISMODULE_OK is returned. If the key is not open for
......@@ -1609,7 +1612,7 @@ int RM_DeleteKey(RedisModuleKey *key) {
int RM_UnlinkKey(RedisModuleKey *key) {
if (!(key->mode & REDISMODULE_WRITE)) return REDISMODULE_ERR;
if (key->value) {
dbAsyncDelete(key->db,key->key);
dbAsyncDelete(key->db,key->keyname);
key->value = NULL;
}
return REDISMODULE_OK;
......@@ -1619,7 +1622,7 @@ int RM_UnlinkKey(RedisModuleKey *key) {
* If no TTL is associated with the key or if the key is empty,
* REDISMODULE_NO_EXPIRE is returned. */
mstime_t RM_GetExpire(RedisModuleKey *key) {
mstime_t expire = getExpire(key->db,key->key);
mstime_t expire = getExpire(key->keyobj);
if (expire == -1 || key->value == NULL) return -1;
expire -= mstime();
return expire >= 0 ? expire : 0;
......@@ -1639,9 +1642,9 @@ int RM_SetExpire(RedisModuleKey *key, mstime_t expire) {
return REDISMODULE_ERR;
if (expire != REDISMODULE_NO_EXPIRE) {
expire += mstime();
setExpire(key->ctx->client,key->db,key->key,expire);
setExpire(key->ctx->client,key->db,key->keyobj,expire);
} else {
removeExpire(key->db,key->key);
removeExpire(key->db,key->keyobj);
}
return REDISMODULE_OK;
}
......@@ -1657,7 +1660,7 @@ int RM_SetExpire(RedisModuleKey *key, mstime_t expire) {
int RM_StringSet(RedisModuleKey *key, RedisModuleString *str) {
if (!(key->mode & REDISMODULE_WRITE) || key->iter) return REDISMODULE_ERR;
RM_DeleteKey(key);
setKey(key->db,key->key,str);
setKey(key->db,key->keyname,str);
key->value = str;
return REDISMODULE_OK;
}
......@@ -1707,7 +1710,7 @@ char *RM_StringDMA(RedisModuleKey *key, size_t *len, int mode) {
/* For write access, and even for read access if the object is encoded,
* we unshare the string (that has the side effect of decoding it). */
if ((mode & REDISMODULE_WRITE) || key->value->encoding != OBJ_ENCODING_RAW)
key->value = dbUnshareStringValue(key->db, key->key, key->value);
key->value = dbUnshareStringValue(key->db, key->keyname, key->value);
*len = sdslen(key->value->ptr);
return key->value->ptr;
......@@ -1737,12 +1740,12 @@ int RM_StringTruncate(RedisModuleKey *key, size_t newlen) {
if (key->value == NULL) {
/* Empty key: create it with the new size. */
robj *o = createObject(OBJ_STRING,sdsnewlen(NULL, newlen));
setKey(key->db,key->key,o);
setKey(key->db,key->keyname,o);
key->value = o;
decrRefCount(o);
} else {
/* Unshare and resize. */
key->value = dbUnshareStringValue(key->db, key->key, key->value);
key->value = dbUnshareStringValue(key->db, key->keyname, key->value);
size_t curlen = sdslen(key->value->ptr);
if (newlen > curlen) {
key->value->ptr = sdsgrowzero(key->value->ptr,newlen);
......@@ -3088,7 +3091,7 @@ int RM_ModuleTypeSetValue(RedisModuleKey *key, moduleType *mt, void *value) {
if (!(key->mode & REDISMODULE_WRITE) || key->iter) return REDISMODULE_ERR;
RM_DeleteKey(key);
robj *o = createModuleObject(mt,value);
setKey(key->db,key->key,o);
setKey(key->db,key->keyname,o);
decrRefCount(o);
key->value = o;
return REDISMODULE_OK;
......@@ -5031,7 +5034,8 @@ int dictCStringKeyCompare(void *privdata, const void *key1, const void *key2) {
}
dictType moduleAPIDictType = {
dictCStringKeyHash, /* hash function */
dictCStringKeyHash, /* lookup hash function */
dictCStringKeyHash, /* stored hash function */
NULL, /* key dup */
NULL, /* val dup */
dictCStringKeyCompare, /* key compare */
......
......@@ -44,14 +44,6 @@ robj *createObject(int type, void *ptr) {
o->encoding = OBJ_ENCODING_RAW;
o->ptr = ptr;
o->refcount = 1;
/* Set the LRU to the current lruclock (minutes resolution), or
* alternatively the LFU counter. */
if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) {
o->lru = (LFUGetTimeInMinutes()<<8) | LFU_INIT_VAL;
} else {
o->lru = LRU_CLOCK();
}
return o;
}
......@@ -89,11 +81,6 @@ robj *createEmbeddedStringObject(const char *ptr, size_t len) {
o->encoding = OBJ_ENCODING_EMBSTR;
o->ptr = sh+1;
o->refcount = 1;
if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) {
o->lru = (LFUGetTimeInMinutes()<<8) | LFU_INIT_VAL;
} else {
o->lru = LRU_CLOCK();
}
sh->len = len;
sh->alloc = len;
......@@ -1052,8 +1039,7 @@ struct redisMemOverhead *getMemoryOverheadData(void) {
mh->db[mh->num_dbs].overhead_ht_main = mem;
mem_total+=mem;
mem = dictSize(db->expires) * sizeof(dictEntry) +
dictSlots(db->expires) * sizeof(dictEntry*);
#warning "Fix the memory computation here with expires overhead"
mh->db[mh->num_dbs].overhead_ht_expires = mem;
mem_total+=mem;
......@@ -1202,12 +1188,12 @@ sds getMemoryDoctorReport(void) {
* The lru_idle and lru_clock args are only relevant if policy
* is MAXMEMORY_FLAG_LRU.
* Either or both of them may be <0, in that case, nothing is set. */
void objectSetLRUOrLFU(robj *val, long long lfu_freq, long long lru_idle,
void objectSetLRUOrLFU(rkey *key, long long lfu_freq, long long lru_idle,
long long lru_clock) {
if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) {
if (lfu_freq >= 0) {
serverAssert(lfu_freq <= 255);
val->lru = (LFUGetTimeInMinutes()<<8) | lfu_freq;
key->lru = (LFUGetTimeInMinutes()<<8) | lfu_freq;
}
} else if (lru_idle >= 0) {
/* Provided LRU idle time is in seconds. Scale
......@@ -1223,7 +1209,7 @@ void objectSetLRUOrLFU(robj *val, long long lfu_freq, long long lru_idle,
* some time. */
if (lru_abs < 0)
lru_abs = (lru_clock+(LRU_CLOCK_MAX/2)) % LRU_CLOCK_MAX;
val->lru = lru_abs;
key->lru = lru_abs;
}
}
......@@ -1231,15 +1217,16 @@ void objectSetLRUOrLFU(robj *val, long long lfu_freq, long long lru_idle,
/* This is a helper function for the OBJECT command. We need to lookup keys
* without any modification of LRU or other parameters. */
robj *objectCommandLookup(client *c, robj *key) {
robj *objectCommandLookup(client *c, robj *keyname, rkey **key) {
dictEntry *de;
if ((de = dictFind(c->db->dict,key->ptr)) == NULL) return NULL;
if ((de = dictFind(c->db->dict,keyname->ptr)) == NULL) return NULL;
if (key) *key = dictGetKey(de);
return (robj*) dictGetVal(de);
}
robj *objectCommandLookupOrReply(client *c, robj *key, robj *reply) {
robj *o = objectCommandLookup(c,key);
robj *objectCommandLookupOrReply(client *c, robj *keyname, rkey **key, robj *reply) {
robj *o = objectCommandLookup(c,keyname,key);
if (!o) addReply(c, reply);
return o;
......@@ -1260,24 +1247,26 @@ NULL
};
addReplyHelp(c, help);
} else if (!strcasecmp(c->argv[1]->ptr,"refcount") && c->argc == 3) {
if ((o = objectCommandLookupOrReply(c,c->argv[2],shared.null[c->resp]))
== NULL) return;
if ((o = objectCommandLookupOrReply(c,c->argv[2],NULL,
shared.null[c->resp])) == NULL) return;
addReplyLongLong(c,o->refcount);
} else if (!strcasecmp(c->argv[1]->ptr,"encoding") && c->argc == 3) {
if ((o = objectCommandLookupOrReply(c,c->argv[2],shared.null[c->resp]))
== NULL) return;
if ((o = objectCommandLookupOrReply(c,c->argv[2],NULL,
shared.null[c->resp])) == NULL) return;
addReplyBulkCString(c,strEncoding(o->encoding));
} else if (!strcasecmp(c->argv[1]->ptr,"idletime") && c->argc == 3) {
if ((o = objectCommandLookupOrReply(c,c->argv[2],shared.null[c->resp]))
== NULL) return;
rkey *key;
if ((o = objectCommandLookupOrReply(c,c->argv[2],&key,
shared.null[c->resp])) == NULL) return;
if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) {
addReplyError(c,"An LFU maxmemory policy is selected, idle time not tracked. Please note that when switching between policies at runtime LRU and LFU data will take some time to adjust.");
return;
}
addReplyLongLong(c,estimateObjectIdleTime(o)/1000);
addReplyLongLong(c,estimateObjectIdleTime(key)/1000);
} else if (!strcasecmp(c->argv[1]->ptr,"freq") && c->argc == 3) {
if ((o = objectCommandLookupOrReply(c,c->argv[2],shared.null[c->resp]))
== NULL) return;
rkey *k;
if ((o = objectCommandLookupOrReply(c,c->argv[2],&k,
shared.null[c->resp])) == NULL) return;
if (!(server.maxmemory_policy & MAXMEMORY_FLAG_LFU)) {
addReplyError(c,"An LFU maxmemory policy is not selected, access frequency not tracked. Please note that when switching between policies at runtime LRU and LFU data will take some time to adjust.");
return;
......@@ -1286,7 +1275,7 @@ NULL
* in case of the key has not been accessed for a long time,
* because we update the access time only
* when the key is read or overwritten. */
addReplyLongLong(c,LFUDecrAndReturn(o));
addReplyLongLong(c,LFUDecrAndReturn(k));
} else {
addReplySubcommandSyntaxError(c);
}
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment