]> git.saurik.com Git - redis.git/blame - src/db.c
Remove comment
[redis.git] / src / db.c
CommitLineData
e2641e09 1#include "redis.h"
2
3#include <signal.h>
4
5/*-----------------------------------------------------------------------------
6 * C-level DB API
7 *----------------------------------------------------------------------------*/
8
5d46e370 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
31void 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
e2641e09 38robj *lookupKey(redisDb *db, robj *key) {
39 dictEntry *de = dictFind(db->dict,key->ptr);
40 if (de) {
41 robj *val = dictGetEntryVal(de);
42
7d0966a6 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;
ef59a8bc 48
3be00d7e 49 if (server.ds_enabled &&
50 cacheScheduleIOGetFlags(db,key) & REDIS_IO_SAVEINPROG)
51 {
5d46e370 52 /* Need to wait for the key to get unbusy */
5ab7bbfc 53 redisLog(REDIS_DEBUG,"Lookup found a key in SAVEINPROG state. Waiting. (Key was in the cache)");
5d46e370 54 lookupWaitBusyKey(db,key);
e2641e09 55 }
53eeeaff 56 server.stat_keyspace_hits++;
e2641e09 57 return val;
58 } else {
ad01a255 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
9a373028 64 * in a blocking way. */
ad01a255 65 if (server.ds_enabled && cacheKeyMayExist(db,key)) {
5d46e370 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) {
5ab7bbfc 79 redisLog(REDIS_DEBUG,"Lookup found a key in SAVEINPROG state. Waiting (while force loading).");
5d46e370 80 lookupWaitBusyKey(db,key);
9a373028 81 }
82
5d46e370 83 redisLog(REDIS_DEBUG,"Force loading key %s via lookup", key->ptr);
ad01a255 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;
5d46e370 91 } else {
92 cacheSetKeyDoesNotExist(db,key);
ad01a255 93 }
94 }
53eeeaff 95 server.stat_keyspace_misses++;
e2641e09 96 return NULL;
97 }
98}
99
100robj *lookupKeyRead(redisDb *db, robj *key) {
101 expireIfNeeded(db,key);
102 return lookupKey(db,key);
103}
104
105robj *lookupKeyWrite(redisDb *db, robj *key) {
bcf2995c 106 expireIfNeeded(db,key);
e2641e09 107 return lookupKey(db,key);
108}
109
110robj *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
116robj *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'. */
125int 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);
c15a3887 133 if (server.ds_enabled) cacheSetKeyMayExist(db,key);
e2641e09 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. */
142int dbReplace(redisDb *db, robj *key, robj *val) {
a440ecf0 143 robj *oldval;
c15a3887 144 int retval;
a440ecf0 145
146 if ((oldval = dictFetchValue(db->dict,key->ptr)) == NULL) {
e2641e09 147 sds copy = sdsdup(key->ptr);
148 dictAdd(db->dict, copy, val);
c15a3887 149 retval = 1;
e2641e09 150 } else {
151 dictReplace(db->dict, key->ptr, val);
c15a3887 152 retval = 0;
e2641e09 153 }
c15a3887 154 if (server.ds_enabled) cacheSetKeyMayExist(db,key);
155 return retval;
e2641e09 156}
157
158int 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. */
166robj *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 */
189int dbDelete(redisDb *db, robj *key) {
d934e1e8 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. */
c15a3887 193 if (server.ds_enabled) {
194 handleClientsBlockedOnSwappedKey(db,key);
195 cacheSetKeyDoesNotExist(db,key);
196 }
16d77878 197
e2641e09 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
69bfffb4 204/* Empty the whole database.
205 * If diskstore is enabled this function will just flush the in-memory cache. */
e2641e09 206long 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);
69bfffb4 214 if (server.ds_enabled) dictEmpty(server.db[j].io_negcache);
e2641e09 215 }
216 return removed;
217}
218
219int 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
cea8c5cd 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
235void signalModifiedKey(redisDb *db, robj *key) {
236 touchWatchedKey(db,key);
237 if (server.ds_enabled)
3be00d7e 238 cacheScheduleIO(db,key,REDIS_IO_SAVE);
cea8c5cd 239}
240
241void signalFlushedDb(int dbid) {
242 touchWatchedKeysOnFlush(dbid);
cea8c5cd 243}
244
e2641e09 245/*-----------------------------------------------------------------------------
246 * Type agnostic commands operating on the key space
247 *----------------------------------------------------------------------------*/
248
249void flushdbCommand(redisClient *c) {
250 server.dirty += dictSize(c->db->dict);
cea8c5cd 251 signalFlushedDb(c->db->id);
e2641e09 252 dictEmpty(c->db->dict);
253 dictEmpty(c->db->expires);
120b9ba8 254 if (server.ds_enabled) dsFlushDb(c->db->id);
e2641e09 255 addReply(c,shared.ok);
256}
257
258void flushallCommand(redisClient *c) {
cea8c5cd 259 signalFlushedDb(-1);
e2641e09 260 server.dirty += emptyDb();
261 addReply(c,shared.ok);
262 if (server.bgsavechildpid != -1) {
263 kill(server.bgsavechildpid,SIGKILL);
264 rdbRemoveTempFile(server.bgsavechildpid);
265 }
120b9ba8 266 if (server.ds_enabled)
267 dsFlushDb(-1);
268 else
269 rdbSave(server.dbfilename);
e2641e09 270 server.dirty++;
271}
272
273void delCommand(redisClient *c) {
274 int deleted = 0, j;
275
276 for (j = 1; j < c->argc; j++) {
31222292 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 }
e2641e09 282 if (dbDelete(c->db,c->argv[j])) {
cea8c5cd 283 signalModifiedKey(c->db,c->argv[j]);
e2641e09 284 server.dirty++;
285 deleted++;
31222292 286 } else if (server.ds_enabled) {
287 if (cacheKeyMayExist(c->db,c->argv[j]) &&
288 dsExists(c->db,c->argv[j]))
289 {
3be00d7e 290 cacheScheduleIO(c->db,c->argv[j],REDIS_IO_SAVE);
31222292 291 deleted = 1;
292 }
e2641e09 293 }
294 }
295 addReplyLongLong(c,deleted);
296}
297
298void 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
307void selectCommand(redisClient *c) {
308 int id = atoi(c->argv[1]->ptr);
309
310 if (selectDb(c,id) == REDIS_ERR) {
3ab20376 311 addReplyError(c,"invalid DB index");
e2641e09 312 } else {
313 addReply(c,shared.ok);
314 }
315}
316
317void randomkeyCommand(redisClient *c) {
318 robj *key;
319
320 if ((key = dbRandomKey(c->db)) == NULL) {
321 addReply(c,shared.nullbulk);
322 return;
323 }
324
325 addReplyBulk(c,key);
326 decrRefCount(key);
327}
328
329void keysCommand(redisClient *c) {
330 dictIterator *di;
331 dictEntry *de;
332 sds pattern = c->argv[1]->ptr;
e0e1c195 333 int plen = sdslen(pattern), allkeys;
e2641e09 334 unsigned long numkeys = 0;
b301c1fc 335 void *replylen = addDeferredMultiBulkLength(c);
e2641e09 336
337 di = dictGetIterator(c->db->dict);
e0e1c195 338 allkeys = (pattern[0] == '*' && pattern[1] == '\0');
e2641e09 339 while((de = dictNext(di)) != NULL) {
340 sds key = dictGetEntryKey(de);
341 robj *keyobj;
342
e0e1c195 343 if (allkeys || stringmatchlen(pattern,plen,key,sdslen(key),0)) {
e2641e09 344 keyobj = createStringObject(key,sdslen(key));
345 if (expireIfNeeded(c->db,keyobj) == 0) {
346 addReplyBulk(c,keyobj);
347 numkeys++;
348 }
349 decrRefCount(keyobj);
350 }
351 }
352 dictReleaseIterator(di);
b301c1fc 353 setDeferredMultiBulkLength(c,replylen,numkeys);
e2641e09 354}
355
356void dbsizeCommand(redisClient *c) {
b70d3555 357 addReplyLongLong(c,dictSize(c->db->dict));
e2641e09 358}
359
360void lastsaveCommand(redisClient *c) {
b70d3555 361 addReplyLongLong(c,server.lastsave);
e2641e09 362}
363
364void typeCommand(redisClient *c) {
365 robj *o;
366 char *type;
367
368 o = lookupKeyRead(c->db,c->argv[1]);
369 if (o == NULL) {
3ab20376 370 type = "none";
e2641e09 371 } else {
372 switch(o->type) {
3ab20376
PN
373 case REDIS_STRING: type = "string"; break;
374 case REDIS_LIST: type = "list"; break;
375 case REDIS_SET: type = "set"; break;
376 case REDIS_ZSET: type = "zset"; break;
377 case REDIS_HASH: type = "hash"; break;
378 default: type = "unknown"; break;
e2641e09 379 }
380 }
3ab20376 381 addReplyStatus(c,type);
e2641e09 382}
383
e2641e09 384void shutdownCommand(redisClient *c) {
385 if (prepareForShutdown() == REDIS_OK)
386 exit(0);
3ab20376 387 addReplyError(c,"Errors trying to SHUTDOWN. Check logs.");
e2641e09 388}
389
390void renameGenericCommand(redisClient *c, int nx) {
391 robj *o;
392
393 /* To use the same key as src and dst is probably an error */
394 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
395 addReply(c,shared.sameobjecterr);
396 return;
397 }
398
399 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
400 return;
401
402 incrRefCount(o);
e2641e09 403 if (dbAdd(c->db,c->argv[2],o) == REDIS_ERR) {
404 if (nx) {
405 decrRefCount(o);
406 addReply(c,shared.czero);
407 return;
408 }
409 dbReplace(c->db,c->argv[2],o);
410 }
411 dbDelete(c->db,c->argv[1]);
cea8c5cd 412 signalModifiedKey(c->db,c->argv[1]);
413 signalModifiedKey(c->db,c->argv[2]);
e2641e09 414 server.dirty++;
415 addReply(c,nx ? shared.cone : shared.ok);
416}
417
418void renameCommand(redisClient *c) {
419 renameGenericCommand(c,0);
420}
421
422void renamenxCommand(redisClient *c) {
423 renameGenericCommand(c,1);
424}
425
426void moveCommand(redisClient *c) {
427 robj *o;
428 redisDb *src, *dst;
429 int srcid;
430
431 /* Obtain source and target DB pointers */
432 src = c->db;
433 srcid = c->db->id;
434 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
435 addReply(c,shared.outofrangeerr);
436 return;
437 }
438 dst = c->db;
439 selectDb(c,srcid); /* Back to the source DB */
440
441 /* If the user is moving using as target the same
442 * DB as the source DB it is probably an error. */
443 if (src == dst) {
444 addReply(c,shared.sameobjecterr);
445 return;
446 }
447
448 /* Check if the element exists and get a reference */
449 o = lookupKeyWrite(c->db,c->argv[1]);
450 if (!o) {
451 addReply(c,shared.czero);
452 return;
453 }
454
455 /* Try to add the element to the target DB */
e2641e09 456 if (dbAdd(dst,c->argv[1],o) == REDIS_ERR) {
457 addReply(c,shared.czero);
458 return;
459 }
460 incrRefCount(o);
461
462 /* OK! key moved, free the entry in the source DB */
463 dbDelete(src,c->argv[1]);
464 server.dirty++;
465 addReply(c,shared.cone);
466}
467
468/*-----------------------------------------------------------------------------
469 * Expires API
470 *----------------------------------------------------------------------------*/
471
472int removeExpire(redisDb *db, robj *key) {
473 /* An expire may only be removed if there is a corresponding entry in the
474 * main dict. Otherwise, the key will never be freed. */
475 redisAssert(dictFind(db->dict,key->ptr) != NULL);
a539d29a 476 return dictDelete(db->expires,key->ptr) == DICT_OK;
e2641e09 477}
478
0cf5b7b5 479void setExpire(redisDb *db, robj *key, time_t when) {
e2641e09 480 dictEntry *de;
481
482 /* Reuse the sds from the main dict in the expire dict */
0cf5b7b5 483 de = dictFind(db->dict,key->ptr);
484 redisAssert(de != NULL);
485 dictReplace(db->expires,dictGetEntryKey(de),(void*)when);
e2641e09 486}
487
488/* Return the expire time of the specified key, or -1 if no expire
489 * is associated with this key (i.e. the key is non volatile) */
490time_t getExpire(redisDb *db, robj *key) {
491 dictEntry *de;
492
493 /* No expire? return ASAP */
494 if (dictSize(db->expires) == 0 ||
495 (de = dictFind(db->expires,key->ptr)) == NULL) return -1;
496
497 /* The entry was found in the expire dict, this means it should also
498 * be present in the main dict (safety check). */
499 redisAssert(dictFind(db->dict,key->ptr) != NULL);
500 return (time_t) dictGetEntryVal(de);
501}
502
bcf2995c 503/* Propagate expires into slaves and the AOF file.
504 * When a key expires in the master, a DEL operation for this key is sent
505 * to all the slaves and the AOF file if enabled.
506 *
507 * This way the key expiry is centralized in one place, and since both
508 * AOF and the master->slave link guarantee operation ordering, everything
509 * will be consistent even if we allow write operations against expiring
510 * keys. */
511void propagateExpire(redisDb *db, robj *key) {
bcf2995c 512 robj *argv[2];
513
bcf2995c 514 argv[0] = createStringObject("DEL",3);
515 argv[1] = key;
516 incrRefCount(key);
517
518 if (server.appendonly)
1b1f47c9 519 feedAppendOnlyFile(server.delCommand,db->id,argv,2);
bcf2995c 520 if (listLength(server.slaves))
521 replicationFeedSlaves(server.slaves,db->id,argv,2);
522
c25a5d3b 523 decrRefCount(argv[0]);
524 decrRefCount(argv[1]);
bcf2995c 525}
526
e2641e09 527int expireIfNeeded(redisDb *db, robj *key) {
528 time_t when = getExpire(db,key);
bcf2995c 529
3a73be75 530 if (when < 0) return 0; /* No expire for this key */
531
bcf2995c 532 /* If we are running in the context of a slave, return ASAP:
533 * the slave key expiration is controlled by the master that will
534 * send us synthesized DEL operations for expired keys.
535 *
536 * Still we try to return the right information to the caller,
537 * that is, 0 if we think the key should be still valid, 1 if
538 * we think the key is expired at this time. */
539 if (server.masterhost != NULL) {
540 return time(NULL) > when;
541 }
542
e2641e09 543 /* Return when this key has not expired */
544 if (time(NULL) <= when) return 0;
545
546 /* Delete the key */
547 server.stat_expiredkeys++;
bcf2995c 548 propagateExpire(db,key);
e2641e09 549 return dbDelete(db,key);
550}
551
552/*-----------------------------------------------------------------------------
553 * Expires Commands
554 *----------------------------------------------------------------------------*/
555
556void expireGenericCommand(redisClient *c, robj *key, robj *param, long offset) {
557 dictEntry *de;
144a5e72 558 long seconds;
e2641e09 559
560 if (getLongFromObjectOrReply(c, param, &seconds, NULL) != REDIS_OK) return;
561
562 seconds -= offset;
563
564 de = dictFind(c->db->dict,key->ptr);
565 if (de == NULL) {
566 addReply(c,shared.czero);
567 return;
568 }
569 if (seconds <= 0) {
570 if (dbDelete(c->db,key)) server.dirty++;
571 addReply(c, shared.cone);
cea8c5cd 572 signalModifiedKey(c->db,key);
e2641e09 573 return;
574 } else {
575 time_t when = time(NULL)+seconds;
0cf5b7b5 576 setExpire(c->db,key,when);
577 addReply(c,shared.cone);
cea8c5cd 578 signalModifiedKey(c->db,key);
0cf5b7b5 579 server.dirty++;
e2641e09 580 return;
581 }
582}
583
584void expireCommand(redisClient *c) {
585 expireGenericCommand(c,c->argv[1],c->argv[2],0);
586}
587
588void expireatCommand(redisClient *c) {
589 expireGenericCommand(c,c->argv[1],c->argv[2],time(NULL));
590}
591
592void ttlCommand(redisClient *c) {
c91abdcd 593 time_t expire, ttl = -1;
e2641e09 594
15db4aa0 595 if (server.ds_enabled) lookupKeyRead(c->db,c->argv[1]);
e2641e09 596 expire = getExpire(c->db,c->argv[1]);
597 if (expire != -1) {
c91abdcd 598 ttl = (expire-time(NULL));
e2641e09 599 if (ttl < 0) ttl = -1;
600 }
c91abdcd 601 addReplyLongLong(c,(long long)ttl);
e2641e09 602}
a539d29a 603
604void persistCommand(redisClient *c) {
605 dictEntry *de;
606
607 de = dictFind(c->db->dict,c->argv[1]->ptr);
608 if (de == NULL) {
609 addReply(c,shared.czero);
610 } else {
1fb4e8de 611 if (removeExpire(c->db,c->argv[1])) {
a539d29a 612 addReply(c,shared.cone);
1fb4e8de 613 server.dirty++;
614 } else {
a539d29a 615 addReply(c,shared.czero);
1fb4e8de 616 }
a539d29a 617 }
618}