]>
git.saurik.com Git - redis.git/blob - src/db.c
5 void SlotToKeyAdd(robj
*key
);
6 void SlotToKeyDel(robj
*key
);
8 /*-----------------------------------------------------------------------------
10 *----------------------------------------------------------------------------*/
12 /* Important notes on lookup and disk store.
14 * When disk store is enabled on lookup we can have different cases.
16 * a) The key is in memory:
17 * - If the key is not in IO_SAVEINPROG state we can access it.
18 * As if it's just IO_SAVE this means we have the key in the IO queue
19 * but can't be accessed by the IO thread (it requires to be
20 * translated into an IO Job by the cache cron function.)
21 * - If the key is in IO_SAVEINPROG we can't touch the key and have
22 * to blocking wait completion of operations.
23 * b) The key is not in memory:
24 * - If it's marked as non existing on disk as well (negative cache)
25 * we don't need to perform the disk access.
26 * - if the key MAY EXIST, but is not in memory, and it is marked as IO_SAVE
27 * then the key can only be a deleted one. As IO_SAVE keys are never
28 * evicted (dirty state), so the only possibility is that key was deleted.
29 * - if the key MAY EXIST we need to blocking load it.
30 * We check that the key is not in IO_SAVEINPROG state before accessing
31 * the disk object. If it is in this state, we wait.
34 void lookupWaitBusyKey(redisDb
*db
, robj
*key
) {
35 /* FIXME: wait just for this key, not everything */
36 waitEmptyIOJobsQueue();
37 processAllPendingIOJobs();
38 redisAssert((cacheScheduleIOGetFlags(db
,key
) & REDIS_IO_SAVEINPROG
) == 0);
41 robj
*lookupKey(redisDb
*db
, robj
*key
) {
42 dictEntry
*de
= dictFind(db
->dict
,key
->ptr
);
44 robj
*val
= dictGetEntryVal(de
);
46 /* Update the access time for the aging algorithm.
47 * Don't do it if we have a saving child, as this will trigger
48 * a copy on write madness. */
49 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
50 val
->lru
= server
.lruclock
;
52 if (server
.ds_enabled
&&
53 cacheScheduleIOGetFlags(db
,key
) & REDIS_IO_SAVEINPROG
)
55 /* Need to wait for the key to get unbusy */
56 redisLog(REDIS_DEBUG
,"Lookup found a key in SAVEINPROG state. Waiting. (Key was in the cache)");
57 lookupWaitBusyKey(db
,key
);
59 server
.stat_keyspace_hits
++;
65 /* Key not found in the in memory hash table, but if disk store is
66 * enabled we may have this key on disk. If so load it in memory
67 * in a blocking way. */
68 if (server
.ds_enabled
&& cacheKeyMayExist(db
,key
)) {
69 long flags
= cacheScheduleIOGetFlags(db
,key
);
71 /* They key is not in cache, but it has a SAVE op in queue?
72 * The only possibility is that the key was deleted, since
73 * dirty keys are not evicted. */
74 if (flags
& REDIS_IO_SAVE
) {
75 server
.stat_keyspace_misses
++;
79 /* At this point we need to blocking load the key in memory.
80 * The first thing we do is waiting here if the key is busy. */
81 if (flags
& REDIS_IO_SAVEINPROG
) {
82 redisLog(REDIS_DEBUG
,"Lookup found a key in SAVEINPROG state. Waiting (while force loading).");
83 lookupWaitBusyKey(db
,key
);
86 redisLog(REDIS_DEBUG
,"Force loading key %s via lookup", key
->ptr
);
87 val
= dsGet(db
,key
,&expire
);
90 if (expire
!= -1) setExpire(db
,key
,expire
);
91 server
.stat_keyspace_hits
++;
94 cacheSetKeyDoesNotExist(db
,key
);
97 server
.stat_keyspace_misses
++;
102 robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
103 expireIfNeeded(db
,key
);
104 return lookupKey(db
,key
);
107 robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
108 expireIfNeeded(db
,key
);
109 return lookupKey(db
,key
);
112 robj
*lookupKeyReadOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
113 robj
*o
= lookupKeyRead(c
->db
, key
);
114 if (!o
) addReply(c
,reply
);
118 robj
*lookupKeyWriteOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
119 robj
*o
= lookupKeyWrite(c
->db
, key
);
120 if (!o
) addReply(c
,reply
);
124 /* Add the key to the DB. It's up to the caller to increment the reference
125 * counte of the value if needed.
127 * The program is aborted if the key already exists. */
128 void dbAdd(redisDb
*db
, robj
*key
, robj
*val
) {
129 sds copy
= sdsdup(key
->ptr
);
130 int retval
= dictAdd(db
->dict
, copy
, val
);
132 redisAssert(retval
== REDIS_OK
);
133 if (server
.ds_enabled
) cacheSetKeyMayExist(db
,key
);
134 if (server
.cluster_enabled
) SlotToKeyAdd(key
);
137 /* Overwrite an existing key with a new value. Incrementing the reference
138 * count of the new value is up to the caller.
139 * This function does not modify the expire time of the existing key.
141 * The program is aborted if the key was not already present. */
142 void dbOverwrite(redisDb
*db
, robj
*key
, robj
*val
) {
143 struct dictEntry
*de
= dictFind(db
->dict
,key
->ptr
);
145 redisAssert(de
!= NULL
);
146 dictReplace(db
->dict
, key
->ptr
, val
);
147 if (server
.ds_enabled
) cacheSetKeyMayExist(db
,key
);
150 /* High level Set operation. This function can be used in order to set
151 * a key, whatever it was existing or not, to a new object.
153 * 1) The ref count of the value object is incremented.
154 * 2) clients WATCHing for the destination key notified.
155 * 3) The expire time of the key is reset (the key is made persistent). */
156 void setKey(redisDb
*db
, robj
*key
, robj
*val
) {
157 if (lookupKeyWrite(db
,key
) == NULL
) {
160 dbOverwrite(db
,key
,val
);
163 removeExpire(db
,key
);
164 touchWatchedKey(db
,key
);
167 int dbExists(redisDb
*db
, robj
*key
) {
168 return dictFind(db
->dict
,key
->ptr
) != NULL
;
171 /* Return a random key, in form of a Redis object.
172 * If there are no keys, NULL is returned.
174 * The function makes sure to return keys not already expired. */
175 robj
*dbRandomKey(redisDb
*db
) {
176 struct dictEntry
*de
;
182 de
= dictGetRandomKey(db
->dict
);
183 if (de
== NULL
) return NULL
;
185 key
= dictGetEntryKey(de
);
186 keyobj
= createStringObject(key
,sdslen(key
));
187 if (dictFind(db
->expires
,key
)) {
188 if (expireIfNeeded(db
,keyobj
)) {
189 decrRefCount(keyobj
);
190 continue; /* search for another key. This expired. */
197 /* Delete a key, value, and associated expiration entry if any, from the DB */
198 int dbDelete(redisDb
*db
, robj
*key
) {
199 /* If diskstore is enabled make sure to awake waiting clients for this key
200 * as it is not really useful to wait for a key already deleted to be
201 * loaded from disk. */
202 if (server
.ds_enabled
) {
203 handleClientsBlockedOnSwappedKey(db
,key
);
204 cacheSetKeyDoesNotExist(db
,key
);
207 /* Deleting an entry from the expires dict will not free the sds of
208 * the key, because it is shared with the main dictionary. */
209 if (dictSize(db
->expires
) > 0) dictDelete(db
->expires
,key
->ptr
);
210 if (dictDelete(db
->dict
,key
->ptr
) == DICT_OK
) {
211 if (server
.cluster_enabled
) SlotToKeyDel(key
);
218 /* Empty the whole database.
219 * If diskstore is enabled this function will just flush the in-memory cache. */
220 long long emptyDb() {
222 long long removed
= 0;
224 for (j
= 0; j
< server
.dbnum
; j
++) {
225 removed
+= dictSize(server
.db
[j
].dict
);
226 dictEmpty(server
.db
[j
].dict
);
227 dictEmpty(server
.db
[j
].expires
);
228 if (server
.ds_enabled
) dictEmpty(server
.db
[j
].io_negcache
);
233 int selectDb(redisClient
*c
, int id
) {
234 if (id
< 0 || id
>= server
.dbnum
)
236 c
->db
= &server
.db
[id
];
240 /*-----------------------------------------------------------------------------
241 * Hooks for key space changes.
243 * Every time a key in the database is modified the function
244 * signalModifiedKey() is called.
246 * Every time a DB is flushed the function signalFlushDb() is called.
247 *----------------------------------------------------------------------------*/
249 void signalModifiedKey(redisDb
*db
, robj
*key
) {
250 touchWatchedKey(db
,key
);
251 if (server
.ds_enabled
)
252 cacheScheduleIO(db
,key
,REDIS_IO_SAVE
);
255 void signalFlushedDb(int dbid
) {
256 touchWatchedKeysOnFlush(dbid
);
259 /*-----------------------------------------------------------------------------
260 * Type agnostic commands operating on the key space
261 *----------------------------------------------------------------------------*/
263 void flushdbCommand(redisClient
*c
) {
264 server
.dirty
+= dictSize(c
->db
->dict
);
265 signalFlushedDb(c
->db
->id
);
266 dictEmpty(c
->db
->dict
);
267 dictEmpty(c
->db
->expires
);
268 if (server
.ds_enabled
) dsFlushDb(c
->db
->id
);
269 addReply(c
,shared
.ok
);
272 void flushallCommand(redisClient
*c
) {
274 server
.dirty
+= emptyDb();
275 addReply(c
,shared
.ok
);
276 if (server
.bgsavechildpid
!= -1) {
277 kill(server
.bgsavechildpid
,SIGKILL
);
278 rdbRemoveTempFile(server
.bgsavechildpid
);
280 if (server
.ds_enabled
)
283 rdbSave(server
.dbfilename
);
287 void delCommand(redisClient
*c
) {
290 for (j
= 1; j
< c
->argc
; j
++) {
291 if (server
.ds_enabled
) {
292 lookupKeyRead(c
->db
,c
->argv
[j
]);
293 /* FIXME: this can be optimized a lot, no real need to load
294 * a possibly huge value. */
296 if (dbDelete(c
->db
,c
->argv
[j
])) {
297 signalModifiedKey(c
->db
,c
->argv
[j
]);
300 } else if (server
.ds_enabled
) {
301 if (cacheKeyMayExist(c
->db
,c
->argv
[j
]) &&
302 dsExists(c
->db
,c
->argv
[j
]))
304 cacheScheduleIO(c
->db
,c
->argv
[j
],REDIS_IO_SAVE
);
309 addReplyLongLong(c
,deleted
);
312 void existsCommand(redisClient
*c
) {
313 expireIfNeeded(c
->db
,c
->argv
[1]);
314 if (dbExists(c
->db
,c
->argv
[1])) {
315 addReply(c
, shared
.cone
);
317 addReply(c
, shared
.czero
);
321 void selectCommand(redisClient
*c
) {
322 int id
= atoi(c
->argv
[1]->ptr
);
324 if (server
.cluster_enabled
&& id
!= 0) {
325 addReplyError(c
,"SELECT is not allowed in cluster mode");
328 if (selectDb(c
,id
) == REDIS_ERR
) {
329 addReplyError(c
,"invalid DB index");
331 addReply(c
,shared
.ok
);
335 void randomkeyCommand(redisClient
*c
) {
338 if ((key
= dbRandomKey(c
->db
)) == NULL
) {
339 addReply(c
,shared
.nullbulk
);
347 void keysCommand(redisClient
*c
) {
350 sds pattern
= c
->argv
[1]->ptr
;
351 int plen
= sdslen(pattern
), allkeys
;
352 unsigned long numkeys
= 0;
353 void *replylen
= addDeferredMultiBulkLength(c
);
355 di
= dictGetIterator(c
->db
->dict
);
356 allkeys
= (pattern
[0] == '*' && pattern
[1] == '\0');
357 while((de
= dictNext(di
)) != NULL
) {
358 sds key
= dictGetEntryKey(de
);
361 if (allkeys
|| stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
362 keyobj
= createStringObject(key
,sdslen(key
));
363 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
364 addReplyBulk(c
,keyobj
);
367 decrRefCount(keyobj
);
370 dictReleaseIterator(di
);
371 setDeferredMultiBulkLength(c
,replylen
,numkeys
);
374 void dbsizeCommand(redisClient
*c
) {
375 addReplyLongLong(c
,dictSize(c
->db
->dict
));
378 void lastsaveCommand(redisClient
*c
) {
379 addReplyLongLong(c
,server
.lastsave
);
382 void typeCommand(redisClient
*c
) {
386 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
391 case REDIS_STRING
: type
= "string"; break;
392 case REDIS_LIST
: type
= "list"; break;
393 case REDIS_SET
: type
= "set"; break;
394 case REDIS_ZSET
: type
= "zset"; break;
395 case REDIS_HASH
: type
= "hash"; break;
396 default: type
= "unknown"; break;
399 addReplyStatus(c
,type
);
402 void shutdownCommand(redisClient
*c
) {
403 if (prepareForShutdown() == REDIS_OK
)
405 addReplyError(c
,"Errors trying to SHUTDOWN. Check logs.");
408 void renameGenericCommand(redisClient
*c
, int nx
) {
411 /* To use the same key as src and dst is probably an error */
412 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
413 addReply(c
,shared
.sameobjecterr
);
417 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
)
421 if (lookupKeyWrite(c
->db
,c
->argv
[2]) != NULL
) {
424 addReply(c
,shared
.czero
);
427 dbOverwrite(c
->db
,c
->argv
[2],o
);
429 dbAdd(c
->db
,c
->argv
[2],o
);
431 dbDelete(c
->db
,c
->argv
[1]);
432 signalModifiedKey(c
->db
,c
->argv
[1]);
433 signalModifiedKey(c
->db
,c
->argv
[2]);
435 addReply(c
,nx
? shared
.cone
: shared
.ok
);
438 void renameCommand(redisClient
*c
) {
439 renameGenericCommand(c
,0);
442 void renamenxCommand(redisClient
*c
) {
443 renameGenericCommand(c
,1);
446 void moveCommand(redisClient
*c
) {
451 if (server
.cluster_enabled
) {
452 addReplyError(c
,"MOVE is not allowed in cluster mode");
456 /* Obtain source and target DB pointers */
459 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
460 addReply(c
,shared
.outofrangeerr
);
464 selectDb(c
,srcid
); /* Back to the source DB */
466 /* If the user is moving using as target the same
467 * DB as the source DB it is probably an error. */
469 addReply(c
,shared
.sameobjecterr
);
473 /* Check if the element exists and get a reference */
474 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
476 addReply(c
,shared
.czero
);
480 /* Return zero if the key already exists in the target DB */
481 if (lookupKeyWrite(dst
,c
->argv
[1]) != NULL
) {
482 addReply(c
,shared
.czero
);
485 dbAdd(dst
,c
->argv
[1],o
);
488 /* OK! key moved, free the entry in the source DB */
489 dbDelete(src
,c
->argv
[1]);
491 addReply(c
,shared
.cone
);
494 /*-----------------------------------------------------------------------------
496 *----------------------------------------------------------------------------*/
498 int removeExpire(redisDb
*db
, robj
*key
) {
499 /* An expire may only be removed if there is a corresponding entry in the
500 * main dict. Otherwise, the key will never be freed. */
501 redisAssert(dictFind(db
->dict
,key
->ptr
) != NULL
);
502 return dictDelete(db
->expires
,key
->ptr
) == DICT_OK
;
505 void setExpire(redisDb
*db
, robj
*key
, time_t when
) {
508 /* Reuse the sds from the main dict in the expire dict */
509 de
= dictFind(db
->dict
,key
->ptr
);
510 redisAssert(de
!= NULL
);
511 dictReplace(db
->expires
,dictGetEntryKey(de
),(void*)when
);
514 /* Return the expire time of the specified key, or -1 if no expire
515 * is associated with this key (i.e. the key is non volatile) */
516 time_t getExpire(redisDb
*db
, robj
*key
) {
519 /* No expire? return ASAP */
520 if (dictSize(db
->expires
) == 0 ||
521 (de
= dictFind(db
->expires
,key
->ptr
)) == NULL
) return -1;
523 /* The entry was found in the expire dict, this means it should also
524 * be present in the main dict (safety check). */
525 redisAssert(dictFind(db
->dict
,key
->ptr
) != NULL
);
526 return (time_t) dictGetEntryVal(de
);
529 /* Propagate expires into slaves and the AOF file.
530 * When a key expires in the master, a DEL operation for this key is sent
531 * to all the slaves and the AOF file if enabled.
533 * This way the key expiry is centralized in one place, and since both
534 * AOF and the master->slave link guarantee operation ordering, everything
535 * will be consistent even if we allow write operations against expiring
537 void propagateExpire(redisDb
*db
, robj
*key
) {
540 argv
[0] = createStringObject("DEL",3);
544 if (server
.appendonly
)
545 feedAppendOnlyFile(server
.delCommand
,db
->id
,argv
,2);
546 if (listLength(server
.slaves
))
547 replicationFeedSlaves(server
.slaves
,db
->id
,argv
,2);
549 decrRefCount(argv
[0]);
550 decrRefCount(argv
[1]);
553 int expireIfNeeded(redisDb
*db
, robj
*key
) {
554 time_t when
= getExpire(db
,key
);
556 if (when
< 0) return 0; /* No expire for this key */
558 /* If we are running in the context of a slave, return ASAP:
559 * the slave key expiration is controlled by the master that will
560 * send us synthesized DEL operations for expired keys.
562 * Still we try to return the right information to the caller,
563 * that is, 0 if we think the key should be still valid, 1 if
564 * we think the key is expired at this time. */
565 if (server
.masterhost
!= NULL
) {
566 return time(NULL
) > when
;
569 /* Return when this key has not expired */
570 if (time(NULL
) <= when
) return 0;
573 server
.stat_expiredkeys
++;
574 propagateExpire(db
,key
);
575 return dbDelete(db
,key
);
578 /*-----------------------------------------------------------------------------
580 *----------------------------------------------------------------------------*/
582 void expireGenericCommand(redisClient
*c
, robj
*key
, robj
*param
, long offset
) {
586 if (getLongFromObjectOrReply(c
, param
, &seconds
, NULL
) != REDIS_OK
) return;
590 de
= dictFind(c
->db
->dict
,key
->ptr
);
592 addReply(c
,shared
.czero
);
596 if (dbDelete(c
->db
,key
)) server
.dirty
++;
597 addReply(c
, shared
.cone
);
598 signalModifiedKey(c
->db
,key
);
601 time_t when
= time(NULL
)+seconds
;
602 setExpire(c
->db
,key
,when
);
603 addReply(c
,shared
.cone
);
604 signalModifiedKey(c
->db
,key
);
610 void expireCommand(redisClient
*c
) {
611 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],0);
614 void expireatCommand(redisClient
*c
) {
615 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],time(NULL
));
618 void ttlCommand(redisClient
*c
) {
619 time_t expire
, ttl
= -1;
621 if (server
.ds_enabled
) lookupKeyRead(c
->db
,c
->argv
[1]);
622 expire
= getExpire(c
->db
,c
->argv
[1]);
624 ttl
= (expire
-time(NULL
));
625 if (ttl
< 0) ttl
= -1;
627 addReplyLongLong(c
,(long long)ttl
);
630 void persistCommand(redisClient
*c
) {
633 de
= dictFind(c
->db
->dict
,c
->argv
[1]->ptr
);
635 addReply(c
,shared
.czero
);
637 if (removeExpire(c
->db
,c
->argv
[1])) {
638 addReply(c
,shared
.cone
);
641 addReply(c
,shared
.czero
);
646 /* -----------------------------------------------------------------------------
647 * API to get key arguments from commands
648 * ---------------------------------------------------------------------------*/
650 int *getKeysUsingCommandTable(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
) {
651 int j
, i
= 0, last
, *keys
;
654 if (cmd
->firstkey
== 0) {
659 if (last
< 0) last
= argc
+last
;
660 keys
= zmalloc(sizeof(int)*((last
- cmd
->firstkey
)+1));
661 for (j
= cmd
->firstkey
; j
<= last
; j
+= cmd
->keystep
) {
662 redisAssert(j
< argc
);
669 int *getKeysFromCommand(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
670 if (cmd
->getkeys_proc
) {
671 return cmd
->getkeys_proc(cmd
,argv
,argc
,numkeys
,flags
);
673 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
677 void getKeysFreeResult(int *result
) {
681 int *noPreloadGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
682 if (flags
& REDIS_GETKEYS_PRELOAD
) {
686 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
690 int *renameGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
691 if (flags
& REDIS_GETKEYS_PRELOAD
) {
692 int *keys
= zmalloc(sizeof(int));
697 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
701 int *zunionInterGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
704 REDIS_NOTUSED(flags
);
706 num
= atoi(argv
[2]->ptr
);
707 /* Sanity check. Don't return any key if the command is going to
708 * reply with syntax error. */
709 if (num
> (argc
-3)) {
713 keys
= zmalloc(sizeof(int)*num
);
714 for (i
= 0; i
< num
; i
++) keys
[i
] = 3+i
;
719 /* Slot to Key API. This is used by Redis Cluster in order to obtain in
720 * a fast way a key that belongs to a specified hash slot. This is useful
721 * while rehashing the cluster. */
722 void SlotToKeyAdd(robj
*key
) {
723 unsigned int hashslot
= keyHashSlot(key
->ptr
,sdslen(key
->ptr
));
725 zslInsert(server
.cluster
.slots_to_keys
,hashslot
,key
);
729 void SlotToKeyDel(robj
*key
) {
730 unsigned int hashslot
= keyHashSlot(key
->ptr
,sdslen(key
->ptr
));
732 zslDelete(server
.cluster
.slots_to_keys
,hashslot
,key
);
735 unsigned int GetKeysInSlot(unsigned int hashslot
, robj
**keys
, unsigned int count
) {
740 range
.min
= range
.max
= hashslot
;
741 range
.minex
= range
.maxex
= 0;
743 n
= zslFirstInRange(server
.cluster
.slots_to_keys
, range
);
744 while(n
&& n
->score
== hashslot
&& count
--) {
746 n
= n
->level
[0].forward
;