]> git.saurik.com Git - redis.git/blob - src/db.c
source reshaped a bit to play well with a bgsaving thread, still work to do, does...
[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 long long emptyDb() {
206 int j;
207 long long removed = 0;
208
209 for (j = 0; j < server.dbnum; j++) {
210 removed += dictSize(server.db[j].dict);
211 dictEmpty(server.db[j].dict);
212 dictEmpty(server.db[j].expires);
213 }
214 return removed;
215 }
216
217 int selectDb(redisClient *c, int id) {
218 if (id < 0 || id >= server.dbnum)
219 return REDIS_ERR;
220 c->db = &server.db[id];
221 return REDIS_OK;
222 }
223
224 /*-----------------------------------------------------------------------------
225 * Hooks for key space changes.
226 *
227 * Every time a key in the database is modified the function
228 * signalModifiedKey() is called.
229 *
230 * Every time a DB is flushed the function signalFlushDb() is called.
231 *----------------------------------------------------------------------------*/
232
233 void signalModifiedKey(redisDb *db, robj *key) {
234 touchWatchedKey(db,key);
235 if (server.ds_enabled)
236 cacheScheduleIO(db,key,REDIS_IO_SAVE);
237 }
238
239 void signalFlushedDb(int dbid) {
240 touchWatchedKeysOnFlush(dbid);
241 }
242
243 /*-----------------------------------------------------------------------------
244 * Type agnostic commands operating on the key space
245 *----------------------------------------------------------------------------*/
246
247 void flushdbCommand(redisClient *c) {
248 server.dirty += dictSize(c->db->dict);
249 signalFlushedDb(c->db->id);
250 dictEmpty(c->db->dict);
251 dictEmpty(c->db->expires);
252 if (server.ds_enabled) dsFlushDb(c->db->id);
253 addReply(c,shared.ok);
254 }
255
256 void flushallCommand(redisClient *c) {
257 signalFlushedDb(-1);
258 server.dirty += emptyDb();
259 addReply(c,shared.ok);
260 if (server.bgsavechildpid != -1) {
261 kill(server.bgsavechildpid,SIGKILL);
262 rdbRemoveTempFile(server.bgsavechildpid);
263 }
264 if (server.ds_enabled)
265 dsFlushDb(-1);
266 else
267 rdbSave(server.dbfilename);
268 server.dirty++;
269 }
270
271 void delCommand(redisClient *c) {
272 int deleted = 0, j;
273
274 for (j = 1; j < c->argc; j++) {
275 if (server.ds_enabled) {
276 lookupKeyRead(c->db,c->argv[j]);
277 /* FIXME: this can be optimized a lot, no real need to load
278 * a possibly huge value. */
279 }
280 if (dbDelete(c->db,c->argv[j])) {
281 signalModifiedKey(c->db,c->argv[j]);
282 server.dirty++;
283 deleted++;
284 } else if (server.ds_enabled) {
285 if (cacheKeyMayExist(c->db,c->argv[j]) &&
286 dsExists(c->db,c->argv[j]))
287 {
288 cacheScheduleIO(c->db,c->argv[j],REDIS_IO_SAVE);
289 deleted = 1;
290 }
291 }
292 }
293 addReplyLongLong(c,deleted);
294 }
295
296 void existsCommand(redisClient *c) {
297 expireIfNeeded(c->db,c->argv[1]);
298 if (dbExists(c->db,c->argv[1])) {
299 addReply(c, shared.cone);
300 } else {
301 addReply(c, shared.czero);
302 }
303 }
304
305 void selectCommand(redisClient *c) {
306 int id = atoi(c->argv[1]->ptr);
307
308 if (selectDb(c,id) == REDIS_ERR) {
309 addReplyError(c,"invalid DB index");
310 } else {
311 addReply(c,shared.ok);
312 }
313 }
314
315 void randomkeyCommand(redisClient *c) {
316 robj *key;
317
318 if ((key = dbRandomKey(c->db)) == NULL) {
319 addReply(c,shared.nullbulk);
320 return;
321 }
322
323 addReplyBulk(c,key);
324 decrRefCount(key);
325 }
326
327 void keysCommand(redisClient *c) {
328 dictIterator *di;
329 dictEntry *de;
330 sds pattern = c->argv[1]->ptr;
331 int plen = sdslen(pattern), allkeys;
332 unsigned long numkeys = 0;
333 void *replylen = addDeferredMultiBulkLength(c);
334
335 di = dictGetIterator(c->db->dict);
336 allkeys = (pattern[0] == '*' && pattern[1] == '\0');
337 while((de = dictNext(di)) != NULL) {
338 sds key = dictGetEntryKey(de);
339 robj *keyobj;
340
341 if (allkeys || stringmatchlen(pattern,plen,key,sdslen(key),0)) {
342 keyobj = createStringObject(key,sdslen(key));
343 if (expireIfNeeded(c->db,keyobj) == 0) {
344 addReplyBulk(c,keyobj);
345 numkeys++;
346 }
347 decrRefCount(keyobj);
348 }
349 }
350 dictReleaseIterator(di);
351 setDeferredMultiBulkLength(c,replylen,numkeys);
352 }
353
354 void dbsizeCommand(redisClient *c) {
355 addReplyLongLong(c,dictSize(c->db->dict));
356 }
357
358 void lastsaveCommand(redisClient *c) {
359 addReplyLongLong(c,server.lastsave);
360 }
361
362 void typeCommand(redisClient *c) {
363 robj *o;
364 char *type;
365
366 o = lookupKeyRead(c->db,c->argv[1]);
367 if (o == NULL) {
368 type = "none";
369 } else {
370 switch(o->type) {
371 case REDIS_STRING: type = "string"; break;
372 case REDIS_LIST: type = "list"; break;
373 case REDIS_SET: type = "set"; break;
374 case REDIS_ZSET: type = "zset"; break;
375 case REDIS_HASH: type = "hash"; break;
376 default: type = "unknown"; break;
377 }
378 }
379 addReplyStatus(c,type);
380 }
381
382 void shutdownCommand(redisClient *c) {
383 if (prepareForShutdown() == REDIS_OK)
384 exit(0);
385 addReplyError(c,"Errors trying to SHUTDOWN. Check logs.");
386 }
387
388 void renameGenericCommand(redisClient *c, int nx) {
389 robj *o;
390
391 /* To use the same key as src and dst is probably an error */
392 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
393 addReply(c,shared.sameobjecterr);
394 return;
395 }
396
397 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
398 return;
399
400 incrRefCount(o);
401 if (dbAdd(c->db,c->argv[2],o) == REDIS_ERR) {
402 if (nx) {
403 decrRefCount(o);
404 addReply(c,shared.czero);
405 return;
406 }
407 dbReplace(c->db,c->argv[2],o);
408 }
409 dbDelete(c->db,c->argv[1]);
410 signalModifiedKey(c->db,c->argv[1]);
411 signalModifiedKey(c->db,c->argv[2]);
412 server.dirty++;
413 addReply(c,nx ? shared.cone : shared.ok);
414 }
415
416 void renameCommand(redisClient *c) {
417 renameGenericCommand(c,0);
418 }
419
420 void renamenxCommand(redisClient *c) {
421 renameGenericCommand(c,1);
422 }
423
424 void moveCommand(redisClient *c) {
425 robj *o;
426 redisDb *src, *dst;
427 int srcid;
428
429 /* Obtain source and target DB pointers */
430 src = c->db;
431 srcid = c->db->id;
432 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
433 addReply(c,shared.outofrangeerr);
434 return;
435 }
436 dst = c->db;
437 selectDb(c,srcid); /* Back to the source DB */
438
439 /* If the user is moving using as target the same
440 * DB as the source DB it is probably an error. */
441 if (src == dst) {
442 addReply(c,shared.sameobjecterr);
443 return;
444 }
445
446 /* Check if the element exists and get a reference */
447 o = lookupKeyWrite(c->db,c->argv[1]);
448 if (!o) {
449 addReply(c,shared.czero);
450 return;
451 }
452
453 /* Try to add the element to the target DB */
454 if (dbAdd(dst,c->argv[1],o) == REDIS_ERR) {
455 addReply(c,shared.czero);
456 return;
457 }
458 incrRefCount(o);
459
460 /* OK! key moved, free the entry in the source DB */
461 dbDelete(src,c->argv[1]);
462 server.dirty++;
463 addReply(c,shared.cone);
464 }
465
466 /*-----------------------------------------------------------------------------
467 * Expires API
468 *----------------------------------------------------------------------------*/
469
470 int removeExpire(redisDb *db, robj *key) {
471 /* An expire may only be removed if there is a corresponding entry in the
472 * main dict. Otherwise, the key will never be freed. */
473 redisAssert(dictFind(db->dict,key->ptr) != NULL);
474 return dictDelete(db->expires,key->ptr) == DICT_OK;
475 }
476
477 void setExpire(redisDb *db, robj *key, time_t when) {
478 dictEntry *de;
479
480 /* Reuse the sds from the main dict in the expire dict */
481 de = dictFind(db->dict,key->ptr);
482 redisAssert(de != NULL);
483 dictReplace(db->expires,dictGetEntryKey(de),(void*)when);
484 }
485
486 /* Return the expire time of the specified key, or -1 if no expire
487 * is associated with this key (i.e. the key is non volatile) */
488 time_t getExpire(redisDb *db, robj *key) {
489 dictEntry *de;
490
491 /* No expire? return ASAP */
492 if (dictSize(db->expires) == 0 ||
493 (de = dictFind(db->expires,key->ptr)) == NULL) return -1;
494
495 /* The entry was found in the expire dict, this means it should also
496 * be present in the main dict (safety check). */
497 redisAssert(dictFind(db->dict,key->ptr) != NULL);
498 return (time_t) dictGetEntryVal(de);
499 }
500
501 /* Propagate expires into slaves and the AOF file.
502 * When a key expires in the master, a DEL operation for this key is sent
503 * to all the slaves and the AOF file if enabled.
504 *
505 * This way the key expiry is centralized in one place, and since both
506 * AOF and the master->slave link guarantee operation ordering, everything
507 * will be consistent even if we allow write operations against expiring
508 * keys. */
509 void propagateExpire(redisDb *db, robj *key) {
510 robj *argv[2];
511
512 argv[0] = createStringObject("DEL",3);
513 argv[1] = key;
514 incrRefCount(key);
515
516 if (server.appendonly)
517 feedAppendOnlyFile(server.delCommand,db->id,argv,2);
518 if (listLength(server.slaves))
519 replicationFeedSlaves(server.slaves,db->id,argv,2);
520
521 decrRefCount(argv[0]);
522 decrRefCount(argv[1]);
523 }
524
525 int expireIfNeeded(redisDb *db, robj *key) {
526 time_t when = getExpire(db,key);
527
528 /* If we are running in the context of a slave, return ASAP:
529 * the slave key expiration is controlled by the master that will
530 * send us synthesized DEL operations for expired keys.
531 *
532 * Still we try to return the right information to the caller,
533 * that is, 0 if we think the key should be still valid, 1 if
534 * we think the key is expired at this time. */
535 if (server.masterhost != NULL) {
536 return time(NULL) > when;
537 }
538
539 if (when < 0) return 0;
540
541 /* Return when this key has not expired */
542 if (time(NULL) <= when) return 0;
543
544 /* Delete the key */
545 server.stat_expiredkeys++;
546 propagateExpire(db,key);
547 return dbDelete(db,key);
548 }
549
550 /*-----------------------------------------------------------------------------
551 * Expires Commands
552 *----------------------------------------------------------------------------*/
553
554 void expireGenericCommand(redisClient *c, robj *key, robj *param, long offset) {
555 dictEntry *de;
556 long seconds;
557
558 if (getLongFromObjectOrReply(c, param, &seconds, NULL) != REDIS_OK) return;
559
560 seconds -= offset;
561
562 de = dictFind(c->db->dict,key->ptr);
563 if (de == NULL) {
564 addReply(c,shared.czero);
565 return;
566 }
567 if (seconds <= 0) {
568 if (dbDelete(c->db,key)) server.dirty++;
569 addReply(c, shared.cone);
570 signalModifiedKey(c->db,key);
571 return;
572 } else {
573 time_t when = time(NULL)+seconds;
574 setExpire(c->db,key,when);
575 addReply(c,shared.cone);
576 signalModifiedKey(c->db,key);
577 server.dirty++;
578 return;
579 }
580 }
581
582 void expireCommand(redisClient *c) {
583 expireGenericCommand(c,c->argv[1],c->argv[2],0);
584 }
585
586 void expireatCommand(redisClient *c) {
587 expireGenericCommand(c,c->argv[1],c->argv[2],time(NULL));
588 }
589
590 void ttlCommand(redisClient *c) {
591 time_t expire, ttl = -1;
592
593 expire = getExpire(c->db,c->argv[1]);
594 if (expire != -1) {
595 ttl = (expire-time(NULL));
596 if (ttl < 0) ttl = -1;
597 }
598 addReplyLongLong(c,(long long)ttl);
599 }
600
601 void persistCommand(redisClient *c) {
602 dictEntry *de;
603
604 de = dictFind(c->db->dict,c->argv[1]->ptr);
605 if (de == NULL) {
606 addReply(c,shared.czero);
607 } else {
608 if (removeExpire(c->db,c->argv[1])) {
609 addReply(c,shared.cone);
610 server.dirty++;
611 } else {
612 addReply(c,shared.czero);
613 }
614 }
615 }