]>
git.saurik.com Git - redis.git/blob - src/db.c
38983cb5a9d66ce331ee9226ef967ec6e83412fc
6 void SlotToKeyAdd(robj
*key
);
7 void SlotToKeyDel(robj
*key
);
9 /*-----------------------------------------------------------------------------
11 *----------------------------------------------------------------------------*/
13 /* Important notes on lookup and disk store.
15 * When disk store is enabled on lookup we can have different cases.
17 * a) The key is in memory:
18 * - If the key is not in IO_SAVEINPROG state we can access it.
19 * As if it's just IO_SAVE this means we have the key in the IO queue
20 * but can't be accessed by the IO thread (it requires to be
21 * translated into an IO Job by the cache cron function.)
22 * - If the key is in IO_SAVEINPROG we can't touch the key and have
23 * to blocking wait completion of operations.
24 * b) The key is not in memory:
25 * - If it's marked as non existing on disk as well (negative cache)
26 * we don't need to perform the disk access.
27 * - if the key MAY EXIST, but is not in memory, and it is marked as IO_SAVE
28 * then the key can only be a deleted one. As IO_SAVE keys are never
29 * evicted (dirty state), so the only possibility is that key was deleted.
30 * - if the key MAY EXIST we need to blocking load it.
31 * We check that the key is not in IO_SAVEINPROG state before accessing
32 * the disk object. If it is in this state, we wait.
35 robj
*lookupKey(redisDb
*db
, robj
*key
) {
36 dictEntry
*de
= dictFind(db
->dict
,key
->ptr
);
38 robj
*val
= dictGetVal(de
);
40 /* Update the access time for the aging algorithm.
41 * Don't do it if we have a saving child, as this will trigger
42 * a copy on write madness. */
43 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
44 val
->lru
= server
.lruclock
;
45 server
.stat_keyspace_hits
++;
48 server
.stat_keyspace_misses
++;
53 robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
54 expireIfNeeded(db
,key
);
55 return lookupKey(db
,key
);
58 robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
59 expireIfNeeded(db
,key
);
60 return lookupKey(db
,key
);
63 robj
*lookupKeyReadOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
64 robj
*o
= lookupKeyRead(c
->db
, key
);
65 if (!o
) addReply(c
,reply
);
69 robj
*lookupKeyWriteOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
70 robj
*o
= lookupKeyWrite(c
->db
, key
);
71 if (!o
) addReply(c
,reply
);
75 /* Add the key to the DB. It's up to the caller to increment the reference
76 * counte of the value if needed.
78 * The program is aborted if the key already exists. */
79 void dbAdd(redisDb
*db
, robj
*key
, robj
*val
) {
80 sds copy
= sdsdup(key
->ptr
);
81 int retval
= dictAdd(db
->dict
, copy
, val
);
83 redisAssertWithInfo(NULL
,key
,retval
== REDIS_OK
);
84 if (server
.cluster_enabled
) SlotToKeyAdd(key
);
87 /* Overwrite an existing key with a new value. Incrementing the reference
88 * count of the new value is up to the caller.
89 * This function does not modify the expire time of the existing key.
91 * The program is aborted if the key was not already present. */
92 void dbOverwrite(redisDb
*db
, robj
*key
, robj
*val
) {
93 struct dictEntry
*de
= dictFind(db
->dict
,key
->ptr
);
95 redisAssertWithInfo(NULL
,key
,de
!= NULL
);
96 dictReplace(db
->dict
, key
->ptr
, val
);
99 /* High level Set operation. This function can be used in order to set
100 * a key, whatever it was existing or not, to a new object.
102 * 1) The ref count of the value object is incremented.
103 * 2) clients WATCHing for the destination key notified.
104 * 3) The expire time of the key is reset (the key is made persistent). */
105 void setKey(redisDb
*db
, robj
*key
, robj
*val
) {
106 if (lookupKeyWrite(db
,key
) == NULL
) {
109 dbOverwrite(db
,key
,val
);
112 removeExpire(db
,key
);
113 touchWatchedKey(db
,key
);
116 int dbExists(redisDb
*db
, robj
*key
) {
117 return dictFind(db
->dict
,key
->ptr
) != NULL
;
120 /* Return a random key, in form of a Redis object.
121 * If there are no keys, NULL is returned.
123 * The function makes sure to return keys not already expired. */
124 robj
*dbRandomKey(redisDb
*db
) {
125 struct dictEntry
*de
;
131 de
= dictGetRandomKey(db
->dict
);
132 if (de
== NULL
) return NULL
;
134 key
= dictGetKey(de
);
135 keyobj
= createStringObject(key
,sdslen(key
));
136 if (dictFind(db
->expires
,key
)) {
137 if (expireIfNeeded(db
,keyobj
)) {
138 decrRefCount(keyobj
);
139 continue; /* search for another key. This expired. */
146 /* Delete a key, value, and associated expiration entry if any, from the DB */
147 int dbDelete(redisDb
*db
, robj
*key
) {
148 /* Deleting an entry from the expires dict will not free the sds of
149 * the key, because it is shared with the main dictionary. */
150 if (dictSize(db
->expires
) > 0) dictDelete(db
->expires
,key
->ptr
);
151 if (dictDelete(db
->dict
,key
->ptr
) == DICT_OK
) {
152 if (server
.cluster_enabled
) SlotToKeyDel(key
);
159 /* Empty the whole database.
160 * If diskstore is enabled this function will just flush the in-memory cache. */
161 long long emptyDb() {
163 long long removed
= 0;
165 for (j
= 0; j
< server
.dbnum
; j
++) {
166 removed
+= dictSize(server
.db
[j
].dict
);
167 dictEmpty(server
.db
[j
].dict
);
168 dictEmpty(server
.db
[j
].expires
);
173 int selectDb(redisClient
*c
, int id
) {
174 if (id
< 0 || id
>= server
.dbnum
)
176 c
->db
= &server
.db
[id
];
180 /*-----------------------------------------------------------------------------
181 * Hooks for key space changes.
183 * Every time a key in the database is modified the function
184 * signalModifiedKey() is called.
186 * Every time a DB is flushed the function signalFlushDb() is called.
187 *----------------------------------------------------------------------------*/
189 void signalModifiedKey(redisDb
*db
, robj
*key
) {
190 touchWatchedKey(db
,key
);
193 void signalFlushedDb(int dbid
) {
194 touchWatchedKeysOnFlush(dbid
);
197 /*-----------------------------------------------------------------------------
198 * Type agnostic commands operating on the key space
199 *----------------------------------------------------------------------------*/
201 void flushdbCommand(redisClient
*c
) {
202 server
.dirty
+= dictSize(c
->db
->dict
);
203 signalFlushedDb(c
->db
->id
);
204 dictEmpty(c
->db
->dict
);
205 dictEmpty(c
->db
->expires
);
206 addReply(c
,shared
.ok
);
209 void flushallCommand(redisClient
*c
) {
211 server
.dirty
+= emptyDb();
212 addReply(c
,shared
.ok
);
213 if (server
.bgsavechildpid
!= -1) {
214 kill(server
.bgsavechildpid
,SIGKILL
);
215 rdbRemoveTempFile(server
.bgsavechildpid
);
217 if (server
.saveparamslen
> 0) {
218 /* Normally rdbSave() will reset dirty, but we don't want this here
219 * as otherwise FLUSHALL will not be replicated nor put into the AOF. */
220 int saved_dirty
= server
.dirty
;
221 rdbSave(server
.dbfilename
);
222 server
.dirty
= saved_dirty
;
227 void delCommand(redisClient
*c
) {
230 for (j
= 1; j
< c
->argc
; j
++) {
231 if (dbDelete(c
->db
,c
->argv
[j
])) {
232 signalModifiedKey(c
->db
,c
->argv
[j
]);
237 addReplyLongLong(c
,deleted
);
240 void existsCommand(redisClient
*c
) {
241 expireIfNeeded(c
->db
,c
->argv
[1]);
242 if (dbExists(c
->db
,c
->argv
[1])) {
243 addReply(c
, shared
.cone
);
245 addReply(c
, shared
.czero
);
249 void selectCommand(redisClient
*c
) {
250 int id
= atoi(c
->argv
[1]->ptr
);
252 if (server
.cluster_enabled
&& id
!= 0) {
253 addReplyError(c
,"SELECT is not allowed in cluster mode");
256 if (selectDb(c
,id
) == REDIS_ERR
) {
257 addReplyError(c
,"invalid DB index");
259 addReply(c
,shared
.ok
);
263 void randomkeyCommand(redisClient
*c
) {
266 if ((key
= dbRandomKey(c
->db
)) == NULL
) {
267 addReply(c
,shared
.nullbulk
);
275 void keysCommand(redisClient
*c
) {
278 sds pattern
= c
->argv
[1]->ptr
;
279 int plen
= sdslen(pattern
), allkeys
;
280 unsigned long numkeys
= 0;
281 void *replylen
= addDeferredMultiBulkLength(c
);
283 di
= dictGetIterator(c
->db
->dict
);
284 allkeys
= (pattern
[0] == '*' && pattern
[1] == '\0');
285 while((de
= dictNext(di
)) != NULL
) {
286 sds key
= dictGetKey(de
);
289 if (allkeys
|| stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
290 keyobj
= createStringObject(key
,sdslen(key
));
291 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
292 addReplyBulk(c
,keyobj
);
295 decrRefCount(keyobj
);
298 dictReleaseIterator(di
);
299 setDeferredMultiBulkLength(c
,replylen
,numkeys
);
302 void dbsizeCommand(redisClient
*c
) {
303 addReplyLongLong(c
,dictSize(c
->db
->dict
));
306 void lastsaveCommand(redisClient
*c
) {
307 addReplyLongLong(c
,server
.lastsave
);
310 void typeCommand(redisClient
*c
) {
314 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
319 case REDIS_STRING
: type
= "string"; break;
320 case REDIS_LIST
: type
= "list"; break;
321 case REDIS_SET
: type
= "set"; break;
322 case REDIS_ZSET
: type
= "zset"; break;
323 case REDIS_HASH
: type
= "hash"; break;
324 default: type
= "unknown"; break;
327 addReplyStatus(c
,type
);
330 void shutdownCommand(redisClient
*c
) {
331 if (prepareForShutdown() == REDIS_OK
)
333 addReplyError(c
,"Errors trying to SHUTDOWN. Check logs.");
336 void renameGenericCommand(redisClient
*c
, int nx
) {
340 /* To use the same key as src and dst is probably an error */
341 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
342 addReply(c
,shared
.sameobjecterr
);
346 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
)
350 expire
= getExpire(c
->db
,c
->argv
[1]);
351 if (lookupKeyWrite(c
->db
,c
->argv
[2]) != NULL
) {
354 addReply(c
,shared
.czero
);
357 /* Overwrite: delete the old key before creating the new one with the same name. */
358 dbDelete(c
->db
,c
->argv
[2]);
360 dbAdd(c
->db
,c
->argv
[2],o
);
361 if (expire
!= -1) setExpire(c
->db
,c
->argv
[2],expire
);
362 dbDelete(c
->db
,c
->argv
[1]);
363 signalModifiedKey(c
->db
,c
->argv
[1]);
364 signalModifiedKey(c
->db
,c
->argv
[2]);
366 addReply(c
,nx
? shared
.cone
: shared
.ok
);
369 void renameCommand(redisClient
*c
) {
370 renameGenericCommand(c
,0);
373 void renamenxCommand(redisClient
*c
) {
374 renameGenericCommand(c
,1);
377 void moveCommand(redisClient
*c
) {
382 if (server
.cluster_enabled
) {
383 addReplyError(c
,"MOVE is not allowed in cluster mode");
387 /* Obtain source and target DB pointers */
390 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
391 addReply(c
,shared
.outofrangeerr
);
395 selectDb(c
,srcid
); /* Back to the source DB */
397 /* If the user is moving using as target the same
398 * DB as the source DB it is probably an error. */
400 addReply(c
,shared
.sameobjecterr
);
404 /* Check if the element exists and get a reference */
405 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
407 addReply(c
,shared
.czero
);
411 /* Return zero if the key already exists in the target DB */
412 if (lookupKeyWrite(dst
,c
->argv
[1]) != NULL
) {
413 addReply(c
,shared
.czero
);
416 dbAdd(dst
,c
->argv
[1],o
);
419 /* OK! key moved, free the entry in the source DB */
420 dbDelete(src
,c
->argv
[1]);
422 addReply(c
,shared
.cone
);
425 /*-----------------------------------------------------------------------------
427 *----------------------------------------------------------------------------*/
429 int removeExpire(redisDb
*db
, robj
*key
) {
430 /* An expire may only be removed if there is a corresponding entry in the
431 * main dict. Otherwise, the key will never be freed. */
432 redisAssertWithInfo(NULL
,key
,dictFind(db
->dict
,key
->ptr
) != NULL
);
433 return dictDelete(db
->expires
,key
->ptr
) == DICT_OK
;
436 void setExpire(redisDb
*db
, robj
*key
, long long when
) {
439 /* Reuse the sds from the main dict in the expire dict */
440 kde
= dictFind(db
->dict
,key
->ptr
);
441 redisAssertWithInfo(NULL
,key
,kde
!= NULL
);
442 de
= dictReplaceRaw(db
->expires
,dictGetKey(kde
));
443 dictSetSignedIntegerVal(de
,when
);
446 /* Return the expire time of the specified key, or -1 if no expire
447 * is associated with this key (i.e. the key is non volatile) */
448 long long getExpire(redisDb
*db
, robj
*key
) {
451 /* No expire? return ASAP */
452 if (dictSize(db
->expires
) == 0 ||
453 (de
= dictFind(db
->expires
,key
->ptr
)) == NULL
) return -1;
455 /* The entry was found in the expire dict, this means it should also
456 * be present in the main dict (safety check). */
457 redisAssertWithInfo(NULL
,key
,dictFind(db
->dict
,key
->ptr
) != NULL
);
458 return dictGetSignedIntegerVal(de
);
461 /* Propagate expires into slaves and the AOF file.
462 * When a key expires in the master, a DEL operation for this key is sent
463 * to all the slaves and the AOF file if enabled.
465 * This way the key expiry is centralized in one place, and since both
466 * AOF and the master->slave link guarantee operation ordering, everything
467 * will be consistent even if we allow write operations against expiring
469 void propagateExpire(redisDb
*db
, robj
*key
) {
472 argv
[0] = createStringObject("DEL",3);
476 if (server
.appendonly
)
477 feedAppendOnlyFile(server
.delCommand
,db
->id
,argv
,2);
478 if (listLength(server
.slaves
))
479 replicationFeedSlaves(server
.slaves
,db
->id
,argv
,2);
481 decrRefCount(argv
[0]);
482 decrRefCount(argv
[1]);
485 int expireIfNeeded(redisDb
*db
, robj
*key
) {
486 long long when
= getExpire(db
,key
);
488 if (when
< 0) return 0; /* No expire for this key */
490 /* Don't expire anything while loading. It will be done later. */
491 if (server
.loading
) return 0;
493 /* If we are running in the context of a slave, return ASAP:
494 * the slave key expiration is controlled by the master that will
495 * send us synthesized DEL operations for expired keys.
497 * Still we try to return the right information to the caller,
498 * that is, 0 if we think the key should be still valid, 1 if
499 * we think the key is expired at this time. */
500 if (server
.masterhost
!= NULL
) {
501 return time(NULL
) > when
;
504 /* Return when this key has not expired */
505 if (mstime() <= when
) return 0;
508 server
.stat_expiredkeys
++;
509 propagateExpire(db
,key
);
510 return dbDelete(db
,key
);
513 /*-----------------------------------------------------------------------------
515 *----------------------------------------------------------------------------*/
517 /* Given an string object return true if it contains exactly the "ms"
518 * or "MS" string. This is used in order to check if the last argument
519 * of EXPIRE, EXPIREAT or TTL is "ms" to switch into millisecond input/output */
520 int stringObjectEqualsMs(robj
*a
) {
522 return tolower(arg
[0]) == 'm' && tolower(arg
[1]) == 's' && arg
[2] == '\0';
525 void expireGenericCommand(redisClient
*c
, long long offset
, int unit
) {
527 robj
*key
= c
->argv
[1], *param
= c
->argv
[2];
528 long long milliseconds
;
530 if (getLongLongFromObjectOrReply(c
, param
, &milliseconds
, NULL
) != REDIS_OK
)
533 if (unit
== UNIT_SECONDS
) milliseconds
*= 1000;
534 milliseconds
-= offset
;
536 de
= dictFind(c
->db
->dict
,key
->ptr
);
538 addReply(c
,shared
.czero
);
541 /* EXPIRE with negative TTL, or EXPIREAT with a timestamp into the past
542 * should never be executed as a DEL when load the AOF or in the context
543 * of a slave instance.
545 * Instead we take the other branch of the IF statement setting an expire
546 * (possibly in the past) and wait for an explicit DEL from the master. */
547 if (milliseconds
<= 0 && !server
.loading
&& !server
.masterhost
) {
550 redisAssertWithInfo(c
,key
,dbDelete(c
->db
,key
));
553 /* Replicate/AOF this as an explicit DEL. */
554 aux
= createStringObject("DEL",3);
555 rewriteClientCommandVector(c
,2,aux
,key
);
557 signalModifiedKey(c
->db
,key
);
558 addReply(c
, shared
.cone
);
561 long long when
= mstime()+milliseconds
;
562 setExpire(c
->db
,key
,when
);
563 addReply(c
,shared
.cone
);
564 signalModifiedKey(c
->db
,key
);
570 void expireCommand(redisClient
*c
) {
571 expireGenericCommand(c
,0,UNIT_SECONDS
);
574 void expireatCommand(redisClient
*c
) {
575 expireGenericCommand(c
,mstime(),UNIT_SECONDS
);
578 void pexpireCommand(redisClient
*c
) {
579 expireGenericCommand(c
,0,UNIT_MILLISECONDS
);
582 void pexpireatCommand(redisClient
*c
) {
583 expireGenericCommand(c
,mstime(),UNIT_MILLISECONDS
);
586 void ttlGenericCommand(redisClient
*c
, int output_ms
) {
587 long long expire
, ttl
= -1;
589 expire
= getExpire(c
->db
,c
->argv
[1]);
591 ttl
= expire
-mstime();
592 if (ttl
< 0) ttl
= -1;
595 addReplyLongLong(c
,-1);
597 addReplyLongLong(c
,output_ms
? ttl
: ((ttl
+500)/1000));
601 void ttlCommand(redisClient
*c
) {
602 ttlGenericCommand(c
, 0);
605 void pttlCommand(redisClient
*c
) {
606 ttlGenericCommand(c
, 1);
609 void persistCommand(redisClient
*c
) {
612 de
= dictFind(c
->db
->dict
,c
->argv
[1]->ptr
);
614 addReply(c
,shared
.czero
);
616 if (removeExpire(c
->db
,c
->argv
[1])) {
617 addReply(c
,shared
.cone
);
620 addReply(c
,shared
.czero
);
625 /* -----------------------------------------------------------------------------
626 * API to get key arguments from commands
627 * ---------------------------------------------------------------------------*/
629 int *getKeysUsingCommandTable(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
) {
630 int j
, i
= 0, last
, *keys
;
633 if (cmd
->firstkey
== 0) {
638 if (last
< 0) last
= argc
+last
;
639 keys
= zmalloc(sizeof(int)*((last
- cmd
->firstkey
)+1));
640 for (j
= cmd
->firstkey
; j
<= last
; j
+= cmd
->keystep
) {
641 redisAssert(j
< argc
);
648 int *getKeysFromCommand(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
649 if (cmd
->getkeys_proc
) {
650 return cmd
->getkeys_proc(cmd
,argv
,argc
,numkeys
,flags
);
652 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
656 void getKeysFreeResult(int *result
) {
660 int *noPreloadGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
661 if (flags
& REDIS_GETKEYS_PRELOAD
) {
665 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
669 int *renameGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
670 if (flags
& REDIS_GETKEYS_PRELOAD
) {
671 int *keys
= zmalloc(sizeof(int));
676 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
680 int *zunionInterGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
683 REDIS_NOTUSED(flags
);
685 num
= atoi(argv
[2]->ptr
);
686 /* Sanity check. Don't return any key if the command is going to
687 * reply with syntax error. */
688 if (num
> (argc
-3)) {
692 keys
= zmalloc(sizeof(int)*num
);
693 for (i
= 0; i
< num
; i
++) keys
[i
] = 3+i
;
698 /* Slot to Key API. This is used by Redis Cluster in order to obtain in
699 * a fast way a key that belongs to a specified hash slot. This is useful
700 * while rehashing the cluster. */
701 void SlotToKeyAdd(robj
*key
) {
702 unsigned int hashslot
= keyHashSlot(key
->ptr
,sdslen(key
->ptr
));
704 zslInsert(server
.cluster
.slots_to_keys
,hashslot
,key
);
708 void SlotToKeyDel(robj
*key
) {
709 unsigned int hashslot
= keyHashSlot(key
->ptr
,sdslen(key
->ptr
));
711 zslDelete(server
.cluster
.slots_to_keys
,hashslot
,key
);
714 unsigned int GetKeysInSlot(unsigned int hashslot
, robj
**keys
, unsigned int count
) {
719 range
.min
= range
.max
= hashslot
;
720 range
.minex
= range
.maxex
= 0;
722 n
= zslFirstInRange(server
.cluster
.slots_to_keys
, range
);
723 while(n
&& n
->score
== hashslot
&& count
--) {
725 n
= n
->level
[0].forward
;