]> git.saurik.com Git - redis.git/blame - src/db.c
Fix bug in gluing a deferred multi bulk length to the next reply chunk
[redis.git] / src / db.c
CommitLineData
e2641e09 1#include "redis.h"
2
3#include <signal.h>
4
5/*-----------------------------------------------------------------------------
6 * C-level DB API
7 *----------------------------------------------------------------------------*/
8
9robj *lookupKey(redisDb *db, robj *key) {
10 dictEntry *de = dictFind(db->dict,key->ptr);
11 if (de) {
12 robj *val = dictGetEntryVal(de);
13
14 if (server.vm_enabled) {
15 if (val->storage == REDIS_VM_MEMORY ||
16 val->storage == REDIS_VM_SWAPPING)
17 {
18 /* If we were swapping the object out, cancel the operation */
19 if (val->storage == REDIS_VM_SWAPPING)
20 vmCancelThreadedIOJob(val);
21 /* Update the access time for the aging algorithm. */
22 val->lru = server.lruclock;
23 } else {
24 int notify = (val->storage == REDIS_VM_LOADING);
25
26 /* Our value was swapped on disk. Bring it at home. */
27 redisAssert(val->type == REDIS_VMPOINTER);
28 val = vmLoadObject(val);
29 dictGetEntryVal(de) = val;
30
31 /* Clients blocked by the VM subsystem may be waiting for
32 * this key... */
33 if (notify) handleClientsBlockedOnSwappedKey(db,key);
34 }
35 }
36 return val;
37 } else {
38 return NULL;
39 }
40}
41
42robj *lookupKeyRead(redisDb *db, robj *key) {
43 expireIfNeeded(db,key);
44 return lookupKey(db,key);
45}
46
47robj *lookupKeyWrite(redisDb *db, robj *key) {
bcf2995c 48 expireIfNeeded(db,key);
e2641e09 49 return lookupKey(db,key);
50}
51
52robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply) {
53 robj *o = lookupKeyRead(c->db, key);
54 if (!o) addReply(c,reply);
55 return o;
56}
57
58robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply) {
59 robj *o = lookupKeyWrite(c->db, key);
60 if (!o) addReply(c,reply);
61 return o;
62}
63
64/* Add the key to the DB. If the key already exists REDIS_ERR is returned,
65 * otherwise REDIS_OK is returned, and the caller should increment the
66 * refcount of 'val'. */
67int dbAdd(redisDb *db, robj *key, robj *val) {
68 /* Perform a lookup before adding the key, as we need to copy the
69 * key value. */
70 if (dictFind(db->dict, key->ptr) != NULL) {
71 return REDIS_ERR;
72 } else {
73 sds copy = sdsdup(key->ptr);
74 dictAdd(db->dict, copy, val);
75 return REDIS_OK;
76 }
77}
78
79/* If the key does not exist, this is just like dbAdd(). Otherwise
80 * the value associated to the key is replaced with the new one.
81 *
82 * On update (key already existed) 0 is returned. Otherwise 1. */
83int dbReplace(redisDb *db, robj *key, robj *val) {
84 if (dictFind(db->dict,key->ptr) == NULL) {
85 sds copy = sdsdup(key->ptr);
86 dictAdd(db->dict, copy, val);
87 return 1;
88 } else {
89 dictReplace(db->dict, key->ptr, val);
90 return 0;
91 }
92}
93
94int dbExists(redisDb *db, robj *key) {
95 return dictFind(db->dict,key->ptr) != NULL;
96}
97
98/* Return a random key, in form of a Redis object.
99 * If there are no keys, NULL is returned.
100 *
101 * The function makes sure to return keys not already expired. */
102robj *dbRandomKey(redisDb *db) {
103 struct dictEntry *de;
104
105 while(1) {
106 sds key;
107 robj *keyobj;
108
109 de = dictGetRandomKey(db->dict);
110 if (de == NULL) return NULL;
111
112 key = dictGetEntryKey(de);
113 keyobj = createStringObject(key,sdslen(key));
114 if (dictFind(db->expires,key)) {
115 if (expireIfNeeded(db,keyobj)) {
116 decrRefCount(keyobj);
117 continue; /* search for another key. This expired. */
118 }
119 }
120 return keyobj;
121 }
122}
123
124/* Delete a key, value, and associated expiration entry if any, from the DB */
125int dbDelete(redisDb *db, robj *key) {
126 /* Deleting an entry from the expires dict will not free the sds of
127 * the key, because it is shared with the main dictionary. */
128 if (dictSize(db->expires) > 0) dictDelete(db->expires,key->ptr);
129 return dictDelete(db->dict,key->ptr) == DICT_OK;
130}
131
132/* Empty the whole database */
133long long emptyDb() {
134 int j;
135 long long removed = 0;
136
137 for (j = 0; j < server.dbnum; j++) {
138 removed += dictSize(server.db[j].dict);
139 dictEmpty(server.db[j].dict);
140 dictEmpty(server.db[j].expires);
141 }
142 return removed;
143}
144
145int selectDb(redisClient *c, int id) {
146 if (id < 0 || id >= server.dbnum)
147 return REDIS_ERR;
148 c->db = &server.db[id];
149 return REDIS_OK;
150}
151
152/*-----------------------------------------------------------------------------
153 * Type agnostic commands operating on the key space
154 *----------------------------------------------------------------------------*/
155
156void flushdbCommand(redisClient *c) {
157 server.dirty += dictSize(c->db->dict);
158 touchWatchedKeysOnFlush(c->db->id);
159 dictEmpty(c->db->dict);
160 dictEmpty(c->db->expires);
161 addReply(c,shared.ok);
162}
163
164void flushallCommand(redisClient *c) {
165 touchWatchedKeysOnFlush(-1);
166 server.dirty += emptyDb();
167 addReply(c,shared.ok);
168 if (server.bgsavechildpid != -1) {
169 kill(server.bgsavechildpid,SIGKILL);
170 rdbRemoveTempFile(server.bgsavechildpid);
171 }
172 rdbSave(server.dbfilename);
173 server.dirty++;
174}
175
176void delCommand(redisClient *c) {
177 int deleted = 0, j;
178
179 for (j = 1; j < c->argc; j++) {
180 if (dbDelete(c->db,c->argv[j])) {
181 touchWatchedKey(c->db,c->argv[j]);
182 server.dirty++;
183 deleted++;
184 }
185 }
186 addReplyLongLong(c,deleted);
187}
188
189void existsCommand(redisClient *c) {
190 expireIfNeeded(c->db,c->argv[1]);
191 if (dbExists(c->db,c->argv[1])) {
192 addReply(c, shared.cone);
193 } else {
194 addReply(c, shared.czero);
195 }
196}
197
198void selectCommand(redisClient *c) {
199 int id = atoi(c->argv[1]->ptr);
200
201 if (selectDb(c,id) == REDIS_ERR) {
3ab20376 202 addReplyError(c,"invalid DB index");
e2641e09 203 } else {
204 addReply(c,shared.ok);
205 }
206}
207
208void randomkeyCommand(redisClient *c) {
209 robj *key;
210
211 if ((key = dbRandomKey(c->db)) == NULL) {
212 addReply(c,shared.nullbulk);
213 return;
214 }
215
216 addReplyBulk(c,key);
217 decrRefCount(key);
218}
219
220void keysCommand(redisClient *c) {
221 dictIterator *di;
222 dictEntry *de;
223 sds pattern = c->argv[1]->ptr;
224 int plen = sdslen(pattern);
225 unsigned long numkeys = 0;
b301c1fc 226 void *replylen = addDeferredMultiBulkLength(c);
e2641e09 227
228 di = dictGetIterator(c->db->dict);
e2641e09 229 while((de = dictNext(di)) != NULL) {
230 sds key = dictGetEntryKey(de);
231 robj *keyobj;
232
233 if ((pattern[0] == '*' && pattern[1] == '\0') ||
234 stringmatchlen(pattern,plen,key,sdslen(key),0)) {
235 keyobj = createStringObject(key,sdslen(key));
236 if (expireIfNeeded(c->db,keyobj) == 0) {
237 addReplyBulk(c,keyobj);
238 numkeys++;
239 }
240 decrRefCount(keyobj);
241 }
242 }
243 dictReleaseIterator(di);
b301c1fc 244 setDeferredMultiBulkLength(c,replylen,numkeys);
e2641e09 245}
246
247void dbsizeCommand(redisClient *c) {
b70d3555 248 addReplyLongLong(c,dictSize(c->db->dict));
e2641e09 249}
250
251void lastsaveCommand(redisClient *c) {
b70d3555 252 addReplyLongLong(c,server.lastsave);
e2641e09 253}
254
255void typeCommand(redisClient *c) {
256 robj *o;
257 char *type;
258
259 o = lookupKeyRead(c->db,c->argv[1]);
260 if (o == NULL) {
3ab20376 261 type = "none";
e2641e09 262 } else {
263 switch(o->type) {
3ab20376
PN
264 case REDIS_STRING: type = "string"; break;
265 case REDIS_LIST: type = "list"; break;
266 case REDIS_SET: type = "set"; break;
267 case REDIS_ZSET: type = "zset"; break;
268 case REDIS_HASH: type = "hash"; break;
269 default: type = "unknown"; break;
e2641e09 270 }
271 }
3ab20376 272 addReplyStatus(c,type);
e2641e09 273}
274
275void saveCommand(redisClient *c) {
276 if (server.bgsavechildpid != -1) {
3ab20376 277 addReplyError(c,"Background save already in progress");
e2641e09 278 return;
279 }
280 if (rdbSave(server.dbfilename) == REDIS_OK) {
281 addReply(c,shared.ok);
282 } else {
283 addReply(c,shared.err);
284 }
285}
286
287void bgsaveCommand(redisClient *c) {
288 if (server.bgsavechildpid != -1) {
3ab20376 289 addReplyError(c,"Background save already in progress");
e2641e09 290 return;
291 }
292 if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
3ab20376 293 addReplyStatus(c,"Background saving started");
e2641e09 294 } else {
295 addReply(c,shared.err);
296 }
297}
298
299void shutdownCommand(redisClient *c) {
300 if (prepareForShutdown() == REDIS_OK)
301 exit(0);
3ab20376 302 addReplyError(c,"Errors trying to SHUTDOWN. Check logs.");
e2641e09 303}
304
305void renameGenericCommand(redisClient *c, int nx) {
306 robj *o;
307
308 /* To use the same key as src and dst is probably an error */
309 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
310 addReply(c,shared.sameobjecterr);
311 return;
312 }
313
314 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
315 return;
316
317 incrRefCount(o);
e2641e09 318 if (dbAdd(c->db,c->argv[2],o) == REDIS_ERR) {
319 if (nx) {
320 decrRefCount(o);
321 addReply(c,shared.czero);
322 return;
323 }
324 dbReplace(c->db,c->argv[2],o);
325 }
326 dbDelete(c->db,c->argv[1]);
5b4bff9c 327 touchWatchedKey(c->db,c->argv[1]);
e2641e09 328 touchWatchedKey(c->db,c->argv[2]);
329 server.dirty++;
330 addReply(c,nx ? shared.cone : shared.ok);
331}
332
333void renameCommand(redisClient *c) {
334 renameGenericCommand(c,0);
335}
336
337void renamenxCommand(redisClient *c) {
338 renameGenericCommand(c,1);
339}
340
341void moveCommand(redisClient *c) {
342 robj *o;
343 redisDb *src, *dst;
344 int srcid;
345
346 /* Obtain source and target DB pointers */
347 src = c->db;
348 srcid = c->db->id;
349 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
350 addReply(c,shared.outofrangeerr);
351 return;
352 }
353 dst = c->db;
354 selectDb(c,srcid); /* Back to the source DB */
355
356 /* If the user is moving using as target the same
357 * DB as the source DB it is probably an error. */
358 if (src == dst) {
359 addReply(c,shared.sameobjecterr);
360 return;
361 }
362
363 /* Check if the element exists and get a reference */
364 o = lookupKeyWrite(c->db,c->argv[1]);
365 if (!o) {
366 addReply(c,shared.czero);
367 return;
368 }
369
370 /* Try to add the element to the target DB */
e2641e09 371 if (dbAdd(dst,c->argv[1],o) == REDIS_ERR) {
372 addReply(c,shared.czero);
373 return;
374 }
375 incrRefCount(o);
376
377 /* OK! key moved, free the entry in the source DB */
378 dbDelete(src,c->argv[1]);
379 server.dirty++;
380 addReply(c,shared.cone);
381}
382
383/*-----------------------------------------------------------------------------
384 * Expires API
385 *----------------------------------------------------------------------------*/
386
387int removeExpire(redisDb *db, robj *key) {
388 /* An expire may only be removed if there is a corresponding entry in the
389 * main dict. Otherwise, the key will never be freed. */
390 redisAssert(dictFind(db->dict,key->ptr) != NULL);
a539d29a 391 return dictDelete(db->expires,key->ptr) == DICT_OK;
e2641e09 392}
393
0cf5b7b5 394void setExpire(redisDb *db, robj *key, time_t when) {
e2641e09 395 dictEntry *de;
396
397 /* Reuse the sds from the main dict in the expire dict */
0cf5b7b5 398 de = dictFind(db->dict,key->ptr);
399 redisAssert(de != NULL);
400 dictReplace(db->expires,dictGetEntryKey(de),(void*)when);
e2641e09 401}
402
403/* Return the expire time of the specified key, or -1 if no expire
404 * is associated with this key (i.e. the key is non volatile) */
405time_t getExpire(redisDb *db, robj *key) {
406 dictEntry *de;
407
408 /* No expire? return ASAP */
409 if (dictSize(db->expires) == 0 ||
410 (de = dictFind(db->expires,key->ptr)) == NULL) return -1;
411
412 /* The entry was found in the expire dict, this means it should also
413 * be present in the main dict (safety check). */
414 redisAssert(dictFind(db->dict,key->ptr) != NULL);
415 return (time_t) dictGetEntryVal(de);
416}
417
bcf2995c 418/* Propagate expires into slaves and the AOF file.
419 * When a key expires in the master, a DEL operation for this key is sent
420 * to all the slaves and the AOF file if enabled.
421 *
422 * This way the key expiry is centralized in one place, and since both
423 * AOF and the master->slave link guarantee operation ordering, everything
424 * will be consistent even if we allow write operations against expiring
425 * keys. */
426void propagateExpire(redisDb *db, robj *key) {
427 struct redisCommand *cmd;
428 robj *argv[2];
429
430 cmd = lookupCommand("del");
431 argv[0] = createStringObject("DEL",3);
432 argv[1] = key;
433 incrRefCount(key);
434
435 if (server.appendonly)
436 feedAppendOnlyFile(cmd,db->id,argv,2);
437 if (listLength(server.slaves))
438 replicationFeedSlaves(server.slaves,db->id,argv,2);
439
c25a5d3b 440 decrRefCount(argv[0]);
441 decrRefCount(argv[1]);
bcf2995c 442}
443
e2641e09 444int expireIfNeeded(redisDb *db, robj *key) {
445 time_t when = getExpire(db,key);
bcf2995c 446
447 /* If we are running in the context of a slave, return ASAP:
448 * the slave key expiration is controlled by the master that will
449 * send us synthesized DEL operations for expired keys.
450 *
451 * Still we try to return the right information to the caller,
452 * that is, 0 if we think the key should be still valid, 1 if
453 * we think the key is expired at this time. */
454 if (server.masterhost != NULL) {
455 return time(NULL) > when;
456 }
457
e2641e09 458 if (when < 0) return 0;
459
460 /* Return when this key has not expired */
461 if (time(NULL) <= when) return 0;
462
463 /* Delete the key */
464 server.stat_expiredkeys++;
465 server.dirty++;
bcf2995c 466 propagateExpire(db,key);
e2641e09 467 return dbDelete(db,key);
468}
469
470/*-----------------------------------------------------------------------------
471 * Expires Commands
472 *----------------------------------------------------------------------------*/
473
474void expireGenericCommand(redisClient *c, robj *key, robj *param, long offset) {
475 dictEntry *de;
476 time_t seconds;
477
478 if (getLongFromObjectOrReply(c, param, &seconds, NULL) != REDIS_OK) return;
479
480 seconds -= offset;
481
482 de = dictFind(c->db->dict,key->ptr);
483 if (de == NULL) {
484 addReply(c,shared.czero);
485 return;
486 }
487 if (seconds <= 0) {
488 if (dbDelete(c->db,key)) server.dirty++;
489 addReply(c, shared.cone);
b7a8daef 490 touchWatchedKey(c->db,key);
e2641e09 491 return;
492 } else {
493 time_t when = time(NULL)+seconds;
0cf5b7b5 494 setExpire(c->db,key,when);
495 addReply(c,shared.cone);
496 touchWatchedKey(c->db,key);
497 server.dirty++;
e2641e09 498 return;
499 }
500}
501
502void expireCommand(redisClient *c) {
503 expireGenericCommand(c,c->argv[1],c->argv[2],0);
504}
505
506void expireatCommand(redisClient *c) {
507 expireGenericCommand(c,c->argv[1],c->argv[2],time(NULL));
508}
509
510void ttlCommand(redisClient *c) {
c91abdcd 511 time_t expire, ttl = -1;
e2641e09 512
513 expire = getExpire(c->db,c->argv[1]);
514 if (expire != -1) {
c91abdcd 515 ttl = (expire-time(NULL));
e2641e09 516 if (ttl < 0) ttl = -1;
517 }
c91abdcd 518 addReplyLongLong(c,(long long)ttl);
e2641e09 519}
a539d29a 520
521void persistCommand(redisClient *c) {
522 dictEntry *de;
523
524 de = dictFind(c->db->dict,c->argv[1]->ptr);
525 if (de == NULL) {
526 addReply(c,shared.czero);
527 } else {
1fb4e8de 528 if (removeExpire(c->db,c->argv[1])) {
a539d29a 529 addReply(c,shared.cone);
1fb4e8de 530 server.dirty++;
531 } else {
a539d29a 532 addReply(c,shared.czero);
1fb4e8de 533 }
a539d29a 534 }
535}