]>
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
);
89 int retval
= dbAdd(db
,key
,val
);
90 redisAssert(retval
== REDIS_OK
);
91 if (expire
!= -1) setExpire(db
,key
,expire
);
92 server
.stat_keyspace_hits
++;
95 cacheSetKeyDoesNotExist(db
,key
);
98 server
.stat_keyspace_misses
++;
103 robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
104 expireIfNeeded(db
,key
);
105 return lookupKey(db
,key
);
108 robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
109 expireIfNeeded(db
,key
);
110 return lookupKey(db
,key
);
113 robj
*lookupKeyReadOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
114 robj
*o
= lookupKeyRead(c
->db
, key
);
115 if (!o
) addReply(c
,reply
);
119 robj
*lookupKeyWriteOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
120 robj
*o
= lookupKeyWrite(c
->db
, key
);
121 if (!o
) addReply(c
,reply
);
125 /* Add the key to the DB. If the key already exists REDIS_ERR is returned,
126 * otherwise REDIS_OK is returned, and the caller should increment the
127 * refcount of 'val'. */
128 int dbAdd(redisDb
*db
, robj
*key
, robj
*val
) {
129 /* Perform a lookup before adding the key, as we need to copy the
131 if (dictFind(db
->dict
, key
->ptr
) != NULL
) {
134 sds copy
= sdsdup(key
->ptr
);
135 dictAdd(db
->dict
, copy
, val
);
136 if (server
.ds_enabled
) cacheSetKeyMayExist(db
,key
);
137 if (server
.cluster_enabled
) SlotToKeyAdd(key
);
142 /* If the key does not exist, this is just like dbAdd(). Otherwise
143 * the value associated to the key is replaced with the new one.
145 * On update (key already existed) 0 is returned. Otherwise 1. */
146 int dbReplace(redisDb
*db
, robj
*key
, robj
*val
) {
150 if ((oldval
= dictFetchValue(db
->dict
,key
->ptr
)) == NULL
) {
151 sds copy
= sdsdup(key
->ptr
);
152 dictAdd(db
->dict
, copy
, val
);
153 if (server
.cluster_enabled
) SlotToKeyAdd(key
);
156 dictReplace(db
->dict
, key
->ptr
, val
);
159 if (server
.ds_enabled
) cacheSetKeyMayExist(db
,key
);
163 int dbExists(redisDb
*db
, robj
*key
) {
164 return dictFind(db
->dict
,key
->ptr
) != NULL
;
167 /* Return a random key, in form of a Redis object.
168 * If there are no keys, NULL is returned.
170 * The function makes sure to return keys not already expired. */
171 robj
*dbRandomKey(redisDb
*db
) {
172 struct dictEntry
*de
;
178 de
= dictGetRandomKey(db
->dict
);
179 if (de
== NULL
) return NULL
;
181 key
= dictGetEntryKey(de
);
182 keyobj
= createStringObject(key
,sdslen(key
));
183 if (dictFind(db
->expires
,key
)) {
184 if (expireIfNeeded(db
,keyobj
)) {
185 decrRefCount(keyobj
);
186 continue; /* search for another key. This expired. */
193 /* Delete a key, value, and associated expiration entry if any, from the DB */
194 int dbDelete(redisDb
*db
, robj
*key
) {
195 /* If diskstore is enabled make sure to awake waiting clients for this key
196 * as it is not really useful to wait for a key already deleted to be
197 * loaded from disk. */
198 if (server
.ds_enabled
) {
199 handleClientsBlockedOnSwappedKey(db
,key
);
200 cacheSetKeyDoesNotExist(db
,key
);
203 /* Deleting an entry from the expires dict will not free the sds of
204 * the key, because it is shared with the main dictionary. */
205 if (dictSize(db
->expires
) > 0) dictDelete(db
->expires
,key
->ptr
);
206 if (dictDelete(db
->dict
,key
->ptr
) == DICT_OK
) {
207 if (server
.cluster_enabled
) SlotToKeyDel(key
);
214 /* Empty the whole database.
215 * If diskstore is enabled this function will just flush the in-memory cache. */
216 long long emptyDb() {
218 long long removed
= 0;
220 for (j
= 0; j
< server
.dbnum
; j
++) {
221 removed
+= dictSize(server
.db
[j
].dict
);
222 dictEmpty(server
.db
[j
].dict
);
223 dictEmpty(server
.db
[j
].expires
);
224 if (server
.ds_enabled
) dictEmpty(server
.db
[j
].io_negcache
);
229 int selectDb(redisClient
*c
, int id
) {
230 if (id
< 0 || id
>= server
.dbnum
)
232 c
->db
= &server
.db
[id
];
236 /*-----------------------------------------------------------------------------
237 * Hooks for key space changes.
239 * Every time a key in the database is modified the function
240 * signalModifiedKey() is called.
242 * Every time a DB is flushed the function signalFlushDb() is called.
243 *----------------------------------------------------------------------------*/
245 void signalModifiedKey(redisDb
*db
, robj
*key
) {
246 touchWatchedKey(db
,key
);
247 if (server
.ds_enabled
)
248 cacheScheduleIO(db
,key
,REDIS_IO_SAVE
);
251 void signalFlushedDb(int dbid
) {
252 touchWatchedKeysOnFlush(dbid
);
255 /*-----------------------------------------------------------------------------
256 * Type agnostic commands operating on the key space
257 *----------------------------------------------------------------------------*/
259 void flushdbCommand(redisClient
*c
) {
260 server
.dirty
+= dictSize(c
->db
->dict
);
261 signalFlushedDb(c
->db
->id
);
262 dictEmpty(c
->db
->dict
);
263 dictEmpty(c
->db
->expires
);
264 if (server
.ds_enabled
) dsFlushDb(c
->db
->id
);
265 addReply(c
,shared
.ok
);
268 void flushallCommand(redisClient
*c
) {
270 server
.dirty
+= emptyDb();
271 addReply(c
,shared
.ok
);
272 if (server
.bgsavechildpid
!= -1) {
273 kill(server
.bgsavechildpid
,SIGKILL
);
274 rdbRemoveTempFile(server
.bgsavechildpid
);
276 if (server
.ds_enabled
)
279 rdbSave(server
.dbfilename
);
283 void delCommand(redisClient
*c
) {
286 for (j
= 1; j
< c
->argc
; j
++) {
287 if (server
.ds_enabled
) {
288 lookupKeyRead(c
->db
,c
->argv
[j
]);
289 /* FIXME: this can be optimized a lot, no real need to load
290 * a possibly huge value. */
292 if (dbDelete(c
->db
,c
->argv
[j
])) {
293 signalModifiedKey(c
->db
,c
->argv
[j
]);
296 } else if (server
.ds_enabled
) {
297 if (cacheKeyMayExist(c
->db
,c
->argv
[j
]) &&
298 dsExists(c
->db
,c
->argv
[j
]))
300 cacheScheduleIO(c
->db
,c
->argv
[j
],REDIS_IO_SAVE
);
305 addReplyLongLong(c
,deleted
);
308 void existsCommand(redisClient
*c
) {
309 expireIfNeeded(c
->db
,c
->argv
[1]);
310 if (dbExists(c
->db
,c
->argv
[1])) {
311 addReply(c
, shared
.cone
);
313 addReply(c
, shared
.czero
);
317 void selectCommand(redisClient
*c
) {
318 int id
= atoi(c
->argv
[1]->ptr
);
320 if (server
.cluster_enabled
) {
321 addReplyError(c
,"SELECT is not allowed in cluster mode");
324 if (selectDb(c
,id
) == REDIS_ERR
) {
325 addReplyError(c
,"invalid DB index");
327 addReply(c
,shared
.ok
);
331 void randomkeyCommand(redisClient
*c
) {
334 if ((key
= dbRandomKey(c
->db
)) == NULL
) {
335 addReply(c
,shared
.nullbulk
);
343 void keysCommand(redisClient
*c
) {
346 sds pattern
= c
->argv
[1]->ptr
;
347 int plen
= sdslen(pattern
), allkeys
;
348 unsigned long numkeys
= 0;
349 void *replylen
= addDeferredMultiBulkLength(c
);
351 di
= dictGetIterator(c
->db
->dict
);
352 allkeys
= (pattern
[0] == '*' && pattern
[1] == '\0');
353 while((de
= dictNext(di
)) != NULL
) {
354 sds key
= dictGetEntryKey(de
);
357 if (allkeys
|| stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
358 keyobj
= createStringObject(key
,sdslen(key
));
359 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
360 addReplyBulk(c
,keyobj
);
363 decrRefCount(keyobj
);
366 dictReleaseIterator(di
);
367 setDeferredMultiBulkLength(c
,replylen
,numkeys
);
370 void dbsizeCommand(redisClient
*c
) {
371 addReplyLongLong(c
,dictSize(c
->db
->dict
));
374 void lastsaveCommand(redisClient
*c
) {
375 addReplyLongLong(c
,server
.lastsave
);
378 void typeCommand(redisClient
*c
) {
382 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
387 case REDIS_STRING
: type
= "string"; break;
388 case REDIS_LIST
: type
= "list"; break;
389 case REDIS_SET
: type
= "set"; break;
390 case REDIS_ZSET
: type
= "zset"; break;
391 case REDIS_HASH
: type
= "hash"; break;
392 default: type
= "unknown"; break;
395 addReplyStatus(c
,type
);
398 void shutdownCommand(redisClient
*c
) {
399 if (prepareForShutdown() == REDIS_OK
)
401 addReplyError(c
,"Errors trying to SHUTDOWN. Check logs.");
404 void renameGenericCommand(redisClient
*c
, int nx
) {
407 /* To use the same key as src and dst is probably an error */
408 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
409 addReply(c
,shared
.sameobjecterr
);
413 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
)
417 if (dbAdd(c
->db
,c
->argv
[2],o
) == REDIS_ERR
) {
420 addReply(c
,shared
.czero
);
423 dbReplace(c
->db
,c
->argv
[2],o
);
425 dbDelete(c
->db
,c
->argv
[1]);
426 signalModifiedKey(c
->db
,c
->argv
[1]);
427 signalModifiedKey(c
->db
,c
->argv
[2]);
429 addReply(c
,nx
? shared
.cone
: shared
.ok
);
432 void renameCommand(redisClient
*c
) {
433 renameGenericCommand(c
,0);
436 void renamenxCommand(redisClient
*c
) {
437 renameGenericCommand(c
,1);
440 void moveCommand(redisClient
*c
) {
445 if (server
.cluster_enabled
) {
446 addReplyError(c
,"MOVE is not allowed in cluster mode");
450 /* Obtain source and target DB pointers */
453 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
454 addReply(c
,shared
.outofrangeerr
);
458 selectDb(c
,srcid
); /* Back to the source DB */
460 /* If the user is moving using as target the same
461 * DB as the source DB it is probably an error. */
463 addReply(c
,shared
.sameobjecterr
);
467 /* Check if the element exists and get a reference */
468 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
470 addReply(c
,shared
.czero
);
474 /* Try to add the element to the target DB */
475 if (dbAdd(dst
,c
->argv
[1],o
) == REDIS_ERR
) {
476 addReply(c
,shared
.czero
);
481 /* OK! key moved, free the entry in the source DB */
482 dbDelete(src
,c
->argv
[1]);
484 addReply(c
,shared
.cone
);
487 /*-----------------------------------------------------------------------------
489 *----------------------------------------------------------------------------*/
491 int removeExpire(redisDb
*db
, robj
*key
) {
492 /* An expire may only be removed if there is a corresponding entry in the
493 * main dict. Otherwise, the key will never be freed. */
494 redisAssert(dictFind(db
->dict
,key
->ptr
) != NULL
);
495 return dictDelete(db
->expires
,key
->ptr
) == DICT_OK
;
498 void setExpire(redisDb
*db
, robj
*key
, time_t when
) {
501 /* Reuse the sds from the main dict in the expire dict */
502 de
= dictFind(db
->dict
,key
->ptr
);
503 redisAssert(de
!= NULL
);
504 dictReplace(db
->expires
,dictGetEntryKey(de
),(void*)when
);
507 /* Return the expire time of the specified key, or -1 if no expire
508 * is associated with this key (i.e. the key is non volatile) */
509 time_t getExpire(redisDb
*db
, robj
*key
) {
512 /* No expire? return ASAP */
513 if (dictSize(db
->expires
) == 0 ||
514 (de
= dictFind(db
->expires
,key
->ptr
)) == NULL
) return -1;
516 /* The entry was found in the expire dict, this means it should also
517 * be present in the main dict (safety check). */
518 redisAssert(dictFind(db
->dict
,key
->ptr
) != NULL
);
519 return (time_t) dictGetEntryVal(de
);
522 /* Propagate expires into slaves and the AOF file.
523 * When a key expires in the master, a DEL operation for this key is sent
524 * to all the slaves and the AOF file if enabled.
526 * This way the key expiry is centralized in one place, and since both
527 * AOF and the master->slave link guarantee operation ordering, everything
528 * will be consistent even if we allow write operations against expiring
530 void propagateExpire(redisDb
*db
, robj
*key
) {
533 argv
[0] = createStringObject("DEL",3);
537 if (server
.appendonly
)
538 feedAppendOnlyFile(server
.delCommand
,db
->id
,argv
,2);
539 if (listLength(server
.slaves
))
540 replicationFeedSlaves(server
.slaves
,db
->id
,argv
,2);
542 decrRefCount(argv
[0]);
543 decrRefCount(argv
[1]);
546 int expireIfNeeded(redisDb
*db
, robj
*key
) {
547 time_t when
= getExpire(db
,key
);
549 if (when
< 0) return 0; /* No expire for this key */
551 /* If we are running in the context of a slave, return ASAP:
552 * the slave key expiration is controlled by the master that will
553 * send us synthesized DEL operations for expired keys.
555 * Still we try to return the right information to the caller,
556 * that is, 0 if we think the key should be still valid, 1 if
557 * we think the key is expired at this time. */
558 if (server
.masterhost
!= NULL
) {
559 return time(NULL
) > when
;
562 /* Return when this key has not expired */
563 if (time(NULL
) <= when
) return 0;
566 server
.stat_expiredkeys
++;
567 propagateExpire(db
,key
);
568 return dbDelete(db
,key
);
571 /*-----------------------------------------------------------------------------
573 *----------------------------------------------------------------------------*/
575 void expireGenericCommand(redisClient
*c
, robj
*key
, robj
*param
, long offset
) {
579 if (getLongFromObjectOrReply(c
, param
, &seconds
, NULL
) != REDIS_OK
) return;
583 de
= dictFind(c
->db
->dict
,key
->ptr
);
585 addReply(c
,shared
.czero
);
589 if (dbDelete(c
->db
,key
)) server
.dirty
++;
590 addReply(c
, shared
.cone
);
591 signalModifiedKey(c
->db
,key
);
594 time_t when
= time(NULL
)+seconds
;
595 setExpire(c
->db
,key
,when
);
596 addReply(c
,shared
.cone
);
597 signalModifiedKey(c
->db
,key
);
603 void expireCommand(redisClient
*c
) {
604 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],0);
607 void expireatCommand(redisClient
*c
) {
608 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],time(NULL
));
611 void ttlCommand(redisClient
*c
) {
612 time_t expire
, ttl
= -1;
614 if (server
.ds_enabled
) lookupKeyRead(c
->db
,c
->argv
[1]);
615 expire
= getExpire(c
->db
,c
->argv
[1]);
617 ttl
= (expire
-time(NULL
));
618 if (ttl
< 0) ttl
= -1;
620 addReplyLongLong(c
,(long long)ttl
);
623 void persistCommand(redisClient
*c
) {
626 de
= dictFind(c
->db
->dict
,c
->argv
[1]->ptr
);
628 addReply(c
,shared
.czero
);
630 if (removeExpire(c
->db
,c
->argv
[1])) {
631 addReply(c
,shared
.cone
);
634 addReply(c
,shared
.czero
);
639 /* -----------------------------------------------------------------------------
640 * API to get key arguments from commands
641 * ---------------------------------------------------------------------------*/
643 int *getKeysUsingCommandTable(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
) {
644 int j
, i
= 0, last
, *keys
;
647 if (cmd
->firstkey
== 0) {
652 if (last
< 0) last
= argc
+last
;
653 keys
= zmalloc(sizeof(int)*((last
- cmd
->firstkey
)+1));
654 for (j
= cmd
->firstkey
; j
<= last
; j
+= cmd
->keystep
) {
655 redisAssert(j
< argc
);
662 int *getKeysFromCommand(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
663 if (cmd
->getkeys_proc
) {
664 return cmd
->getkeys_proc(cmd
,argv
,argc
,numkeys
,flags
);
666 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
670 void getKeysFreeResult(int *result
) {
674 int *noPreloadGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
675 if (flags
& REDIS_GETKEYS_PRELOAD
) {
679 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
683 int *renameGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
684 if (flags
& REDIS_GETKEYS_PRELOAD
) {
685 int *keys
= zmalloc(sizeof(int));
690 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
694 int *zunionInterGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
697 REDIS_NOTUSED(flags
);
699 num
= atoi(argv
[2]->ptr
);
700 /* Sanity check. Don't return any key if the command is going to
701 * reply with syntax error. */
702 if (num
> (argc
-3)) {
706 keys
= zmalloc(sizeof(int)*num
);
707 for (i
= 0; i
< num
; i
++) keys
[i
] = 3+i
;
712 /* Slot to Key API. This is used by Redis Cluster in order to obtain in
713 * a fast way a key that belongs to a specified hash slot. This is useful
714 * while rehashing the cluster. */
715 void SlotToKeyAdd(robj
*key
) {
716 unsigned int hashslot
= keyHashSlot(key
->ptr
,sdslen(key
->ptr
));
718 zslInsert(server
.cluster
.slots_to_keys
,hashslot
,key
);
722 void SlotToKeyDel(robj
*key
) {
723 unsigned int hashslot
= keyHashSlot(key
->ptr
,sdslen(key
->ptr
));
725 zslDelete(server
.cluster
.slots_to_keys
,hashslot
,key
);
728 unsigned int GetKeysInSlot(unsigned int hashslot
, robj
**keys
, unsigned int count
) {
733 range
.min
= range
.max
= hashslot
;
734 range
.minex
= range
.maxex
= 0;
736 n
= zslFirstInRange(server
.cluster
.slots_to_keys
, range
);
737 while(n
&& n
->score
== hashslot
&& count
--) {
739 n
= n
->level
[0].forward
;