]>
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
);
91 /* Overwrite an existing key with a new value. Incrementing the reference
92 * count of the new value is up to the caller.
93 * This function does not modify the expire time of the existing key.
95 * The program is aborted if the key was not already present. */
96 void dbOverwrite(redisDb
*db
, robj
*key
, robj
*val
) {
97 struct dictEntry
*de
= dictFind(db
->dict
,key
->ptr
);
99 redisAssertWithInfo(NULL
,key
,de
!= NULL
);
100 dictReplace(db
->dict
, key
->ptr
, val
);
103 /* High level Set operation. This function can be used in order to set
104 * a key, whatever it was existing or not, to a new object.
106 * 1) The ref count of the value object is incremented.
107 * 2) clients WATCHing for the destination key notified.
108 * 3) The expire time of the key is reset (the key is made persistent). */
109 void setKey(redisDb
*db
, robj
*key
, robj
*val
) {
110 if (lookupKeyWrite(db
,key
) == NULL
) {
113 dbOverwrite(db
,key
,val
);
116 removeExpire(db
,key
);
117 signalModifiedKey(db
,key
);
120 int dbExists(redisDb
*db
, robj
*key
) {
121 return dictFind(db
->dict
,key
->ptr
) != NULL
;
124 /* Return a random key, in form of a Redis object.
125 * If there are no keys, NULL is returned.
127 * The function makes sure to return keys not already expired. */
128 robj
*dbRandomKey(redisDb
*db
) {
129 struct dictEntry
*de
;
135 de
= dictGetRandomKey(db
->dict
);
136 if (de
== NULL
) return NULL
;
138 key
= dictGetKey(de
);
139 keyobj
= createStringObject(key
,sdslen(key
));
140 if (dictFind(db
->expires
,key
)) {
141 if (expireIfNeeded(db
,keyobj
)) {
142 decrRefCount(keyobj
);
143 continue; /* search for another key. This expired. */
150 /* Delete a key, value, and associated expiration entry if any, from the DB */
151 int dbDelete(redisDb
*db
, robj
*key
) {
152 /* Deleting an entry from the expires dict will not free the sds of
153 * the key, because it is shared with the main dictionary. */
154 if (dictSize(db
->expires
) > 0) dictDelete(db
->expires
,key
->ptr
);
155 if (dictDelete(db
->dict
,key
->ptr
) == DICT_OK
) {
162 /* Empty the whole database.
163 * If diskstore is enabled this function will just flush the in-memory cache. */
164 long long emptyDb() {
166 long long removed
= 0;
168 for (j
= 0; j
< server
.dbnum
; j
++) {
169 removed
+= dictSize(server
.db
[j
].dict
);
170 dictEmpty(server
.db
[j
].dict
);
171 dictEmpty(server
.db
[j
].expires
);
176 int selectDb(redisClient
*c
, int id
) {
177 if (id
< 0 || id
>= server
.dbnum
)
179 c
->db
= &server
.db
[id
];
183 /*-----------------------------------------------------------------------------
184 * Hooks for key space changes.
186 * Every time a key in the database is modified the function
187 * signalModifiedKey() is called.
189 * Every time a DB is flushed the function signalFlushDb() is called.
190 *----------------------------------------------------------------------------*/
192 void signalModifiedKey(redisDb
*db
, robj
*key
) {
193 touchWatchedKey(db
,key
);
196 void signalFlushedDb(int dbid
) {
197 touchWatchedKeysOnFlush(dbid
);
200 /*-----------------------------------------------------------------------------
201 * Type agnostic commands operating on the key space
202 *----------------------------------------------------------------------------*/
204 void flushdbCommand(redisClient
*c
) {
205 server
.dirty
+= dictSize(c
->db
->dict
);
206 signalFlushedDb(c
->db
->id
);
207 dictEmpty(c
->db
->dict
);
208 dictEmpty(c
->db
->expires
);
209 addReply(c
,shared
.ok
);
212 void flushallCommand(redisClient
*c
) {
214 server
.dirty
+= emptyDb();
215 addReply(c
,shared
.ok
);
216 if (server
.rdb_child_pid
!= -1) {
217 kill(server
.rdb_child_pid
,SIGKILL
);
218 rdbRemoveTempFile(server
.rdb_child_pid
);
220 if (server
.saveparamslen
> 0) {
221 /* Normally rdbSave() will reset dirty, but we don't want this here
222 * as otherwise FLUSHALL will not be replicated nor put into the AOF. */
223 int saved_dirty
= server
.dirty
;
224 rdbSave(server
.rdb_filename
);
225 server
.dirty
= saved_dirty
;
230 void delCommand(redisClient
*c
) {
233 for (j
= 1; j
< c
->argc
; j
++) {
234 if (dbDelete(c
->db
,c
->argv
[j
])) {
235 signalModifiedKey(c
->db
,c
->argv
[j
]);
240 addReplyLongLong(c
,deleted
);
243 void existsCommand(redisClient
*c
) {
244 expireIfNeeded(c
->db
,c
->argv
[1]);
245 if (dbExists(c
->db
,c
->argv
[1])) {
246 addReply(c
, shared
.cone
);
248 addReply(c
, shared
.czero
);
252 void selectCommand(redisClient
*c
) {
253 int id
= atoi(c
->argv
[1]->ptr
);
255 if (selectDb(c
,id
) == REDIS_ERR
) {
256 addReplyError(c
,"invalid DB index");
258 addReply(c
,shared
.ok
);
262 void randomkeyCommand(redisClient
*c
) {
265 if ((key
= dbRandomKey(c
->db
)) == NULL
) {
266 addReply(c
,shared
.nullbulk
);
274 void keysCommand(redisClient
*c
) {
277 sds pattern
= c
->argv
[1]->ptr
;
278 int plen
= sdslen(pattern
), allkeys
;
279 unsigned long numkeys
= 0;
280 void *replylen
= addDeferredMultiBulkLength(c
);
282 di
= dictGetIterator(c
->db
->dict
);
283 allkeys
= (pattern
[0] == '*' && pattern
[1] == '\0');
284 while((de
= dictNext(di
)) != NULL
) {
285 sds key
= dictGetKey(de
);
288 if (allkeys
|| stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
289 keyobj
= createStringObject(key
,sdslen(key
));
290 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
291 addReplyBulk(c
,keyobj
);
294 decrRefCount(keyobj
);
297 dictReleaseIterator(di
);
298 setDeferredMultiBulkLength(c
,replylen
,numkeys
);
301 void dbsizeCommand(redisClient
*c
) {
302 addReplyLongLong(c
,dictSize(c
->db
->dict
));
305 void lastsaveCommand(redisClient
*c
) {
306 addReplyLongLong(c
,server
.lastsave
);
309 void typeCommand(redisClient
*c
) {
313 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
318 case REDIS_STRING
: type
= "string"; break;
319 case REDIS_LIST
: type
= "list"; break;
320 case REDIS_SET
: type
= "set"; break;
321 case REDIS_ZSET
: type
= "zset"; break;
322 case REDIS_HASH
: type
= "hash"; break;
323 default: type
= "unknown"; break;
326 addReplyStatus(c
,type
);
329 void shutdownCommand(redisClient
*c
) {
333 addReply(c
,shared
.syntaxerr
);
335 } else if (c
->argc
== 2) {
336 if (!strcasecmp(c
->argv
[1]->ptr
,"nosave")) {
337 flags
|= REDIS_SHUTDOWN_NOSAVE
;
338 } else if (!strcasecmp(c
->argv
[1]->ptr
,"save")) {
339 flags
|= REDIS_SHUTDOWN_SAVE
;
341 addReply(c
,shared
.syntaxerr
);
345 if (prepareForShutdown(flags
) == REDIS_OK
) exit(0);
346 addReplyError(c
,"Errors trying to SHUTDOWN. Check logs.");
349 void renameGenericCommand(redisClient
*c
, int nx
) {
353 /* To use the same key as src and dst is probably an error */
354 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
355 addReply(c
,shared
.sameobjecterr
);
359 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
)
363 expire
= getExpire(c
->db
,c
->argv
[1]);
364 if (lookupKeyWrite(c
->db
,c
->argv
[2]) != NULL
) {
367 addReply(c
,shared
.czero
);
370 /* Overwrite: delete the old key before creating the new one with the same name. */
371 dbDelete(c
->db
,c
->argv
[2]);
373 dbAdd(c
->db
,c
->argv
[2],o
);
374 if (expire
!= -1) setExpire(c
->db
,c
->argv
[2],expire
);
375 dbDelete(c
->db
,c
->argv
[1]);
376 signalModifiedKey(c
->db
,c
->argv
[1]);
377 signalModifiedKey(c
->db
,c
->argv
[2]);
379 addReply(c
,nx
? shared
.cone
: shared
.ok
);
382 void renameCommand(redisClient
*c
) {
383 renameGenericCommand(c
,0);
386 void renamenxCommand(redisClient
*c
) {
387 renameGenericCommand(c
,1);
390 void moveCommand(redisClient
*c
) {
395 /* Obtain source and target DB pointers */
398 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
399 addReply(c
,shared
.outofrangeerr
);
403 selectDb(c
,srcid
); /* Back to the source DB */
405 /* If the user is moving using as target the same
406 * DB as the source DB it is probably an error. */
408 addReply(c
,shared
.sameobjecterr
);
412 /* Check if the element exists and get a reference */
413 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
415 addReply(c
,shared
.czero
);
419 /* Return zero if the key already exists in the target DB */
420 if (lookupKeyWrite(dst
,c
->argv
[1]) != NULL
) {
421 addReply(c
,shared
.czero
);
424 dbAdd(dst
,c
->argv
[1],o
);
427 /* OK! key moved, free the entry in the source DB */
428 dbDelete(src
,c
->argv
[1]);
430 addReply(c
,shared
.cone
);
433 /*-----------------------------------------------------------------------------
435 *----------------------------------------------------------------------------*/
437 int removeExpire(redisDb
*db
, robj
*key
) {
438 /* An expire may only be removed if there is a corresponding entry in the
439 * main dict. Otherwise, the key will never be freed. */
440 redisAssertWithInfo(NULL
,key
,dictFind(db
->dict
,key
->ptr
) != NULL
);
441 return dictDelete(db
->expires
,key
->ptr
) == DICT_OK
;
444 void setExpire(redisDb
*db
, robj
*key
, long long when
) {
447 /* Reuse the sds from the main dict in the expire dict */
448 kde
= dictFind(db
->dict
,key
->ptr
);
449 redisAssertWithInfo(NULL
,key
,kde
!= NULL
);
450 de
= dictReplaceRaw(db
->expires
,dictGetKey(kde
));
451 dictSetSignedIntegerVal(de
,when
);
454 /* Return the expire time of the specified key, or -1 if no expire
455 * is associated with this key (i.e. the key is non volatile) */
456 long long getExpire(redisDb
*db
, robj
*key
) {
459 /* No expire? return ASAP */
460 if (dictSize(db
->expires
) == 0 ||
461 (de
= dictFind(db
->expires
,key
->ptr
)) == NULL
) return -1;
463 /* The entry was found in the expire dict, this means it should also
464 * be present in the main dict (safety check). */
465 redisAssertWithInfo(NULL
,key
,dictFind(db
->dict
,key
->ptr
) != NULL
);
466 return dictGetSignedIntegerVal(de
);
469 /* Propagate expires into slaves and the AOF file.
470 * When a key expires in the master, a DEL operation for this key is sent
471 * to all the slaves and the AOF file if enabled.
473 * This way the key expiry is centralized in one place, and since both
474 * AOF and the master->slave link guarantee operation ordering, everything
475 * will be consistent even if we allow write operations against expiring
477 void propagateExpire(redisDb
*db
, robj
*key
) {
480 argv
[0] = shared
.del
;
482 incrRefCount(argv
[0]);
483 incrRefCount(argv
[1]);
485 if (server
.aof_state
!= REDIS_AOF_OFF
)
486 feedAppendOnlyFile(server
.delCommand
,db
->id
,argv
,2);
487 if (listLength(server
.slaves
))
488 replicationFeedSlaves(server
.slaves
,db
->id
,argv
,2);
490 decrRefCount(argv
[0]);
491 decrRefCount(argv
[1]);
494 int expireIfNeeded(redisDb
*db
, robj
*key
) {
495 long long when
= getExpire(db
,key
);
497 if (when
< 0) return 0; /* No expire for this key */
499 /* Don't expire anything while loading. It will be done later. */
500 if (server
.loading
) return 0;
502 /* If we are running in the context of a slave, return ASAP:
503 * the slave key expiration is controlled by the master that will
504 * send us synthesized DEL operations for expired keys.
506 * Still we try to return the right information to the caller,
507 * that is, 0 if we think the key should be still valid, 1 if
508 * we think the key is expired at this time. */
509 if (server
.masterhost
!= NULL
) {
510 return time(NULL
) > when
;
513 /* Return when this key has not expired */
514 if (mstime() <= when
) return 0;
517 server
.stat_expiredkeys
++;
518 propagateExpire(db
,key
);
519 return dbDelete(db
,key
);
522 /*-----------------------------------------------------------------------------
524 *----------------------------------------------------------------------------*/
526 /* Given an string object return true if it contains exactly the "ms"
527 * or "MS" string. This is used in order to check if the last argument
528 * of EXPIRE, EXPIREAT or TTL is "ms" to switch into millisecond input/output */
529 int stringObjectEqualsMs(robj
*a
) {
531 return tolower(arg
[0]) == 'm' && tolower(arg
[1]) == 's' && arg
[2] == '\0';
534 void expireGenericCommand(redisClient
*c
, long long offset
, int unit
) {
536 robj
*key
= c
->argv
[1], *param
= c
->argv
[2];
537 long long milliseconds
;
539 if (getLongLongFromObjectOrReply(c
, param
, &milliseconds
, NULL
) != REDIS_OK
)
542 if (unit
== UNIT_SECONDS
) milliseconds
*= 1000;
543 milliseconds
-= offset
;
545 de
= dictFind(c
->db
->dict
,key
->ptr
);
547 addReply(c
,shared
.czero
);
550 /* EXPIRE with negative TTL, or EXPIREAT with a timestamp into the past
551 * should never be executed as a DEL when load the AOF or in the context
552 * of a slave instance.
554 * Instead we take the other branch of the IF statement setting an expire
555 * (possibly in the past) and wait for an explicit DEL from the master. */
556 if (milliseconds
<= 0 && !server
.loading
&& !server
.masterhost
) {
559 redisAssertWithInfo(c
,key
,dbDelete(c
->db
,key
));
562 /* Replicate/AOF this as an explicit DEL. */
563 aux
= createStringObject("DEL",3);
564 rewriteClientCommandVector(c
,2,aux
,key
);
566 signalModifiedKey(c
->db
,key
);
567 addReply(c
, shared
.cone
);
570 long long when
= mstime()+milliseconds
;
571 setExpire(c
->db
,key
,when
);
572 addReply(c
,shared
.cone
);
573 signalModifiedKey(c
->db
,key
);
579 void expireCommand(redisClient
*c
) {
580 expireGenericCommand(c
,0,UNIT_SECONDS
);
583 void expireatCommand(redisClient
*c
) {
584 expireGenericCommand(c
,mstime(),UNIT_SECONDS
);
587 void pexpireCommand(redisClient
*c
) {
588 expireGenericCommand(c
,0,UNIT_MILLISECONDS
);
591 void pexpireatCommand(redisClient
*c
) {
592 expireGenericCommand(c
,mstime(),UNIT_MILLISECONDS
);
595 void ttlGenericCommand(redisClient
*c
, int output_ms
) {
596 long long expire
, ttl
= -1;
598 expire
= getExpire(c
->db
,c
->argv
[1]);
600 ttl
= expire
-mstime();
601 if (ttl
< 0) ttl
= -1;
604 addReplyLongLong(c
,-1);
606 addReplyLongLong(c
,output_ms
? ttl
: ((ttl
+500)/1000));
610 void ttlCommand(redisClient
*c
) {
611 ttlGenericCommand(c
, 0);
614 void pttlCommand(redisClient
*c
) {
615 ttlGenericCommand(c
, 1);
618 void persistCommand(redisClient
*c
) {
621 de
= dictFind(c
->db
->dict
,c
->argv
[1]->ptr
);
623 addReply(c
,shared
.czero
);
625 if (removeExpire(c
->db
,c
->argv
[1])) {
626 addReply(c
,shared
.cone
);
629 addReply(c
,shared
.czero
);
634 /* -----------------------------------------------------------------------------
635 * API to get key arguments from commands
636 * ---------------------------------------------------------------------------*/
638 int *getKeysUsingCommandTable(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
) {
639 int j
, i
= 0, last
, *keys
;
642 if (cmd
->firstkey
== 0) {
647 if (last
< 0) last
= argc
+last
;
648 keys
= zmalloc(sizeof(int)*((last
- cmd
->firstkey
)+1));
649 for (j
= cmd
->firstkey
; j
<= last
; j
+= cmd
->keystep
) {
650 redisAssert(j
< argc
);
657 int *getKeysFromCommand(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
658 if (cmd
->getkeys_proc
) {
659 return cmd
->getkeys_proc(cmd
,argv
,argc
,numkeys
,flags
);
661 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
665 void getKeysFreeResult(int *result
) {
669 int *noPreloadGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
670 if (flags
& REDIS_GETKEYS_PRELOAD
) {
674 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
678 int *renameGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
679 if (flags
& REDIS_GETKEYS_PRELOAD
) {
680 int *keys
= zmalloc(sizeof(int));
685 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
689 int *zunionInterGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
692 REDIS_NOTUSED(flags
);
694 num
= atoi(argv
[2]->ptr
);
695 /* Sanity check. Don't return any key if the command is going to
696 * reply with syntax error. */
697 if (num
> (argc
-3)) {
701 keys
= zmalloc(sizeof(int)*num
);
702 for (i
= 0; i
< num
; i
++) keys
[i
] = 3+i
;