]>
git.saurik.com Git - redis.git/blob - src/db.c
9fe9a003ce57e7b316ac69e20c5b4b00e3b4e894
2 * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
8 * * Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * * Neither the name of Redis nor the names of its contributors may be used
14 * to endorse or promote products derived from this software without
15 * specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
35 void SlotToKeyAdd(robj
*key
);
36 void SlotToKeyDel(robj
*key
);
38 /*-----------------------------------------------------------------------------
40 *----------------------------------------------------------------------------*/
42 robj
*lookupKey(redisDb
*db
, robj
*key
) {
43 dictEntry
*de
= dictFind(db
->dict
,key
->ptr
);
45 robj
*val
= dictGetVal(de
);
47 /* Update the access time for the aging algorithm.
48 * Don't do it if we have a saving child, as this will trigger
49 * a copy on write madness. */
50 if (server
.rdb_child_pid
== -1 && server
.aof_child_pid
== -1)
51 val
->lru
= server
.lruclock
;
58 robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
61 expireIfNeeded(db
,key
);
62 val
= lookupKey(db
,key
);
64 server
.stat_keyspace_misses
++;
66 server
.stat_keyspace_hits
++;
70 robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
71 expireIfNeeded(db
,key
);
72 return lookupKey(db
,key
);
75 robj
*lookupKeyReadOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
76 robj
*o
= lookupKeyRead(c
->db
, key
);
77 if (!o
) addReply(c
,reply
);
81 robj
*lookupKeyWriteOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
82 robj
*o
= lookupKeyWrite(c
->db
, key
);
83 if (!o
) addReply(c
,reply
);
87 /* Add the key to the DB. It's up to the caller to increment the reference
88 * counte of the value if needed.
90 * The program is aborted if the key already exists. */
91 void dbAdd(redisDb
*db
, robj
*key
, robj
*val
) {
92 sds copy
= sdsdup(key
->ptr
);
93 int retval
= dictAdd(db
->dict
, copy
, val
);
95 redisAssertWithInfo(NULL
,key
,retval
== REDIS_OK
);
96 if (server
.cluster_enabled
) SlotToKeyAdd(key
);
99 /* Overwrite an existing key with a new value. Incrementing the reference
100 * count of the new value is up to the caller.
101 * This function does not modify the expire time of the existing key.
103 * The program is aborted if the key was not already present. */
104 void dbOverwrite(redisDb
*db
, robj
*key
, robj
*val
) {
105 struct dictEntry
*de
= dictFind(db
->dict
,key
->ptr
);
107 redisAssertWithInfo(NULL
,key
,de
!= NULL
);
108 dictReplace(db
->dict
, key
->ptr
, val
);
111 /* High level Set operation. This function can be used in order to set
112 * a key, whatever it was existing or not, to a new object.
114 * 1) The ref count of the value object is incremented.
115 * 2) clients WATCHing for the destination key notified.
116 * 3) The expire time of the key is reset (the key is made persistent). */
117 void setKey(redisDb
*db
, robj
*key
, robj
*val
) {
118 if (lookupKeyWrite(db
,key
) == NULL
) {
121 dbOverwrite(db
,key
,val
);
124 removeExpire(db
,key
);
125 signalModifiedKey(db
,key
);
128 int dbExists(redisDb
*db
, robj
*key
) {
129 return dictFind(db
->dict
,key
->ptr
) != NULL
;
132 /* Return a random key, in form of a Redis object.
133 * If there are no keys, NULL is returned.
135 * The function makes sure to return keys not already expired. */
136 robj
*dbRandomKey(redisDb
*db
) {
137 struct dictEntry
*de
;
143 de
= dictGetRandomKey(db
->dict
);
144 if (de
== NULL
) return NULL
;
146 key
= dictGetKey(de
);
147 keyobj
= createStringObject(key
,sdslen(key
));
148 if (dictFind(db
->expires
,key
)) {
149 if (expireIfNeeded(db
,keyobj
)) {
150 decrRefCount(keyobj
);
151 continue; /* search for another key. This expired. */
158 /* Delete a key, value, and associated expiration entry if any, from the DB */
159 int dbDelete(redisDb
*db
, robj
*key
) {
160 /* Deleting an entry from the expires dict will not free the sds of
161 * the key, because it is shared with the main dictionary. */
162 if (dictSize(db
->expires
) > 0) dictDelete(db
->expires
,key
->ptr
);
163 if (dictDelete(db
->dict
,key
->ptr
) == DICT_OK
) {
164 if (server
.cluster_enabled
) SlotToKeyDel(key
);
171 long long emptyDb() {
173 long long removed
= 0;
175 for (j
= 0; j
< server
.dbnum
; j
++) {
176 removed
+= dictSize(server
.db
[j
].dict
);
177 dictEmpty(server
.db
[j
].dict
);
178 dictEmpty(server
.db
[j
].expires
);
183 int selectDb(redisClient
*c
, int id
) {
184 if (id
< 0 || id
>= server
.dbnum
)
186 c
->db
= &server
.db
[id
];
190 /*-----------------------------------------------------------------------------
191 * Hooks for key space changes.
193 * Every time a key in the database is modified the function
194 * signalModifiedKey() is called.
196 * Every time a DB is flushed the function signalFlushDb() is called.
197 *----------------------------------------------------------------------------*/
199 void signalModifiedKey(redisDb
*db
, robj
*key
) {
200 touchWatchedKey(db
,key
);
203 void signalFlushedDb(int dbid
) {
204 touchWatchedKeysOnFlush(dbid
);
207 /*-----------------------------------------------------------------------------
208 * Type agnostic commands operating on the key space
209 *----------------------------------------------------------------------------*/
211 void flushdbCommand(redisClient
*c
) {
212 server
.dirty
+= dictSize(c
->db
->dict
);
213 signalFlushedDb(c
->db
->id
);
214 dictEmpty(c
->db
->dict
);
215 dictEmpty(c
->db
->expires
);
216 addReply(c
,shared
.ok
);
219 void flushallCommand(redisClient
*c
) {
221 server
.dirty
+= emptyDb();
222 addReply(c
,shared
.ok
);
223 if (server
.rdb_child_pid
!= -1) {
224 kill(server
.rdb_child_pid
,SIGKILL
);
225 rdbRemoveTempFile(server
.rdb_child_pid
);
227 if (server
.saveparamslen
> 0) {
228 /* Normally rdbSave() will reset dirty, but we don't want this here
229 * as otherwise FLUSHALL will not be replicated nor put into the AOF. */
230 int saved_dirty
= server
.dirty
;
231 rdbSave(server
.rdb_filename
);
232 server
.dirty
= saved_dirty
;
237 void delCommand(redisClient
*c
) {
240 for (j
= 1; j
< c
->argc
; j
++) {
241 if (dbDelete(c
->db
,c
->argv
[j
])) {
242 signalModifiedKey(c
->db
,c
->argv
[j
]);
247 addReplyLongLong(c
,deleted
);
250 void existsCommand(redisClient
*c
) {
251 expireIfNeeded(c
->db
,c
->argv
[1]);
252 if (dbExists(c
->db
,c
->argv
[1])) {
253 addReply(c
, shared
.cone
);
255 addReply(c
, shared
.czero
);
259 void selectCommand(redisClient
*c
) {
262 if (getLongFromObjectOrReply(c
, c
->argv
[1], &id
,
263 "invalid DB index") != REDIS_OK
)
266 if (server
.cluster_enabled
&& id
!= 0) {
267 addReplyError(c
,"SELECT is not allowed in cluster mode");
270 if (selectDb(c
,id
) == REDIS_ERR
) {
271 addReplyError(c
,"invalid DB index");
273 addReply(c
,shared
.ok
);
277 void randomkeyCommand(redisClient
*c
) {
280 if ((key
= dbRandomKey(c
->db
)) == NULL
) {
281 addReply(c
,shared
.nullbulk
);
289 void keysCommand(redisClient
*c
) {
292 sds pattern
= c
->argv
[1]->ptr
;
293 int plen
= sdslen(pattern
), allkeys
;
294 unsigned long numkeys
= 0;
295 void *replylen
= addDeferredMultiBulkLength(c
);
297 di
= dictGetSafeIterator(c
->db
->dict
);
298 allkeys
= (pattern
[0] == '*' && pattern
[1] == '\0');
299 while((de
= dictNext(di
)) != NULL
) {
300 sds key
= dictGetKey(de
);
303 if (allkeys
|| stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
304 keyobj
= createStringObject(key
,sdslen(key
));
305 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
306 addReplyBulk(c
,keyobj
);
309 decrRefCount(keyobj
);
312 dictReleaseIterator(di
);
313 setDeferredMultiBulkLength(c
,replylen
,numkeys
);
316 void dbsizeCommand(redisClient
*c
) {
317 addReplyLongLong(c
,dictSize(c
->db
->dict
));
320 void lastsaveCommand(redisClient
*c
) {
321 addReplyLongLong(c
,server
.lastsave
);
324 void typeCommand(redisClient
*c
) {
328 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
333 case REDIS_STRING
: type
= "string"; break;
334 case REDIS_LIST
: type
= "list"; break;
335 case REDIS_SET
: type
= "set"; break;
336 case REDIS_ZSET
: type
= "zset"; break;
337 case REDIS_HASH
: type
= "hash"; break;
338 default: type
= "unknown"; break;
341 addReplyStatus(c
,type
);
344 void shutdownCommand(redisClient
*c
) {
348 addReply(c
,shared
.syntaxerr
);
350 } else if (c
->argc
== 2) {
351 if (!strcasecmp(c
->argv
[1]->ptr
,"nosave")) {
352 flags
|= REDIS_SHUTDOWN_NOSAVE
;
353 } else if (!strcasecmp(c
->argv
[1]->ptr
,"save")) {
354 flags
|= REDIS_SHUTDOWN_SAVE
;
356 addReply(c
,shared
.syntaxerr
);
360 if (prepareForShutdown(flags
) == REDIS_OK
) exit(0);
361 addReplyError(c
,"Errors trying to SHUTDOWN. Check logs.");
364 void renameGenericCommand(redisClient
*c
, int nx
) {
368 /* To use the same key as src and dst is probably an error */
369 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
370 addReply(c
,shared
.sameobjecterr
);
374 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
)
378 expire
= getExpire(c
->db
,c
->argv
[1]);
379 if (lookupKeyWrite(c
->db
,c
->argv
[2]) != NULL
) {
382 addReply(c
,shared
.czero
);
385 /* Overwrite: delete the old key before creating the new one with the same name. */
386 dbDelete(c
->db
,c
->argv
[2]);
388 dbAdd(c
->db
,c
->argv
[2],o
);
389 if (expire
!= -1) setExpire(c
->db
,c
->argv
[2],expire
);
390 dbDelete(c
->db
,c
->argv
[1]);
391 signalModifiedKey(c
->db
,c
->argv
[1]);
392 signalModifiedKey(c
->db
,c
->argv
[2]);
394 addReply(c
,nx
? shared
.cone
: shared
.ok
);
397 void renameCommand(redisClient
*c
) {
398 renameGenericCommand(c
,0);
401 void renamenxCommand(redisClient
*c
) {
402 renameGenericCommand(c
,1);
405 void moveCommand(redisClient
*c
) {
410 if (server
.cluster_enabled
) {
411 addReplyError(c
,"MOVE is not allowed in cluster mode");
415 /* Obtain source and target DB pointers */
418 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
419 addReply(c
,shared
.outofrangeerr
);
423 selectDb(c
,srcid
); /* Back to the source DB */
425 /* If the user is moving using as target the same
426 * DB as the source DB it is probably an error. */
428 addReply(c
,shared
.sameobjecterr
);
432 /* Check if the element exists and get a reference */
433 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
435 addReply(c
,shared
.czero
);
439 /* Return zero if the key already exists in the target DB */
440 if (lookupKeyWrite(dst
,c
->argv
[1]) != NULL
) {
441 addReply(c
,shared
.czero
);
444 dbAdd(dst
,c
->argv
[1],o
);
447 /* OK! key moved, free the entry in the source DB */
448 dbDelete(src
,c
->argv
[1]);
450 addReply(c
,shared
.cone
);
453 /*-----------------------------------------------------------------------------
455 *----------------------------------------------------------------------------*/
457 int removeExpire(redisDb
*db
, robj
*key
) {
458 /* An expire may only be removed if there is a corresponding entry in the
459 * main dict. Otherwise, the key will never be freed. */
460 redisAssertWithInfo(NULL
,key
,dictFind(db
->dict
,key
->ptr
) != NULL
);
461 return dictDelete(db
->expires
,key
->ptr
) == DICT_OK
;
464 void setExpire(redisDb
*db
, robj
*key
, long long when
) {
467 /* Reuse the sds from the main dict in the expire dict */
468 kde
= dictFind(db
->dict
,key
->ptr
);
469 redisAssertWithInfo(NULL
,key
,kde
!= NULL
);
470 de
= dictReplaceRaw(db
->expires
,dictGetKey(kde
));
471 dictSetSignedIntegerVal(de
,when
);
474 /* Return the expire time of the specified key, or -1 if no expire
475 * is associated with this key (i.e. the key is non volatile) */
476 long long getExpire(redisDb
*db
, robj
*key
) {
479 /* No expire? return ASAP */
480 if (dictSize(db
->expires
) == 0 ||
481 (de
= dictFind(db
->expires
,key
->ptr
)) == NULL
) return -1;
483 /* The entry was found in the expire dict, this means it should also
484 * be present in the main dict (safety check). */
485 redisAssertWithInfo(NULL
,key
,dictFind(db
->dict
,key
->ptr
) != NULL
);
486 return dictGetSignedIntegerVal(de
);
489 /* Propagate expires into slaves and the AOF file.
490 * When a key expires in the master, a DEL operation for this key is sent
491 * to all the slaves and the AOF file if enabled.
493 * This way the key expiry is centralized in one place, and since both
494 * AOF and the master->slave link guarantee operation ordering, everything
495 * will be consistent even if we allow write operations against expiring
497 void propagateExpire(redisDb
*db
, robj
*key
) {
500 argv
[0] = shared
.del
;
502 incrRefCount(argv
[0]);
503 incrRefCount(argv
[1]);
505 if (server
.aof_state
!= REDIS_AOF_OFF
)
506 feedAppendOnlyFile(server
.delCommand
,db
->id
,argv
,2);
507 if (listLength(server
.slaves
))
508 replicationFeedSlaves(server
.slaves
,db
->id
,argv
,2);
510 decrRefCount(argv
[0]);
511 decrRefCount(argv
[1]);
514 int expireIfNeeded(redisDb
*db
, robj
*key
) {
515 long long when
= getExpire(db
,key
);
517 if (when
< 0) return 0; /* No expire for this key */
519 /* Don't expire anything while loading. It will be done later. */
520 if (server
.loading
) return 0;
522 /* If we are running in the context of a slave, return ASAP:
523 * the slave key expiration is controlled by the master that will
524 * send us synthesized DEL operations for expired keys.
526 * Still we try to return the right information to the caller,
527 * that is, 0 if we think the key should be still valid, 1 if
528 * we think the key is expired at this time. */
529 if (server
.masterhost
!= NULL
) {
530 return mstime() > when
;
533 /* Return when this key has not expired */
534 if (mstime() <= when
) return 0;
537 server
.stat_expiredkeys
++;
538 propagateExpire(db
,key
);
539 return dbDelete(db
,key
);
542 /*-----------------------------------------------------------------------------
544 *----------------------------------------------------------------------------*/
546 /* This is the generic command implementation for EXPIRE, PEXPIRE, EXPIREAT
547 * and PEXPIREAT. Because the commad second argument may be relative or absolute
548 * the "basetime" argument is used to signal what the base time is (either 0
549 * for *AT variants of the command, or the current time for relative expires).
551 * unit is either UNIT_SECONDS or UNIT_MILLISECONDS, and is only used for
552 * the argv[2] parameter. The basetime is always specified in milliesconds. */
553 void expireGenericCommand(redisClient
*c
, long long basetime
, int unit
) {
555 robj
*key
= c
->argv
[1], *param
= c
->argv
[2];
556 long long when
; /* unix time in milliseconds when the key will expire. */
558 if (getLongLongFromObjectOrReply(c
, param
, &when
, NULL
) != REDIS_OK
)
561 if (unit
== UNIT_SECONDS
) when
*= 1000;
564 de
= dictFind(c
->db
->dict
,key
->ptr
);
566 addReply(c
,shared
.czero
);
569 /* EXPIRE with negative TTL, or EXPIREAT with a timestamp into the past
570 * should never be executed as a DEL when load the AOF or in the context
571 * of a slave instance.
573 * Instead we take the other branch of the IF statement setting an expire
574 * (possibly in the past) and wait for an explicit DEL from the master. */
575 if (when
<= mstime() && !server
.loading
&& !server
.masterhost
) {
578 redisAssertWithInfo(c
,key
,dbDelete(c
->db
,key
));
581 /* Replicate/AOF this as an explicit DEL. */
582 aux
= createStringObject("DEL",3);
583 rewriteClientCommandVector(c
,2,aux
,key
);
585 signalModifiedKey(c
->db
,key
);
586 addReply(c
, shared
.cone
);
589 setExpire(c
->db
,key
,when
);
590 addReply(c
,shared
.cone
);
591 signalModifiedKey(c
->db
,key
);
597 void expireCommand(redisClient
*c
) {
598 expireGenericCommand(c
,mstime(),UNIT_SECONDS
);
601 void expireatCommand(redisClient
*c
) {
602 expireGenericCommand(c
,0,UNIT_SECONDS
);
605 void pexpireCommand(redisClient
*c
) {
606 expireGenericCommand(c
,mstime(),UNIT_MILLISECONDS
);
609 void pexpireatCommand(redisClient
*c
) {
610 expireGenericCommand(c
,0,UNIT_MILLISECONDS
);
613 void ttlGenericCommand(redisClient
*c
, int output_ms
) {
614 long long expire
, ttl
= -1;
616 expire
= getExpire(c
->db
,c
->argv
[1]);
618 ttl
= expire
-mstime();
619 if (ttl
< 0) ttl
= -1;
622 addReplyLongLong(c
,-1);
624 addReplyLongLong(c
,output_ms
? ttl
: ((ttl
+500)/1000));
628 void ttlCommand(redisClient
*c
) {
629 ttlGenericCommand(c
, 0);
632 void pttlCommand(redisClient
*c
) {
633 ttlGenericCommand(c
, 1);
636 void persistCommand(redisClient
*c
) {
639 de
= dictFind(c
->db
->dict
,c
->argv
[1]->ptr
);
641 addReply(c
,shared
.czero
);
643 if (removeExpire(c
->db
,c
->argv
[1])) {
644 addReply(c
,shared
.cone
);
647 addReply(c
,shared
.czero
);
652 /* -----------------------------------------------------------------------------
653 * API to get key arguments from commands
654 * ---------------------------------------------------------------------------*/
656 int *getKeysUsingCommandTable(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
) {
657 int j
, i
= 0, last
, *keys
;
660 if (cmd
->firstkey
== 0) {
665 if (last
< 0) last
= argc
+last
;
666 keys
= zmalloc(sizeof(int)*((last
- cmd
->firstkey
)+1));
667 for (j
= cmd
->firstkey
; j
<= last
; j
+= cmd
->keystep
) {
668 redisAssert(j
< argc
);
675 int *getKeysFromCommand(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
676 if (cmd
->getkeys_proc
) {
677 return cmd
->getkeys_proc(cmd
,argv
,argc
,numkeys
,flags
);
679 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
683 void getKeysFreeResult(int *result
) {
687 int *noPreloadGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
688 if (flags
& REDIS_GETKEYS_PRELOAD
) {
692 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
696 int *renameGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
697 if (flags
& REDIS_GETKEYS_PRELOAD
) {
698 int *keys
= zmalloc(sizeof(int));
703 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
707 int *zunionInterGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
710 REDIS_NOTUSED(flags
);
712 num
= atoi(argv
[2]->ptr
);
713 /* Sanity check. Don't return any key if the command is going to
714 * reply with syntax error. */
715 if (num
> (argc
-3)) {
719 keys
= zmalloc(sizeof(int)*num
);
720 for (i
= 0; i
< num
; i
++) keys
[i
] = 3+i
;
725 /* Slot to Key API. This is used by Redis Cluster in order to obtain in
726 * a fast way a key that belongs to a specified hash slot. This is useful
727 * while rehashing the cluster. */
728 void SlotToKeyAdd(robj
*key
) {
729 unsigned int hashslot
= keyHashSlot(key
->ptr
,sdslen(key
->ptr
));
731 zslInsert(server
.cluster
.slots_to_keys
,hashslot
,key
);
735 void SlotToKeyDel(robj
*key
) {
736 unsigned int hashslot
= keyHashSlot(key
->ptr
,sdslen(key
->ptr
));
738 zslDelete(server
.cluster
.slots_to_keys
,hashslot
,key
);
741 unsigned int GetKeysInSlot(unsigned int hashslot
, robj
**keys
, unsigned int count
) {
746 range
.min
= range
.max
= hashslot
;
747 range
.minex
= range
.maxex
= 0;
749 n
= zslFirstInRange(server
.cluster
.slots_to_keys
, range
);
750 while(n
&& n
->score
== hashslot
&& count
--) {
752 n
= n
->level
[0].forward
;