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