]> git.saurik.com Git - redis.git/blob - src/db.c
Never used function stringObjectEqualsMs() removed.
[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 /* This is the generic command implementation for EXPIRE, PEXPIRE, EXPIREAT
503 * and PEXPIREAT. Because the commad second argument may be relative or absolute
504 * the "basetime" argument is used to signal what the base time is (either 0
505 * for *AT variants of the command, or the current time for relative expires).
506 *
507 * unit is either UNIT_SECONDS or UNIT_MILLISECONDS, and is only used for
508 * the argv[2] parameter. The basetime is always specified in milliesconds. */
509 void expireGenericCommand(redisClient *c, long long basetime, int unit) {
510 dictEntry *de;
511 robj *key = c->argv[1], *param = c->argv[2];
512 long long when; /* unix time in milliseconds when the key will expire. */
513
514 if (getLongLongFromObjectOrReply(c, param, &when, NULL) != REDIS_OK)
515 return;
516
517 if (unit == UNIT_SECONDS) when *= 1000;
518 when += basetime;
519
520 de = dictFind(c->db->dict,key->ptr);
521 if (de == NULL) {
522 addReply(c,shared.czero);
523 return;
524 }
525 /* EXPIRE with negative TTL, or EXPIREAT with a timestamp into the past
526 * should never be executed as a DEL when load the AOF or in the context
527 * of a slave instance.
528 *
529 * Instead we take the other branch of the IF statement setting an expire
530 * (possibly in the past) and wait for an explicit DEL from the master. */
531 if (when <= mstime() && !server.loading && !server.masterhost) {
532 robj *aux;
533
534 redisAssertWithInfo(c,key,dbDelete(c->db,key));
535 server.dirty++;
536
537 /* Replicate/AOF this as an explicit DEL. */
538 aux = createStringObject("DEL",3);
539 rewriteClientCommandVector(c,2,aux,key);
540 decrRefCount(aux);
541 signalModifiedKey(c->db,key);
542 addReply(c, shared.cone);
543 return;
544 } else {
545 setExpire(c->db,key,when);
546 addReply(c,shared.cone);
547 signalModifiedKey(c->db,key);
548 server.dirty++;
549 return;
550 }
551 }
552
553 void expireCommand(redisClient *c) {
554 expireGenericCommand(c,mstime(),UNIT_SECONDS);
555 }
556
557 void expireatCommand(redisClient *c) {
558 expireGenericCommand(c,0,UNIT_SECONDS);
559 }
560
561 void pexpireCommand(redisClient *c) {
562 expireGenericCommand(c,mstime(),UNIT_MILLISECONDS);
563 }
564
565 void pexpireatCommand(redisClient *c) {
566 expireGenericCommand(c,0,UNIT_MILLISECONDS);
567 }
568
569 void ttlGenericCommand(redisClient *c, int output_ms) {
570 long long expire, ttl = -1;
571
572 expire = getExpire(c->db,c->argv[1]);
573 if (expire != -1) {
574 ttl = expire-mstime();
575 if (ttl < 0) ttl = -1;
576 }
577 if (ttl == -1) {
578 addReplyLongLong(c,-1);
579 } else {
580 addReplyLongLong(c,output_ms ? ttl : ((ttl+500)/1000));
581 }
582 }
583
584 void ttlCommand(redisClient *c) {
585 ttlGenericCommand(c, 0);
586 }
587
588 void pttlCommand(redisClient *c) {
589 ttlGenericCommand(c, 1);
590 }
591
592 void persistCommand(redisClient *c) {
593 dictEntry *de;
594
595 de = dictFind(c->db->dict,c->argv[1]->ptr);
596 if (de == NULL) {
597 addReply(c,shared.czero);
598 } else {
599 if (removeExpire(c->db,c->argv[1])) {
600 addReply(c,shared.cone);
601 server.dirty++;
602 } else {
603 addReply(c,shared.czero);
604 }
605 }
606 }
607
608 /* -----------------------------------------------------------------------------
609 * API to get key arguments from commands
610 * ---------------------------------------------------------------------------*/
611
612 int *getKeysUsingCommandTable(struct redisCommand *cmd,robj **argv, int argc, int *numkeys) {
613 int j, i = 0, last, *keys;
614 REDIS_NOTUSED(argv);
615
616 if (cmd->firstkey == 0) {
617 *numkeys = 0;
618 return NULL;
619 }
620 last = cmd->lastkey;
621 if (last < 0) last = argc+last;
622 keys = zmalloc(sizeof(int)*((last - cmd->firstkey)+1));
623 for (j = cmd->firstkey; j <= last; j += cmd->keystep) {
624 redisAssert(j < argc);
625 keys[i++] = j;
626 }
627 *numkeys = i;
628 return keys;
629 }
630
631 int *getKeysFromCommand(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
632 if (cmd->getkeys_proc) {
633 return cmd->getkeys_proc(cmd,argv,argc,numkeys,flags);
634 } else {
635 return getKeysUsingCommandTable(cmd,argv,argc,numkeys);
636 }
637 }
638
639 void getKeysFreeResult(int *result) {
640 zfree(result);
641 }
642
643 int *noPreloadGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
644 if (flags & REDIS_GETKEYS_PRELOAD) {
645 *numkeys = 0;
646 return NULL;
647 } else {
648 return getKeysUsingCommandTable(cmd,argv,argc,numkeys);
649 }
650 }
651
652 int *renameGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
653 if (flags & REDIS_GETKEYS_PRELOAD) {
654 int *keys = zmalloc(sizeof(int));
655 *numkeys = 1;
656 keys[0] = 1;
657 return keys;
658 } else {
659 return getKeysUsingCommandTable(cmd,argv,argc,numkeys);
660 }
661 }
662
663 int *zunionInterGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
664 int i, num, *keys;
665 REDIS_NOTUSED(cmd);
666 REDIS_NOTUSED(flags);
667
668 num = atoi(argv[2]->ptr);
669 /* Sanity check. Don't return any key if the command is going to
670 * reply with syntax error. */
671 if (num > (argc-3)) {
672 *numkeys = 0;
673 return NULL;
674 }
675 keys = zmalloc(sizeof(int)*num);
676 for (i = 0; i < num; i++) keys[i] = 3+i;
677 *numkeys = num;
678 return keys;
679 }