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