]> git.saurik.com Git - redis.git/blob - src/db.c
Sentinel: changes to connection handling and redirection.
[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 long id;
230
231 if (getLongFromObjectOrReply(c, c->argv[1], &id,
232 "invalid DB index") != REDIS_OK)
233 return;
234
235 if (selectDb(c,id) == REDIS_ERR) {
236 addReplyError(c,"invalid DB index");
237 } else {
238 addReply(c,shared.ok);
239 }
240 }
241
242 void randomkeyCommand(redisClient *c) {
243 robj *key;
244
245 if ((key = dbRandomKey(c->db)) == NULL) {
246 addReply(c,shared.nullbulk);
247 return;
248 }
249
250 addReplyBulk(c,key);
251 decrRefCount(key);
252 }
253
254 void keysCommand(redisClient *c) {
255 dictIterator *di;
256 dictEntry *de;
257 sds pattern = c->argv[1]->ptr;
258 int plen = sdslen(pattern), allkeys;
259 unsigned long numkeys = 0;
260 void *replylen = addDeferredMultiBulkLength(c);
261
262 di = dictGetSafeIterator(c->db->dict);
263 allkeys = (pattern[0] == '*' && pattern[1] == '\0');
264 while((de = dictNext(di)) != NULL) {
265 sds key = dictGetKey(de);
266 robj *keyobj;
267
268 if (allkeys || stringmatchlen(pattern,plen,key,sdslen(key),0)) {
269 keyobj = createStringObject(key,sdslen(key));
270 if (expireIfNeeded(c->db,keyobj) == 0) {
271 addReplyBulk(c,keyobj);
272 numkeys++;
273 }
274 decrRefCount(keyobj);
275 }
276 }
277 dictReleaseIterator(di);
278 setDeferredMultiBulkLength(c,replylen,numkeys);
279 }
280
281 void dbsizeCommand(redisClient *c) {
282 addReplyLongLong(c,dictSize(c->db->dict));
283 }
284
285 void lastsaveCommand(redisClient *c) {
286 addReplyLongLong(c,server.lastsave);
287 }
288
289 void typeCommand(redisClient *c) {
290 robj *o;
291 char *type;
292
293 o = lookupKeyRead(c->db,c->argv[1]);
294 if (o == NULL) {
295 type = "none";
296 } else {
297 switch(o->type) {
298 case REDIS_STRING: type = "string"; break;
299 case REDIS_LIST: type = "list"; break;
300 case REDIS_SET: type = "set"; break;
301 case REDIS_ZSET: type = "zset"; break;
302 case REDIS_HASH: type = "hash"; break;
303 default: type = "unknown"; break;
304 }
305 }
306 addReplyStatus(c,type);
307 }
308
309 void shutdownCommand(redisClient *c) {
310 int flags = 0;
311
312 if (c->argc > 2) {
313 addReply(c,shared.syntaxerr);
314 return;
315 } else if (c->argc == 2) {
316 if (!strcasecmp(c->argv[1]->ptr,"nosave")) {
317 flags |= REDIS_SHUTDOWN_NOSAVE;
318 } else if (!strcasecmp(c->argv[1]->ptr,"save")) {
319 flags |= REDIS_SHUTDOWN_SAVE;
320 } else {
321 addReply(c,shared.syntaxerr);
322 return;
323 }
324 }
325 if (prepareForShutdown(flags) == REDIS_OK) exit(0);
326 addReplyError(c,"Errors trying to SHUTDOWN. Check logs.");
327 }
328
329 void renameGenericCommand(redisClient *c, int nx) {
330 robj *o;
331 long long expire;
332
333 /* To use the same key as src and dst is probably an error */
334 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
335 addReply(c,shared.sameobjecterr);
336 return;
337 }
338
339 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
340 return;
341
342 incrRefCount(o);
343 expire = getExpire(c->db,c->argv[1]);
344 if (lookupKeyWrite(c->db,c->argv[2]) != NULL) {
345 if (nx) {
346 decrRefCount(o);
347 addReply(c,shared.czero);
348 return;
349 }
350 /* Overwrite: delete the old key before creating the new one with the same name. */
351 dbDelete(c->db,c->argv[2]);
352 }
353 dbAdd(c->db,c->argv[2],o);
354 if (expire != -1) setExpire(c->db,c->argv[2],expire);
355 dbDelete(c->db,c->argv[1]);
356 signalModifiedKey(c->db,c->argv[1]);
357 signalModifiedKey(c->db,c->argv[2]);
358 server.dirty++;
359 addReply(c,nx ? shared.cone : shared.ok);
360 }
361
362 void renameCommand(redisClient *c) {
363 renameGenericCommand(c,0);
364 }
365
366 void renamenxCommand(redisClient *c) {
367 renameGenericCommand(c,1);
368 }
369
370 void moveCommand(redisClient *c) {
371 robj *o;
372 redisDb *src, *dst;
373 int srcid;
374
375 /* Obtain source and target DB pointers */
376 src = c->db;
377 srcid = c->db->id;
378 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
379 addReply(c,shared.outofrangeerr);
380 return;
381 }
382 dst = c->db;
383 selectDb(c,srcid); /* Back to the source DB */
384
385 /* If the user is moving using as target the same
386 * DB as the source DB it is probably an error. */
387 if (src == dst) {
388 addReply(c,shared.sameobjecterr);
389 return;
390 }
391
392 /* Check if the element exists and get a reference */
393 o = lookupKeyWrite(c->db,c->argv[1]);
394 if (!o) {
395 addReply(c,shared.czero);
396 return;
397 }
398
399 /* Return zero if the key already exists in the target DB */
400 if (lookupKeyWrite(dst,c->argv[1]) != NULL) {
401 addReply(c,shared.czero);
402 return;
403 }
404 dbAdd(dst,c->argv[1],o);
405 incrRefCount(o);
406
407 /* OK! key moved, free the entry in the source DB */
408 dbDelete(src,c->argv[1]);
409 server.dirty++;
410 addReply(c,shared.cone);
411 }
412
413 /*-----------------------------------------------------------------------------
414 * Expires API
415 *----------------------------------------------------------------------------*/
416
417 int removeExpire(redisDb *db, robj *key) {
418 /* An expire may only be removed if there is a corresponding entry in the
419 * main dict. Otherwise, the key will never be freed. */
420 redisAssertWithInfo(NULL,key,dictFind(db->dict,key->ptr) != NULL);
421 return dictDelete(db->expires,key->ptr) == DICT_OK;
422 }
423
424 void setExpire(redisDb *db, robj *key, long long when) {
425 dictEntry *kde, *de;
426
427 /* Reuse the sds from the main dict in the expire dict */
428 kde = dictFind(db->dict,key->ptr);
429 redisAssertWithInfo(NULL,key,kde != NULL);
430 de = dictReplaceRaw(db->expires,dictGetKey(kde));
431 dictSetSignedIntegerVal(de,when);
432 }
433
434 /* Return the expire time of the specified key, or -1 if no expire
435 * is associated with this key (i.e. the key is non volatile) */
436 long long getExpire(redisDb *db, robj *key) {
437 dictEntry *de;
438
439 /* No expire? return ASAP */
440 if (dictSize(db->expires) == 0 ||
441 (de = dictFind(db->expires,key->ptr)) == NULL) return -1;
442
443 /* The entry was found in the expire dict, this means it should also
444 * be present in the main dict (safety check). */
445 redisAssertWithInfo(NULL,key,dictFind(db->dict,key->ptr) != NULL);
446 return dictGetSignedIntegerVal(de);
447 }
448
449 /* Propagate expires into slaves and the AOF file.
450 * When a key expires in the master, a DEL operation for this key is sent
451 * to all the slaves and the AOF file if enabled.
452 *
453 * This way the key expiry is centralized in one place, and since both
454 * AOF and the master->slave link guarantee operation ordering, everything
455 * will be consistent even if we allow write operations against expiring
456 * keys. */
457 void propagateExpire(redisDb *db, robj *key) {
458 robj *argv[2];
459
460 argv[0] = shared.del;
461 argv[1] = key;
462 incrRefCount(argv[0]);
463 incrRefCount(argv[1]);
464
465 if (server.aof_state != REDIS_AOF_OFF)
466 feedAppendOnlyFile(server.delCommand,db->id,argv,2);
467 if (listLength(server.slaves))
468 replicationFeedSlaves(server.slaves,db->id,argv,2);
469
470 decrRefCount(argv[0]);
471 decrRefCount(argv[1]);
472 }
473
474 int expireIfNeeded(redisDb *db, robj *key) {
475 long long when = getExpire(db,key);
476
477 if (when < 0) return 0; /* No expire for this key */
478
479 /* Don't expire anything while loading. It will be done later. */
480 if (server.loading) return 0;
481
482 /* If we are running in the context of a slave, return ASAP:
483 * the slave key expiration is controlled by the master that will
484 * send us synthesized DEL operations for expired keys.
485 *
486 * Still we try to return the right information to the caller,
487 * that is, 0 if we think the key should be still valid, 1 if
488 * we think the key is expired at this time. */
489 if (server.masterhost != NULL) {
490 return mstime() > when;
491 }
492
493 /* Return when this key has not expired */
494 if (mstime() <= when) return 0;
495
496 /* Delete the key */
497 server.stat_expiredkeys++;
498 propagateExpire(db,key);
499 return dbDelete(db,key);
500 }
501
502 /*-----------------------------------------------------------------------------
503 * Expires Commands
504 *----------------------------------------------------------------------------*/
505
506 /* This is the generic command implementation for EXPIRE, PEXPIRE, EXPIREAT
507 * and PEXPIREAT. Because the commad second argument may be relative or absolute
508 * the "basetime" argument is used to signal what the base time is (either 0
509 * for *AT variants of the command, or the current time for relative expires).
510 *
511 * unit is either UNIT_SECONDS or UNIT_MILLISECONDS, and is only used for
512 * the argv[2] parameter. The basetime is always specified in milliesconds. */
513 void expireGenericCommand(redisClient *c, long long basetime, int unit) {
514 dictEntry *de;
515 robj *key = c->argv[1], *param = c->argv[2];
516 long long when; /* unix time in milliseconds when the key will expire. */
517
518 if (getLongLongFromObjectOrReply(c, param, &when, NULL) != REDIS_OK)
519 return;
520
521 if (unit == UNIT_SECONDS) when *= 1000;
522 when += basetime;
523
524 de = dictFind(c->db->dict,key->ptr);
525 if (de == NULL) {
526 addReply(c,shared.czero);
527 return;
528 }
529 /* EXPIRE with negative TTL, or EXPIREAT with a timestamp into the past
530 * should never be executed as a DEL when load the AOF or in the context
531 * of a slave instance.
532 *
533 * Instead we take the other branch of the IF statement setting an expire
534 * (possibly in the past) and wait for an explicit DEL from the master. */
535 if (when <= mstime() && !server.loading && !server.masterhost) {
536 robj *aux;
537
538 redisAssertWithInfo(c,key,dbDelete(c->db,key));
539 server.dirty++;
540
541 /* Replicate/AOF this as an explicit DEL. */
542 aux = createStringObject("DEL",3);
543 rewriteClientCommandVector(c,2,aux,key);
544 decrRefCount(aux);
545 signalModifiedKey(c->db,key);
546 addReply(c, shared.cone);
547 return;
548 } else {
549 setExpire(c->db,key,when);
550 addReply(c,shared.cone);
551 signalModifiedKey(c->db,key);
552 server.dirty++;
553 return;
554 }
555 }
556
557 void expireCommand(redisClient *c) {
558 expireGenericCommand(c,mstime(),UNIT_SECONDS);
559 }
560
561 void expireatCommand(redisClient *c) {
562 expireGenericCommand(c,0,UNIT_SECONDS);
563 }
564
565 void pexpireCommand(redisClient *c) {
566 expireGenericCommand(c,mstime(),UNIT_MILLISECONDS);
567 }
568
569 void pexpireatCommand(redisClient *c) {
570 expireGenericCommand(c,0,UNIT_MILLISECONDS);
571 }
572
573 void ttlGenericCommand(redisClient *c, int output_ms) {
574 long long expire, ttl = -1;
575
576 expire = getExpire(c->db,c->argv[1]);
577 if (expire != -1) {
578 ttl = expire-mstime();
579 if (ttl < 0) ttl = -1;
580 }
581 if (ttl == -1) {
582 addReplyLongLong(c,-1);
583 } else {
584 addReplyLongLong(c,output_ms ? ttl : ((ttl+500)/1000));
585 }
586 }
587
588 void ttlCommand(redisClient *c) {
589 ttlGenericCommand(c, 0);
590 }
591
592 void pttlCommand(redisClient *c) {
593 ttlGenericCommand(c, 1);
594 }
595
596 void persistCommand(redisClient *c) {
597 dictEntry *de;
598
599 de = dictFind(c->db->dict,c->argv[1]->ptr);
600 if (de == NULL) {
601 addReply(c,shared.czero);
602 } else {
603 if (removeExpire(c->db,c->argv[1])) {
604 addReply(c,shared.cone);
605 server.dirty++;
606 } else {
607 addReply(c,shared.czero);
608 }
609 }
610 }
611
612 /* -----------------------------------------------------------------------------
613 * API to get key arguments from commands
614 * ---------------------------------------------------------------------------*/
615
616 int *getKeysUsingCommandTable(struct redisCommand *cmd,robj **argv, int argc, int *numkeys) {
617 int j, i = 0, last, *keys;
618 REDIS_NOTUSED(argv);
619
620 if (cmd->firstkey == 0) {
621 *numkeys = 0;
622 return NULL;
623 }
624 last = cmd->lastkey;
625 if (last < 0) last = argc+last;
626 keys = zmalloc(sizeof(int)*((last - cmd->firstkey)+1));
627 for (j = cmd->firstkey; j <= last; j += cmd->keystep) {
628 redisAssert(j < argc);
629 keys[i++] = j;
630 }
631 *numkeys = i;
632 return keys;
633 }
634
635 int *getKeysFromCommand(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
636 if (cmd->getkeys_proc) {
637 return cmd->getkeys_proc(cmd,argv,argc,numkeys,flags);
638 } else {
639 return getKeysUsingCommandTable(cmd,argv,argc,numkeys);
640 }
641 }
642
643 void getKeysFreeResult(int *result) {
644 zfree(result);
645 }
646
647 int *noPreloadGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
648 if (flags & REDIS_GETKEYS_PRELOAD) {
649 *numkeys = 0;
650 return NULL;
651 } else {
652 return getKeysUsingCommandTable(cmd,argv,argc,numkeys);
653 }
654 }
655
656 int *renameGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
657 if (flags & REDIS_GETKEYS_PRELOAD) {
658 int *keys = zmalloc(sizeof(int));
659 *numkeys = 1;
660 keys[0] = 1;
661 return keys;
662 } else {
663 return getKeysUsingCommandTable(cmd,argv,argc,numkeys);
664 }
665 }
666
667 int *zunionInterGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
668 int i, num, *keys;
669 REDIS_NOTUSED(cmd);
670 REDIS_NOTUSED(flags);
671
672 num = atoi(argv[2]->ptr);
673 /* Sanity check. Don't return any key if the command is going to
674 * reply with syntax error. */
675 if (num > (argc-3)) {
676 *numkeys = 0;
677 return NULL;
678 }
679 keys = zmalloc(sizeof(int)*num);
680 for (i = 0; i < num; i++) keys[i] = 3+i;
681 *numkeys = num;
682 return keys;
683 }