]> git.saurik.com Git - redis.git/blob - src/db.c
Exit with Fatal error at startup if the RDB file signature or version is wrong.
[redis.git] / src / db.c
1 #include "redis.h"
2
3 #include <signal.h>
4
5 void SlotToKeyAdd(robj *key);
6 void SlotToKeyDel(robj *key);
7
8 /*-----------------------------------------------------------------------------
9 * C-level DB API
10 *----------------------------------------------------------------------------*/
11
12 /* Important notes on lookup and disk store.
13 *
14 * When disk store is enabled on lookup we can have different cases.
15 *
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.
32 */
33
34 robj *lookupKey(redisDb *db, robj *key) {
35 dictEntry *de = dictFind(db->dict,key->ptr);
36 if (de) {
37 robj *val = dictGetEntryVal(de);
38
39 /* Update the access time for the aging algorithm.
40 * Don't do it if we have a saving child, as this will trigger
41 * a copy on write madness. */
42 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1)
43 val->lru = server.lruclock;
44 server.stat_keyspace_hits++;
45 return val;
46 } else {
47 server.stat_keyspace_misses++;
48 return NULL;
49 }
50 }
51
52 robj *lookupKeyRead(redisDb *db, robj *key) {
53 expireIfNeeded(db,key);
54 return lookupKey(db,key);
55 }
56
57 robj *lookupKeyWrite(redisDb *db, robj *key) {
58 expireIfNeeded(db,key);
59 return lookupKey(db,key);
60 }
61
62 robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply) {
63 robj *o = lookupKeyRead(c->db, key);
64 if (!o) addReply(c,reply);
65 return o;
66 }
67
68 robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply) {
69 robj *o = lookupKeyWrite(c->db, key);
70 if (!o) addReply(c,reply);
71 return o;
72 }
73
74 /* Add the key to the DB. It's up to the caller to increment the reference
75 * counte of the value if needed.
76 *
77 * The program is aborted if the key already exists. */
78 void dbAdd(redisDb *db, robj *key, robj *val) {
79 sds copy = sdsdup(key->ptr);
80 int retval = dictAdd(db->dict, copy, val);
81
82 redisAssertWithInfo(NULL,key,retval == REDIS_OK);
83 if (server.cluster_enabled) SlotToKeyAdd(key);
84 }
85
86 /* Overwrite an existing key with a new value. Incrementing the reference
87 * count of the new value is up to the caller.
88 * This function does not modify the expire time of the existing key.
89 *
90 * The program is aborted if the key was not already present. */
91 void dbOverwrite(redisDb *db, robj *key, robj *val) {
92 struct dictEntry *de = dictFind(db->dict,key->ptr);
93
94 redisAssertWithInfo(NULL,key,de != NULL);
95 dictReplace(db->dict, key->ptr, val);
96 }
97
98 /* High level Set operation. This function can be used in order to set
99 * a key, whatever it was existing or not, to a new object.
100 *
101 * 1) The ref count of the value object is incremented.
102 * 2) clients WATCHing for the destination key notified.
103 * 3) The expire time of the key is reset (the key is made persistent). */
104 void setKey(redisDb *db, robj *key, robj *val) {
105 if (lookupKeyWrite(db,key) == NULL) {
106 dbAdd(db,key,val);
107 } else {
108 dbOverwrite(db,key,val);
109 }
110 incrRefCount(val);
111 removeExpire(db,key);
112 touchWatchedKey(db,key);
113 }
114
115 int dbExists(redisDb *db, robj *key) {
116 return dictFind(db->dict,key->ptr) != NULL;
117 }
118
119 /* Return a random key, in form of a Redis object.
120 * If there are no keys, NULL is returned.
121 *
122 * The function makes sure to return keys not already expired. */
123 robj *dbRandomKey(redisDb *db) {
124 struct dictEntry *de;
125
126 while(1) {
127 sds key;
128 robj *keyobj;
129
130 de = dictGetRandomKey(db->dict);
131 if (de == NULL) return NULL;
132
133 key = dictGetEntryKey(de);
134 keyobj = createStringObject(key,sdslen(key));
135 if (dictFind(db->expires,key)) {
136 if (expireIfNeeded(db,keyobj)) {
137 decrRefCount(keyobj);
138 continue; /* search for another key. This expired. */
139 }
140 }
141 return keyobj;
142 }
143 }
144
145 /* Delete a key, value, and associated expiration entry if any, from the DB */
146 int dbDelete(redisDb *db, robj *key) {
147 /* Deleting an entry from the expires dict will not free the sds of
148 * the key, because it is shared with the main dictionary. */
149 if (dictSize(db->expires) > 0) dictDelete(db->expires,key->ptr);
150 if (dictDelete(db->dict,key->ptr) == DICT_OK) {
151 if (server.cluster_enabled) SlotToKeyDel(key);
152 return 1;
153 } else {
154 return 0;
155 }
156 }
157
158 /* Empty the whole database.
159 * If diskstore is enabled this function will just flush the in-memory cache. */
160 long long emptyDb() {
161 int j;
162 long long removed = 0;
163
164 for (j = 0; j < server.dbnum; j++) {
165 removed += dictSize(server.db[j].dict);
166 dictEmpty(server.db[j].dict);
167 dictEmpty(server.db[j].expires);
168 }
169 return removed;
170 }
171
172 int selectDb(redisClient *c, int id) {
173 if (id < 0 || id >= server.dbnum)
174 return REDIS_ERR;
175 c->db = &server.db[id];
176 return REDIS_OK;
177 }
178
179 /*-----------------------------------------------------------------------------
180 * Hooks for key space changes.
181 *
182 * Every time a key in the database is modified the function
183 * signalModifiedKey() is called.
184 *
185 * Every time a DB is flushed the function signalFlushDb() is called.
186 *----------------------------------------------------------------------------*/
187
188 void signalModifiedKey(redisDb *db, robj *key) {
189 touchWatchedKey(db,key);
190 }
191
192 void signalFlushedDb(int dbid) {
193 touchWatchedKeysOnFlush(dbid);
194 }
195
196 /*-----------------------------------------------------------------------------
197 * Type agnostic commands operating on the key space
198 *----------------------------------------------------------------------------*/
199
200 void flushdbCommand(redisClient *c) {
201 server.dirty += dictSize(c->db->dict);
202 signalFlushedDb(c->db->id);
203 dictEmpty(c->db->dict);
204 dictEmpty(c->db->expires);
205 addReply(c,shared.ok);
206 }
207
208 void flushallCommand(redisClient *c) {
209 signalFlushedDb(-1);
210 server.dirty += emptyDb();
211 addReply(c,shared.ok);
212 if (server.bgsavechildpid != -1) {
213 kill(server.bgsavechildpid,SIGKILL);
214 rdbRemoveTempFile(server.bgsavechildpid);
215 }
216 rdbSave(server.dbfilename);
217 server.dirty++;
218 }
219
220 void delCommand(redisClient *c) {
221 int deleted = 0, j;
222
223 for (j = 1; j < c->argc; j++) {
224 if (dbDelete(c->db,c->argv[j])) {
225 signalModifiedKey(c->db,c->argv[j]);
226 server.dirty++;
227 deleted++;
228 }
229 }
230 addReplyLongLong(c,deleted);
231 }
232
233 void existsCommand(redisClient *c) {
234 expireIfNeeded(c->db,c->argv[1]);
235 if (dbExists(c->db,c->argv[1])) {
236 addReply(c, shared.cone);
237 } else {
238 addReply(c, shared.czero);
239 }
240 }
241
242 void selectCommand(redisClient *c) {
243 int id = atoi(c->argv[1]->ptr);
244
245 if (server.cluster_enabled && id != 0) {
246 addReplyError(c,"SELECT is not allowed in cluster mode");
247 return;
248 }
249 if (selectDb(c,id) == REDIS_ERR) {
250 addReplyError(c,"invalid DB index");
251 } else {
252 addReply(c,shared.ok);
253 }
254 }
255
256 void randomkeyCommand(redisClient *c) {
257 robj *key;
258
259 if ((key = dbRandomKey(c->db)) == NULL) {
260 addReply(c,shared.nullbulk);
261 return;
262 }
263
264 addReplyBulk(c,key);
265 decrRefCount(key);
266 }
267
268 void keysCommand(redisClient *c) {
269 dictIterator *di;
270 dictEntry *de;
271 sds pattern = c->argv[1]->ptr;
272 int plen = sdslen(pattern), allkeys;
273 unsigned long numkeys = 0;
274 void *replylen = addDeferredMultiBulkLength(c);
275
276 di = dictGetIterator(c->db->dict);
277 allkeys = (pattern[0] == '*' && pattern[1] == '\0');
278 while((de = dictNext(di)) != NULL) {
279 sds key = dictGetEntryKey(de);
280 robj *keyobj;
281
282 if (allkeys || stringmatchlen(pattern,plen,key,sdslen(key),0)) {
283 keyobj = createStringObject(key,sdslen(key));
284 if (expireIfNeeded(c->db,keyobj) == 0) {
285 addReplyBulk(c,keyobj);
286 numkeys++;
287 }
288 decrRefCount(keyobj);
289 }
290 }
291 dictReleaseIterator(di);
292 setDeferredMultiBulkLength(c,replylen,numkeys);
293 }
294
295 void dbsizeCommand(redisClient *c) {
296 addReplyLongLong(c,dictSize(c->db->dict));
297 }
298
299 void lastsaveCommand(redisClient *c) {
300 addReplyLongLong(c,server.lastsave);
301 }
302
303 void typeCommand(redisClient *c) {
304 robj *o;
305 char *type;
306
307 o = lookupKeyRead(c->db,c->argv[1]);
308 if (o == NULL) {
309 type = "none";
310 } else {
311 switch(o->type) {
312 case REDIS_STRING: type = "string"; break;
313 case REDIS_LIST: type = "list"; break;
314 case REDIS_SET: type = "set"; break;
315 case REDIS_ZSET: type = "zset"; break;
316 case REDIS_HASH: type = "hash"; break;
317 default: type = "unknown"; break;
318 }
319 }
320 addReplyStatus(c,type);
321 }
322
323 void shutdownCommand(redisClient *c) {
324 if (prepareForShutdown() == REDIS_OK)
325 exit(0);
326 addReplyError(c,"Errors trying to SHUTDOWN. Check logs.");
327 }
328
329 void renameGenericCommand(redisClient *c, int nx) {
330 robj *o;
331 time_t expire;
332
333 /* To use the same key as src and dst is probably an error */
334 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
335 addReply(c,shared.sameobjecterr);
336 return;
337 }
338
339 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
340 return;
341
342 incrRefCount(o);
343 expire = getExpire(c->db,c->argv[1]);
344 if (lookupKeyWrite(c->db,c->argv[2]) != NULL) {
345 if (nx) {
346 decrRefCount(o);
347 addReply(c,shared.czero);
348 return;
349 }
350 /* Overwrite: delete the old key before creating the new one with the same name. */
351 dbDelete(c->db,c->argv[2]);
352 }
353 dbAdd(c->db,c->argv[2],o);
354 if (expire != -1) setExpire(c->db,c->argv[2],expire);
355 dbDelete(c->db,c->argv[1]);
356 signalModifiedKey(c->db,c->argv[1]);
357 signalModifiedKey(c->db,c->argv[2]);
358 server.dirty++;
359 addReply(c,nx ? shared.cone : shared.ok);
360 }
361
362 void renameCommand(redisClient *c) {
363 renameGenericCommand(c,0);
364 }
365
366 void renamenxCommand(redisClient *c) {
367 renameGenericCommand(c,1);
368 }
369
370 void moveCommand(redisClient *c) {
371 robj *o;
372 redisDb *src, *dst;
373 int srcid;
374
375 if (server.cluster_enabled) {
376 addReplyError(c,"MOVE is not allowed in cluster mode");
377 return;
378 }
379
380 /* Obtain source and target DB pointers */
381 src = c->db;
382 srcid = c->db->id;
383 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
384 addReply(c,shared.outofrangeerr);
385 return;
386 }
387 dst = c->db;
388 selectDb(c,srcid); /* Back to the source DB */
389
390 /* If the user is moving using as target the same
391 * DB as the source DB it is probably an error. */
392 if (src == dst) {
393 addReply(c,shared.sameobjecterr);
394 return;
395 }
396
397 /* Check if the element exists and get a reference */
398 o = lookupKeyWrite(c->db,c->argv[1]);
399 if (!o) {
400 addReply(c,shared.czero);
401 return;
402 }
403
404 /* Return zero if the key already exists in the target DB */
405 if (lookupKeyWrite(dst,c->argv[1]) != NULL) {
406 addReply(c,shared.czero);
407 return;
408 }
409 dbAdd(dst,c->argv[1],o);
410 incrRefCount(o);
411
412 /* OK! key moved, free the entry in the source DB */
413 dbDelete(src,c->argv[1]);
414 server.dirty++;
415 addReply(c,shared.cone);
416 }
417
418 /*-----------------------------------------------------------------------------
419 * Expires API
420 *----------------------------------------------------------------------------*/
421
422 int removeExpire(redisDb *db, robj *key) {
423 /* An expire may only be removed if there is a corresponding entry in the
424 * main dict. Otherwise, the key will never be freed. */
425 redisAssertWithInfo(NULL,key,dictFind(db->dict,key->ptr) != NULL);
426 return dictDelete(db->expires,key->ptr) == DICT_OK;
427 }
428
429 void setExpire(redisDb *db, robj *key, time_t when) {
430 dictEntry *de;
431
432 /* Reuse the sds from the main dict in the expire dict */
433 de = dictFind(db->dict,key->ptr);
434 redisAssertWithInfo(NULL,key,de != NULL);
435 dictReplace(db->expires,dictGetEntryKey(de),(void*)when);
436 }
437
438 /* Return the expire time of the specified key, or -1 if no expire
439 * is associated with this key (i.e. the key is non volatile) */
440 time_t getExpire(redisDb *db, robj *key) {
441 dictEntry *de;
442
443 /* No expire? return ASAP */
444 if (dictSize(db->expires) == 0 ||
445 (de = dictFind(db->expires,key->ptr)) == NULL) return -1;
446
447 /* The entry was found in the expire dict, this means it should also
448 * be present in the main dict (safety check). */
449 redisAssertWithInfo(NULL,key,dictFind(db->dict,key->ptr) != NULL);
450 return (time_t) dictGetEntryVal(de);
451 }
452
453 /* Propagate expires into slaves and the AOF file.
454 * When a key expires in the master, a DEL operation for this key is sent
455 * to all the slaves and the AOF file if enabled.
456 *
457 * This way the key expiry is centralized in one place, and since both
458 * AOF and the master->slave link guarantee operation ordering, everything
459 * will be consistent even if we allow write operations against expiring
460 * keys. */
461 void propagateExpire(redisDb *db, robj *key) {
462 robj *argv[2];
463
464 argv[0] = createStringObject("DEL",3);
465 argv[1] = key;
466 incrRefCount(key);
467
468 if (server.appendonly)
469 feedAppendOnlyFile(server.delCommand,db->id,argv,2);
470 if (listLength(server.slaves))
471 replicationFeedSlaves(server.slaves,db->id,argv,2);
472
473 decrRefCount(argv[0]);
474 decrRefCount(argv[1]);
475 }
476
477 int expireIfNeeded(redisDb *db, robj *key) {
478 time_t when = getExpire(db,key);
479
480 if (when < 0) return 0; /* No expire for this key */
481
482 /* Don't expire anything while loading. It will be done later. */
483 if (server.loading) return 0;
484
485 /* If we are running in the context of a slave, return ASAP:
486 * the slave key expiration is controlled by the master that will
487 * send us synthesized DEL operations for expired keys.
488 *
489 * Still we try to return the right information to the caller,
490 * that is, 0 if we think the key should be still valid, 1 if
491 * we think the key is expired at this time. */
492 if (server.masterhost != NULL) {
493 return time(NULL) > when;
494 }
495
496 /* Return when this key has not expired */
497 if (time(NULL) <= when) return 0;
498
499 /* Delete the key */
500 server.stat_expiredkeys++;
501 propagateExpire(db,key);
502 return dbDelete(db,key);
503 }
504
505 /*-----------------------------------------------------------------------------
506 * Expires Commands
507 *----------------------------------------------------------------------------*/
508
509 void expireGenericCommand(redisClient *c, robj *key, robj *param, long offset) {
510 dictEntry *de;
511 long seconds;
512
513 if (getLongFromObjectOrReply(c, param, &seconds, NULL) != REDIS_OK) return;
514
515 seconds -= offset;
516
517 de = dictFind(c->db->dict,key->ptr);
518 if (de == NULL) {
519 addReply(c,shared.czero);
520 return;
521 }
522 /* EXPIRE with negative TTL, or EXPIREAT with a timestamp into the past
523 * should never be executed as a DEL when load the AOF or in the context
524 * of a slave instance.
525 *
526 * Instead we take the other branch of the IF statement setting an expire
527 * (possibly in the past) and wait for an explicit DEL from the master. */
528 if (seconds <= 0 && !server.loading && !server.masterhost) {
529 robj *aux;
530
531 redisAssertWithInfo(c,key,dbDelete(c->db,key));
532 server.dirty++;
533
534 /* Replicate/AOF this as an explicit DEL. */
535 aux = createStringObject("DEL",3);
536 rewriteClientCommandVector(c,2,aux,key);
537 decrRefCount(aux);
538 signalModifiedKey(c->db,key);
539 addReply(c, shared.cone);
540 return;
541 } else {
542 time_t when = time(NULL)+seconds;
543 setExpire(c->db,key,when);
544 addReply(c,shared.cone);
545 signalModifiedKey(c->db,key);
546 server.dirty++;
547 return;
548 }
549 }
550
551 void expireCommand(redisClient *c) {
552 expireGenericCommand(c,c->argv[1],c->argv[2],0);
553 }
554
555 void expireatCommand(redisClient *c) {
556 expireGenericCommand(c,c->argv[1],c->argv[2],time(NULL));
557 }
558
559 void ttlCommand(redisClient *c) {
560 time_t expire, ttl = -1;
561
562 expire = getExpire(c->db,c->argv[1]);
563 if (expire != -1) {
564 ttl = (expire-time(NULL));
565 if (ttl < 0) ttl = -1;
566 }
567 addReplyLongLong(c,(long long)ttl);
568 }
569
570 void persistCommand(redisClient *c) {
571 dictEntry *de;
572
573 de = dictFind(c->db->dict,c->argv[1]->ptr);
574 if (de == NULL) {
575 addReply(c,shared.czero);
576 } else {
577 if (removeExpire(c->db,c->argv[1])) {
578 addReply(c,shared.cone);
579 server.dirty++;
580 } else {
581 addReply(c,shared.czero);
582 }
583 }
584 }
585
586 /* -----------------------------------------------------------------------------
587 * API to get key arguments from commands
588 * ---------------------------------------------------------------------------*/
589
590 int *getKeysUsingCommandTable(struct redisCommand *cmd,robj **argv, int argc, int *numkeys) {
591 int j, i = 0, last, *keys;
592 REDIS_NOTUSED(argv);
593
594 if (cmd->firstkey == 0) {
595 *numkeys = 0;
596 return NULL;
597 }
598 last = cmd->lastkey;
599 if (last < 0) last = argc+last;
600 keys = zmalloc(sizeof(int)*((last - cmd->firstkey)+1));
601 for (j = cmd->firstkey; j <= last; j += cmd->keystep) {
602 redisAssert(j < argc);
603 keys[i++] = j;
604 }
605 *numkeys = i;
606 return keys;
607 }
608
609 int *getKeysFromCommand(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
610 if (cmd->getkeys_proc) {
611 return cmd->getkeys_proc(cmd,argv,argc,numkeys,flags);
612 } else {
613 return getKeysUsingCommandTable(cmd,argv,argc,numkeys);
614 }
615 }
616
617 void getKeysFreeResult(int *result) {
618 zfree(result);
619 }
620
621 int *noPreloadGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
622 if (flags & REDIS_GETKEYS_PRELOAD) {
623 *numkeys = 0;
624 return NULL;
625 } else {
626 return getKeysUsingCommandTable(cmd,argv,argc,numkeys);
627 }
628 }
629
630 int *renameGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
631 if (flags & REDIS_GETKEYS_PRELOAD) {
632 int *keys = zmalloc(sizeof(int));
633 *numkeys = 1;
634 keys[0] = 1;
635 return keys;
636 } else {
637 return getKeysUsingCommandTable(cmd,argv,argc,numkeys);
638 }
639 }
640
641 int *zunionInterGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
642 int i, num, *keys;
643 REDIS_NOTUSED(cmd);
644 REDIS_NOTUSED(flags);
645
646 num = atoi(argv[2]->ptr);
647 /* Sanity check. Don't return any key if the command is going to
648 * reply with syntax error. */
649 if (num > (argc-3)) {
650 *numkeys = 0;
651 return NULL;
652 }
653 keys = zmalloc(sizeof(int)*num);
654 for (i = 0; i < num; i++) keys[i] = 3+i;
655 *numkeys = num;
656 return keys;
657 }
658
659 /* Slot to Key API. This is used by Redis Cluster in order to obtain in
660 * a fast way a key that belongs to a specified hash slot. This is useful
661 * while rehashing the cluster. */
662 void SlotToKeyAdd(robj *key) {
663 unsigned int hashslot = keyHashSlot(key->ptr,sdslen(key->ptr));
664
665 zslInsert(server.cluster.slots_to_keys,hashslot,key);
666 incrRefCount(key);
667 }
668
669 void SlotToKeyDel(robj *key) {
670 unsigned int hashslot = keyHashSlot(key->ptr,sdslen(key->ptr));
671
672 zslDelete(server.cluster.slots_to_keys,hashslot,key);
673 }
674
675 unsigned int GetKeysInSlot(unsigned int hashslot, robj **keys, unsigned int count) {
676 zskiplistNode *n;
677 zrangespec range;
678 int j = 0;
679
680 range.min = range.max = hashslot;
681 range.minex = range.maxex = 0;
682
683 n = zslFirstInRange(server.cluster.slots_to_keys, range);
684 while(n && n->score == hashslot && count--) {
685 keys[j++] = n->obj;
686 n = n->level[0].forward;
687 }
688 return j;
689 }