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