]>
git.saurik.com Git - redis.git/blob - src/db.c
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
.rdb_child_pid
== -1 && server
.aof_child_pid
== -1)
44 val
->lru
= server
.lruclock
;
51 robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
54 expireIfNeeded(db
,key
);
55 val
= lookupKey(db
,key
);
57 server
.stat_keyspace_misses
++;
59 server
.stat_keyspace_hits
++;
63 robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
64 expireIfNeeded(db
,key
);
65 return lookupKey(db
,key
);
68 robj
*lookupKeyReadOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
69 robj
*o
= lookupKeyRead(c
->db
, key
);
70 if (!o
) addReply(c
,reply
);
74 robj
*lookupKeyWriteOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
75 robj
*o
= lookupKeyWrite(c
->db
, key
);
76 if (!o
) addReply(c
,reply
);
80 /* Add the key to the DB. It's up to the caller to increment the reference
81 * counte of the value if needed.
83 * The program is aborted if the key already exists. */
84 void dbAdd(redisDb
*db
, robj
*key
, robj
*val
) {
85 sds copy
= sdsdup(key
->ptr
);
86 int retval
= dictAdd(db
->dict
, copy
, val
);
88 redisAssertWithInfo(NULL
,key
,retval
== REDIS_OK
);
89 if (server
.cluster_enabled
) SlotToKeyAdd(key
);
92 /* Overwrite an existing key with a new value. Incrementing the reference
93 * count of the new value is up to the caller.
94 * This function does not modify the expire time of the existing key.
96 * The program is aborted if the key was not already present. */
97 void dbOverwrite(redisDb
*db
, robj
*key
, robj
*val
) {
98 struct dictEntry
*de
= dictFind(db
->dict
,key
->ptr
);
100 redisAssertWithInfo(NULL
,key
,de
!= NULL
);
101 dictReplace(db
->dict
, key
->ptr
, val
);
104 /* High level Set operation. This function can be used in order to set
105 * a key, whatever it was existing or not, to a new object.
107 * 1) The ref count of the value object is incremented.
108 * 2) clients WATCHing for the destination key notified.
109 * 3) The expire time of the key is reset (the key is made persistent). */
110 void setKey(redisDb
*db
, robj
*key
, robj
*val
) {
111 if (lookupKeyWrite(db
,key
) == NULL
) {
114 dbOverwrite(db
,key
,val
);
117 removeExpire(db
,key
);
118 signalModifiedKey(db
,key
);
121 int dbExists(redisDb
*db
, robj
*key
) {
122 return dictFind(db
->dict
,key
->ptr
) != NULL
;
125 /* Return a random key, in form of a Redis object.
126 * If there are no keys, NULL is returned.
128 * The function makes sure to return keys not already expired. */
129 robj
*dbRandomKey(redisDb
*db
) {
130 struct dictEntry
*de
;
136 de
= dictGetRandomKey(db
->dict
);
137 if (de
== NULL
) return NULL
;
139 key
= dictGetKey(de
);
140 keyobj
= createStringObject(key
,sdslen(key
));
141 if (dictFind(db
->expires
,key
)) {
142 if (expireIfNeeded(db
,keyobj
)) {
143 decrRefCount(keyobj
);
144 continue; /* search for another key. This expired. */
151 /* Delete a key, value, and associated expiration entry if any, from the DB */
152 int dbDelete(redisDb
*db
, robj
*key
) {
153 /* Deleting an entry from the expires dict will not free the sds of
154 * the key, because it is shared with the main dictionary. */
155 if (dictSize(db
->expires
) > 0) dictDelete(db
->expires
,key
->ptr
);
156 if (dictDelete(db
->dict
,key
->ptr
) == DICT_OK
) {
157 if (server
.cluster_enabled
) SlotToKeyDel(key
);
164 /* Empty the whole database.
165 * If diskstore is enabled this function will just flush the in-memory cache. */
166 long long emptyDb() {
168 long long removed
= 0;
170 for (j
= 0; j
< server
.dbnum
; j
++) {
171 removed
+= dictSize(server
.db
[j
].dict
);
172 dictEmpty(server
.db
[j
].dict
);
173 dictEmpty(server
.db
[j
].expires
);
178 int selectDb(redisClient
*c
, int id
) {
179 if (id
< 0 || id
>= server
.dbnum
)
181 c
->db
= &server
.db
[id
];
185 /*-----------------------------------------------------------------------------
186 * Hooks for key space changes.
188 * Every time a key in the database is modified the function
189 * signalModifiedKey() is called.
191 * Every time a DB is flushed the function signalFlushDb() is called.
192 *----------------------------------------------------------------------------*/
194 void signalModifiedKey(redisDb
*db
, robj
*key
) {
195 touchWatchedKey(db
,key
);
198 void signalFlushedDb(int dbid
) {
199 touchWatchedKeysOnFlush(dbid
);
202 /*-----------------------------------------------------------------------------
203 * Type agnostic commands operating on the key space
204 *----------------------------------------------------------------------------*/
206 void flushdbCommand(redisClient
*c
) {
207 server
.dirty
+= dictSize(c
->db
->dict
);
208 signalFlushedDb(c
->db
->id
);
209 dictEmpty(c
->db
->dict
);
210 dictEmpty(c
->db
->expires
);
211 addReply(c
,shared
.ok
);
214 void flushallCommand(redisClient
*c
) {
216 server
.dirty
+= emptyDb();
217 addReply(c
,shared
.ok
);
218 if (server
.rdb_child_pid
!= -1) {
219 kill(server
.rdb_child_pid
,SIGKILL
);
220 rdbRemoveTempFile(server
.rdb_child_pid
);
222 if (server
.saveparamslen
> 0) {
223 /* Normally rdbSave() will reset dirty, but we don't want this here
224 * as otherwise FLUSHALL will not be replicated nor put into the AOF. */
225 int saved_dirty
= server
.dirty
;
226 rdbSave(server
.rdb_filename
);
227 server
.dirty
= saved_dirty
;
232 void delCommand(redisClient
*c
) {
235 for (j
= 1; j
< c
->argc
; j
++) {
236 if (dbDelete(c
->db
,c
->argv
[j
])) {
237 signalModifiedKey(c
->db
,c
->argv
[j
]);
242 addReplyLongLong(c
,deleted
);
245 void existsCommand(redisClient
*c
) {
246 expireIfNeeded(c
->db
,c
->argv
[1]);
247 if (dbExists(c
->db
,c
->argv
[1])) {
248 addReply(c
, shared
.cone
);
250 addReply(c
, shared
.czero
);
254 void selectCommand(redisClient
*c
) {
255 int id
= atoi(c
->argv
[1]->ptr
);
257 if (server
.cluster_enabled
&& id
!= 0) {
258 addReplyError(c
,"SELECT is not allowed in cluster mode");
261 if (selectDb(c
,id
) == REDIS_ERR
) {
262 addReplyError(c
,"invalid DB index");
264 addReply(c
,shared
.ok
);
268 void randomkeyCommand(redisClient
*c
) {
271 if ((key
= dbRandomKey(c
->db
)) == NULL
) {
272 addReply(c
,shared
.nullbulk
);
280 void keysCommand(redisClient
*c
) {
283 sds pattern
= c
->argv
[1]->ptr
;
284 int plen
= sdslen(pattern
), allkeys
;
285 unsigned long numkeys
= 0;
286 void *replylen
= addDeferredMultiBulkLength(c
);
288 di
= dictGetIterator(c
->db
->dict
);
289 allkeys
= (pattern
[0] == '*' && pattern
[1] == '\0');
290 while((de
= dictNext(di
)) != NULL
) {
291 sds key
= dictGetKey(de
);
294 if (allkeys
|| stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
295 keyobj
= createStringObject(key
,sdslen(key
));
296 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
297 addReplyBulk(c
,keyobj
);
300 decrRefCount(keyobj
);
303 dictReleaseIterator(di
);
304 setDeferredMultiBulkLength(c
,replylen
,numkeys
);
307 void dbsizeCommand(redisClient
*c
) {
308 addReplyLongLong(c
,dictSize(c
->db
->dict
));
311 void lastsaveCommand(redisClient
*c
) {
312 addReplyLongLong(c
,server
.lastsave
);
315 void typeCommand(redisClient
*c
) {
319 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
324 case REDIS_STRING
: type
= "string"; break;
325 case REDIS_LIST
: type
= "list"; break;
326 case REDIS_SET
: type
= "set"; break;
327 case REDIS_ZSET
: type
= "zset"; break;
328 case REDIS_HASH
: type
= "hash"; break;
329 default: type
= "unknown"; break;
332 addReplyStatus(c
,type
);
335 void shutdownCommand(redisClient
*c
) {
339 addReply(c
,shared
.syntaxerr
);
341 } else if (c
->argc
== 2) {
342 if (!strcasecmp(c
->argv
[1]->ptr
,"nosave")) {
343 flags
|= REDIS_SHUTDOWN_NOSAVE
;
344 } else if (!strcasecmp(c
->argv
[1]->ptr
,"save")) {
345 flags
|= REDIS_SHUTDOWN_SAVE
;
347 addReply(c
,shared
.syntaxerr
);
351 if (prepareForShutdown(flags
) == REDIS_OK
) exit(0);
352 addReplyError(c
,"Errors trying to SHUTDOWN. Check logs.");
355 void renameGenericCommand(redisClient
*c
, int nx
) {
359 /* To use the same key as src and dst is probably an error */
360 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
361 addReply(c
,shared
.sameobjecterr
);
365 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
)
369 expire
= getExpire(c
->db
,c
->argv
[1]);
370 if (lookupKeyWrite(c
->db
,c
->argv
[2]) != NULL
) {
373 addReply(c
,shared
.czero
);
376 /* Overwrite: delete the old key before creating the new one with the same name. */
377 dbDelete(c
->db
,c
->argv
[2]);
379 dbAdd(c
->db
,c
->argv
[2],o
);
380 if (expire
!= -1) setExpire(c
->db
,c
->argv
[2],expire
);
381 dbDelete(c
->db
,c
->argv
[1]);
382 signalModifiedKey(c
->db
,c
->argv
[1]);
383 signalModifiedKey(c
->db
,c
->argv
[2]);
385 addReply(c
,nx
? shared
.cone
: shared
.ok
);
388 void renameCommand(redisClient
*c
) {
389 renameGenericCommand(c
,0);
392 void renamenxCommand(redisClient
*c
) {
393 renameGenericCommand(c
,1);
396 void moveCommand(redisClient
*c
) {
401 if (server
.cluster_enabled
) {
402 addReplyError(c
,"MOVE is not allowed in cluster mode");
406 /* Obtain source and target DB pointers */
409 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
410 addReply(c
,shared
.outofrangeerr
);
414 selectDb(c
,srcid
); /* Back to the source DB */
416 /* If the user is moving using as target the same
417 * DB as the source DB it is probably an error. */
419 addReply(c
,shared
.sameobjecterr
);
423 /* Check if the element exists and get a reference */
424 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
426 addReply(c
,shared
.czero
);
430 /* Return zero if the key already exists in the target DB */
431 if (lookupKeyWrite(dst
,c
->argv
[1]) != NULL
) {
432 addReply(c
,shared
.czero
);
435 dbAdd(dst
,c
->argv
[1],o
);
438 /* OK! key moved, free the entry in the source DB */
439 dbDelete(src
,c
->argv
[1]);
441 addReply(c
,shared
.cone
);
444 /*-----------------------------------------------------------------------------
446 *----------------------------------------------------------------------------*/
448 int removeExpire(redisDb
*db
, robj
*key
) {
449 /* An expire may only be removed if there is a corresponding entry in the
450 * main dict. Otherwise, the key will never be freed. */
451 redisAssertWithInfo(NULL
,key
,dictFind(db
->dict
,key
->ptr
) != NULL
);
452 return dictDelete(db
->expires
,key
->ptr
) == DICT_OK
;
455 void setExpire(redisDb
*db
, robj
*key
, long long when
) {
458 /* Reuse the sds from the main dict in the expire dict */
459 kde
= dictFind(db
->dict
,key
->ptr
);
460 redisAssertWithInfo(NULL
,key
,kde
!= NULL
);
461 de
= dictReplaceRaw(db
->expires
,dictGetKey(kde
));
462 dictSetSignedIntegerVal(de
,when
);
465 /* Return the expire time of the specified key, or -1 if no expire
466 * is associated with this key (i.e. the key is non volatile) */
467 long long getExpire(redisDb
*db
, robj
*key
) {
470 /* No expire? return ASAP */
471 if (dictSize(db
->expires
) == 0 ||
472 (de
= dictFind(db
->expires
,key
->ptr
)) == NULL
) return -1;
474 /* The entry was found in the expire dict, this means it should also
475 * be present in the main dict (safety check). */
476 redisAssertWithInfo(NULL
,key
,dictFind(db
->dict
,key
->ptr
) != NULL
);
477 return dictGetSignedIntegerVal(de
);
480 /* Propagate expires into slaves and the AOF file.
481 * When a key expires in the master, a DEL operation for this key is sent
482 * to all the slaves and the AOF file if enabled.
484 * This way the key expiry is centralized in one place, and since both
485 * AOF and the master->slave link guarantee operation ordering, everything
486 * will be consistent even if we allow write operations against expiring
488 void propagateExpire(redisDb
*db
, robj
*key
) {
491 argv
[0] = createStringObject("DEL",3);
495 if (server
.aof_state
!= REDIS_AOF_OFF
)
496 feedAppendOnlyFile(server
.delCommand
,db
->id
,argv
,2);
497 if (listLength(server
.slaves
))
498 replicationFeedSlaves(server
.slaves
,db
->id
,argv
,2);
500 decrRefCount(argv
[0]);
501 decrRefCount(argv
[1]);
504 int expireIfNeeded(redisDb
*db
, robj
*key
) {
505 long long when
= getExpire(db
,key
);
507 if (when
< 0) return 0; /* No expire for this key */
509 /* Don't expire anything while loading. It will be done later. */
510 if (server
.loading
) return 0;
512 /* If we are running in the context of a slave, return ASAP:
513 * the slave key expiration is controlled by the master that will
514 * send us synthesized DEL operations for expired keys.
516 * Still we try to return the right information to the caller,
517 * that is, 0 if we think the key should be still valid, 1 if
518 * we think the key is expired at this time. */
519 if (server
.masterhost
!= NULL
) {
520 return time(NULL
) > when
;
523 /* Return when this key has not expired */
524 if (mstime() <= when
) return 0;
527 server
.stat_expiredkeys
++;
528 propagateExpire(db
,key
);
529 return dbDelete(db
,key
);
532 /*-----------------------------------------------------------------------------
534 *----------------------------------------------------------------------------*/
536 /* Given an string object return true if it contains exactly the "ms"
537 * or "MS" string. This is used in order to check if the last argument
538 * of EXPIRE, EXPIREAT or TTL is "ms" to switch into millisecond input/output */
539 int stringObjectEqualsMs(robj
*a
) {
541 return tolower(arg
[0]) == 'm' && tolower(arg
[1]) == 's' && arg
[2] == '\0';
544 void expireGenericCommand(redisClient
*c
, long long offset
, int unit
) {
546 robj
*key
= c
->argv
[1], *param
= c
->argv
[2];
547 long long milliseconds
;
549 if (getLongLongFromObjectOrReply(c
, param
, &milliseconds
, NULL
) != REDIS_OK
)
552 if (unit
== UNIT_SECONDS
) milliseconds
*= 1000;
553 milliseconds
-= offset
;
555 de
= dictFind(c
->db
->dict
,key
->ptr
);
557 addReply(c
,shared
.czero
);
560 /* EXPIRE with negative TTL, or EXPIREAT with a timestamp into the past
561 * should never be executed as a DEL when load the AOF or in the context
562 * of a slave instance.
564 * Instead we take the other branch of the IF statement setting an expire
565 * (possibly in the past) and wait for an explicit DEL from the master. */
566 if (milliseconds
<= 0 && !server
.loading
&& !server
.masterhost
) {
569 redisAssertWithInfo(c
,key
,dbDelete(c
->db
,key
));
572 /* Replicate/AOF this as an explicit DEL. */
573 aux
= createStringObject("DEL",3);
574 rewriteClientCommandVector(c
,2,aux
,key
);
576 signalModifiedKey(c
->db
,key
);
577 addReply(c
, shared
.cone
);
580 long long when
= mstime()+milliseconds
;
581 setExpire(c
->db
,key
,when
);
582 addReply(c
,shared
.cone
);
583 signalModifiedKey(c
->db
,key
);
589 void expireCommand(redisClient
*c
) {
590 expireGenericCommand(c
,0,UNIT_SECONDS
);
593 void expireatCommand(redisClient
*c
) {
594 expireGenericCommand(c
,mstime(),UNIT_SECONDS
);
597 void pexpireCommand(redisClient
*c
) {
598 expireGenericCommand(c
,0,UNIT_MILLISECONDS
);
601 void pexpireatCommand(redisClient
*c
) {
602 expireGenericCommand(c
,mstime(),UNIT_MILLISECONDS
);
605 void ttlGenericCommand(redisClient
*c
, int output_ms
) {
606 long long expire
, ttl
= -1;
608 expire
= getExpire(c
->db
,c
->argv
[1]);
610 ttl
= expire
-mstime();
611 if (ttl
< 0) ttl
= -1;
614 addReplyLongLong(c
,-1);
616 addReplyLongLong(c
,output_ms
? ttl
: ((ttl
+500)/1000));
620 void ttlCommand(redisClient
*c
) {
621 ttlGenericCommand(c
, 0);
624 void pttlCommand(redisClient
*c
) {
625 ttlGenericCommand(c
, 1);
628 void persistCommand(redisClient
*c
) {
631 de
= dictFind(c
->db
->dict
,c
->argv
[1]->ptr
);
633 addReply(c
,shared
.czero
);
635 if (removeExpire(c
->db
,c
->argv
[1])) {
636 addReply(c
,shared
.cone
);
639 addReply(c
,shared
.czero
);
644 /* -----------------------------------------------------------------------------
645 * API to get key arguments from commands
646 * ---------------------------------------------------------------------------*/
648 int *getKeysUsingCommandTable(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
) {
649 int j
, i
= 0, last
, *keys
;
652 if (cmd
->firstkey
== 0) {
657 if (last
< 0) last
= argc
+last
;
658 keys
= zmalloc(sizeof(int)*((last
- cmd
->firstkey
)+1));
659 for (j
= cmd
->firstkey
; j
<= last
; j
+= cmd
->keystep
) {
660 redisAssert(j
< argc
);
667 int *getKeysFromCommand(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
668 if (cmd
->getkeys_proc
) {
669 return cmd
->getkeys_proc(cmd
,argv
,argc
,numkeys
,flags
);
671 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
675 void getKeysFreeResult(int *result
) {
679 int *noPreloadGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
680 if (flags
& REDIS_GETKEYS_PRELOAD
) {
684 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
688 int *renameGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
689 if (flags
& REDIS_GETKEYS_PRELOAD
) {
690 int *keys
= zmalloc(sizeof(int));
695 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
699 int *zunionInterGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
702 REDIS_NOTUSED(flags
);
704 num
= atoi(argv
[2]->ptr
);
705 /* Sanity check. Don't return any key if the command is going to
706 * reply with syntax error. */
707 if (num
> (argc
-3)) {
711 keys
= zmalloc(sizeof(int)*num
);
712 for (i
= 0; i
< num
; i
++) keys
[i
] = 3+i
;
717 /* Slot to Key API. This is used by Redis Cluster in order to obtain in
718 * a fast way a key that belongs to a specified hash slot. This is useful
719 * while rehashing the cluster. */
720 void SlotToKeyAdd(robj
*key
) {
721 unsigned int hashslot
= keyHashSlot(key
->ptr
,sdslen(key
->ptr
));
723 zslInsert(server
.cluster
.slots_to_keys
,hashslot
,key
);
727 void SlotToKeyDel(robj
*key
) {
728 unsigned int hashslot
= keyHashSlot(key
->ptr
,sdslen(key
->ptr
));
730 zslDelete(server
.cluster
.slots_to_keys
,hashslot
,key
);
733 unsigned int GetKeysInSlot(unsigned int hashslot
, robj
**keys
, unsigned int count
) {
738 range
.min
= range
.max
= hashslot
;
739 range
.minex
= range
.maxex
= 0;
741 n
= zslFirstInRange(server
.cluster
.slots_to_keys
, range
);
742 while(n
&& n
->score
== hashslot
&& count
--) {
744 n
= n
->level
[0].forward
;