db.c 17.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
#include "redis.h"

#include <signal.h>

/*-----------------------------------------------------------------------------
 * C-level DB API
 *----------------------------------------------------------------------------*/

robj *lookupKey(redisDb *db, robj *key) {
    dictEntry *de = dictFind(db->dict,key->ptr);
    if (de) {
        robj *val = dictGetEntryVal(de);

14 15 16 17 18
        /* Update the access time for the aging algorithm.
         * Don't do it if we have a saving child, as this will trigger
         * a copy on write madness. */
        if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1)
            val->lru = server.lruclock;
19

20 21 22 23 24
        if (server.ds_enabled &&
            cacheScheduleIOGetFlags(db,key) & REDIS_IO_SAVEINPROG)
        {
            /* There is a save in progress for this object!
             * Wait for it to get out. */
25
            waitEmptyIOJobsQueue();
A
antirez 已提交
26
            processAllPendingIOJobs();
27
            redisAssert(!(cacheScheduleIOGetFlags(db,key) & REDIS_IO_SAVEINPROG));
28
        }
29
        server.stat_keyspace_hits++;
30 31
        return val;
    } else {
32 33 34 35 36
        time_t expire;
        robj *val;

        /* Key not found in the in memory hash table, but if disk store is
         * enabled we may have this key on disk. If so load it in memory
37
         * in a blocking way. */
38
        if (server.ds_enabled && cacheKeyMayExist(db,key)) {
39 40 41 42 43 44 45 46 47 48
            if (cacheScheduleIOGetFlags(db,key) &
                 (REDIS_IO_SAVE|REDIS_IO_SAVEINPROG))
            {
                /* There is a save in progress for this object!
                 * Wait for it to get out. */
                waitEmptyIOJobsQueue();
                processAllPendingIOJobs();
                redisAssert((cacheScheduleIOGetFlags(db,key) & (REDIS_IO_SAVE|REDIS_IO_SAVEINPROG)) == 0);
            }

A
antirez 已提交
49 50
            redisLog(REDIS_DEBUG,"Force loading key %s via lookup",
                key->ptr);
51 52 53 54 55 56 57 58 59
            val = dsGet(db,key,&expire);
            if (val) {
                int retval = dbAdd(db,key,val);
                redisAssert(retval == REDIS_OK);
                if (expire != -1) setExpire(db,key,expire);
                server.stat_keyspace_hits++;
                return val;
            }
        }
60
        server.stat_keyspace_misses++;
61 62 63 64 65 66 67 68 69 70
        return NULL;
    }
}

robj *lookupKeyRead(redisDb *db, robj *key) {
    expireIfNeeded(db,key);
    return lookupKey(db,key);
}

robj *lookupKeyWrite(redisDb *db, robj *key) {
71
    expireIfNeeded(db,key);
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    return lookupKey(db,key);
}

robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply) {
    robj *o = lookupKeyRead(c->db, key);
    if (!o) addReply(c,reply);
    return o;
}

robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply) {
    robj *o = lookupKeyWrite(c->db, key);
    if (!o) addReply(c,reply);
    return o;
}

/* Add the key to the DB. If the key already exists REDIS_ERR is returned,
 * otherwise REDIS_OK is returned, and the caller should increment the
 * refcount of 'val'. */
int dbAdd(redisDb *db, robj *key, robj *val) {
    /* Perform a lookup before adding the key, as we need to copy the
     * key value. */
    if (dictFind(db->dict, key->ptr) != NULL) {
        return REDIS_ERR;
    } else {
        sds copy = sdsdup(key->ptr);
        dictAdd(db->dict, copy, val);
98 99 100
        if (server.ds_enabled) {
            /* FIXME: remove entry from negative cache */
        }
101 102 103 104 105 106 107 108 109
        return REDIS_OK;
    }
}

/* If the key does not exist, this is just like dbAdd(). Otherwise
 * the value associated to the key is replaced with the new one.
 *
 * On update (key already existed) 0 is returned. Otherwise 1. */
int dbReplace(redisDb *db, robj *key, robj *val) {
A
antirez 已提交
110 111 112
    robj *oldval;

    if ((oldval = dictFetchValue(db->dict,key->ptr)) == NULL) {
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
        sds copy = sdsdup(key->ptr);
        dictAdd(db->dict, copy, val);
        return 1;
    } else {
        dictReplace(db->dict, key->ptr, val);
        return 0;
    }
}

int dbExists(redisDb *db, robj *key) {
    return dictFind(db->dict,key->ptr) != NULL;
}

/* Return a random key, in form of a Redis object.
 * If there are no keys, NULL is returned.
 *
 * The function makes sure to return keys not already expired. */
robj *dbRandomKey(redisDb *db) {
    struct dictEntry *de;

    while(1) {
        sds key;
        robj *keyobj;

        de = dictGetRandomKey(db->dict);
        if (de == NULL) return NULL;

        key = dictGetEntryKey(de);
        keyobj = createStringObject(key,sdslen(key));
        if (dictFind(db->expires,key)) {
            if (expireIfNeeded(db,keyobj)) {
                decrRefCount(keyobj);
                continue; /* search for another key. This expired. */
            }
        }
        return keyobj;
    }
}

/* Delete a key, value, and associated expiration entry if any, from the DB */
int dbDelete(redisDb *db, robj *key) {
A
antirez 已提交
154 155 156
    /* If diskstore is enabled make sure to awake waiting clients for this key
     * as it is not really useful to wait for a key already deleted to be
     * loaded from disk. */
157 158
    if (server.ds_enabled) handleClientsBlockedOnSwappedKey(db,key);

159 160
    /* FIXME: we should mark this key as non existing on disk in the negative
     * cache. */
161

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
    /* Deleting an entry from the expires dict will not free the sds of
     * the key, because it is shared with the main dictionary. */
    if (dictSize(db->expires) > 0) dictDelete(db->expires,key->ptr);
    return dictDelete(db->dict,key->ptr) == DICT_OK;
}

/* Empty the whole database */
long long emptyDb() {
    int j;
    long long removed = 0;

    for (j = 0; j < server.dbnum; j++) {
        removed += dictSize(server.db[j].dict);
        dictEmpty(server.db[j].dict);
        dictEmpty(server.db[j].expires);
    }
    return removed;
}

int selectDb(redisClient *c, int id) {
    if (id < 0 || id >= server.dbnum)
        return REDIS_ERR;
    c->db = &server.db[id];
    return REDIS_OK;
}

188 189 190 191 192 193 194 195 196 197 198 199
/*-----------------------------------------------------------------------------
 * Hooks for key space changes.
 *
 * Every time a key in the database is modified the function
 * signalModifiedKey() is called.
 *
 * Every time a DB is flushed the function signalFlushDb() is called.
 *----------------------------------------------------------------------------*/

void signalModifiedKey(redisDb *db, robj *key) {
    touchWatchedKey(db,key);
    if (server.ds_enabled)
200
        cacheScheduleIO(db,key,REDIS_IO_SAVE);
201 202 203 204 205 206 207 208
}

void signalFlushedDb(int dbid) {
    touchWatchedKeysOnFlush(dbid);
    if (server.ds_enabled)
        dsFlushDb(dbid);
}

209 210 211 212 213 214
/*-----------------------------------------------------------------------------
 * Type agnostic commands operating on the key space
 *----------------------------------------------------------------------------*/

void flushdbCommand(redisClient *c) {
    server.dirty += dictSize(c->db->dict);
215
    signalFlushedDb(c->db->id);
216 217 218 219 220 221
    dictEmpty(c->db->dict);
    dictEmpty(c->db->expires);
    addReply(c,shared.ok);
}

void flushallCommand(redisClient *c) {
222
    signalFlushedDb(-1);
223 224 225 226 227 228 229 230 231 232 233 234 235 236
    server.dirty += emptyDb();
    addReply(c,shared.ok);
    if (server.bgsavechildpid != -1) {
        kill(server.bgsavechildpid,SIGKILL);
        rdbRemoveTempFile(server.bgsavechildpid);
    }
    rdbSave(server.dbfilename);
    server.dirty++;
}

void delCommand(redisClient *c) {
    int deleted = 0, j;

    for (j = 1; j < c->argc; j++) {
237 238 239 240 241
        if (server.ds_enabled) {
            lookupKeyRead(c->db,c->argv[j]);
            /* FIXME: this can be optimized a lot, no real need to load
             * a possibly huge value. */
        }
242
        if (dbDelete(c->db,c->argv[j])) {
243
            signalModifiedKey(c->db,c->argv[j]);
244 245
            server.dirty++;
            deleted++;
246 247 248 249
        } else if (server.ds_enabled) {
            if (cacheKeyMayExist(c->db,c->argv[j]) &&
                dsExists(c->db,c->argv[j]))
            {
250
                cacheScheduleIO(c->db,c->argv[j],REDIS_IO_SAVE);
251 252
                deleted = 1;
            }
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
        }
    }
    addReplyLongLong(c,deleted);
}

void existsCommand(redisClient *c) {
    expireIfNeeded(c->db,c->argv[1]);
    if (dbExists(c->db,c->argv[1])) {
        addReply(c, shared.cone);
    } else {
        addReply(c, shared.czero);
    }
}

void selectCommand(redisClient *c) {
    int id = atoi(c->argv[1]->ptr);

    if (selectDb(c,id) == REDIS_ERR) {
271
        addReplyError(c,"invalid DB index");
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
    } else {
        addReply(c,shared.ok);
    }
}

void randomkeyCommand(redisClient *c) {
    robj *key;

    if ((key = dbRandomKey(c->db)) == NULL) {
        addReply(c,shared.nullbulk);
        return;
    }

    addReplyBulk(c,key);
    decrRefCount(key);
}

void keysCommand(redisClient *c) {
    dictIterator *di;
    dictEntry *de;
    sds pattern = c->argv[1]->ptr;
A
antirez 已提交
293
    int plen = sdslen(pattern), allkeys;
294
    unsigned long numkeys = 0;
295
    void *replylen = addDeferredMultiBulkLength(c);
296 297

    di = dictGetIterator(c->db->dict);
A
antirez 已提交
298
    allkeys = (pattern[0] == '*' && pattern[1] == '\0');
299 300 301 302
    while((de = dictNext(di)) != NULL) {
        sds key = dictGetEntryKey(de);
        robj *keyobj;

A
antirez 已提交
303
        if (allkeys || stringmatchlen(pattern,plen,key,sdslen(key),0)) {
304 305 306 307 308 309 310 311 312
            keyobj = createStringObject(key,sdslen(key));
            if (expireIfNeeded(c->db,keyobj) == 0) {
                addReplyBulk(c,keyobj);
                numkeys++;
            }
            decrRefCount(keyobj);
        }
    }
    dictReleaseIterator(di);
313
    setDeferredMultiBulkLength(c,replylen,numkeys);
314 315 316
}

void dbsizeCommand(redisClient *c) {
317
    addReplyLongLong(c,dictSize(c->db->dict));
318 319 320
}

void lastsaveCommand(redisClient *c) {
321
    addReplyLongLong(c,server.lastsave);
322 323 324 325 326 327 328 329
}

void typeCommand(redisClient *c) {
    robj *o;
    char *type;

    o = lookupKeyRead(c->db,c->argv[1]);
    if (o == NULL) {
330
        type = "none";
331 332
    } else {
        switch(o->type) {
333 334 335 336 337 338
        case REDIS_STRING: type = "string"; break;
        case REDIS_LIST: type = "list"; break;
        case REDIS_SET: type = "set"; break;
        case REDIS_ZSET: type = "zset"; break;
        case REDIS_HASH: type = "hash"; break;
        default: type = "unknown"; break;
339 340
        }
    }
341
    addReplyStatus(c,type);
342 343 344 345
}

void saveCommand(redisClient *c) {
    if (server.bgsavechildpid != -1) {
346
        addReplyError(c,"Background save already in progress");
347 348 349 350 351 352 353 354 355 356 357
        return;
    }
    if (rdbSave(server.dbfilename) == REDIS_OK) {
        addReply(c,shared.ok);
    } else {
        addReply(c,shared.err);
    }
}

void bgsaveCommand(redisClient *c) {
    if (server.bgsavechildpid != -1) {
358
        addReplyError(c,"Background save already in progress");
359 360 361
        return;
    }
    if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
362
        addReplyStatus(c,"Background saving started");
363 364 365 366 367 368 369 370
    } else {
        addReply(c,shared.err);
    }
}

void shutdownCommand(redisClient *c) {
    if (prepareForShutdown() == REDIS_OK)
        exit(0);
371
    addReplyError(c,"Errors trying to SHUTDOWN. Check logs.");
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
}

void renameGenericCommand(redisClient *c, int nx) {
    robj *o;

    /* To use the same key as src and dst is probably an error */
    if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
        addReply(c,shared.sameobjecterr);
        return;
    }

    if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
        return;

    incrRefCount(o);
    if (dbAdd(c->db,c->argv[2],o) == REDIS_ERR) {
        if (nx) {
            decrRefCount(o);
            addReply(c,shared.czero);
            return;
        }
        dbReplace(c->db,c->argv[2],o);
    }
    dbDelete(c->db,c->argv[1]);
396 397
    signalModifiedKey(c->db,c->argv[1]);
    signalModifiedKey(c->db,c->argv[2]);
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
    server.dirty++;
    addReply(c,nx ? shared.cone : shared.ok);
}

void renameCommand(redisClient *c) {
    renameGenericCommand(c,0);
}

void renamenxCommand(redisClient *c) {
    renameGenericCommand(c,1);
}

void moveCommand(redisClient *c) {
    robj *o;
    redisDb *src, *dst;
    int srcid;

    /* Obtain source and target DB pointers */
    src = c->db;
    srcid = c->db->id;
    if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
        addReply(c,shared.outofrangeerr);
        return;
    }
    dst = c->db;
    selectDb(c,srcid); /* Back to the source DB */

    /* If the user is moving using as target the same
     * DB as the source DB it is probably an error. */
    if (src == dst) {
        addReply(c,shared.sameobjecterr);
        return;
    }

    /* Check if the element exists and get a reference */
    o = lookupKeyWrite(c->db,c->argv[1]);
    if (!o) {
        addReply(c,shared.czero);
        return;
    }

    /* Try to add the element to the target DB */
    if (dbAdd(dst,c->argv[1],o) == REDIS_ERR) {
        addReply(c,shared.czero);
        return;
    }
    incrRefCount(o);

    /* OK! key moved, free the entry in the source DB */
    dbDelete(src,c->argv[1]);
    server.dirty++;
    addReply(c,shared.cone);
}

/*-----------------------------------------------------------------------------
 * Expires API
 *----------------------------------------------------------------------------*/

int removeExpire(redisDb *db, robj *key) {
    /* An expire may only be removed if there is a corresponding entry in the
     * main dict. Otherwise, the key will never be freed. */
    redisAssert(dictFind(db->dict,key->ptr) != NULL);
A
antirez 已提交
460
    return dictDelete(db->expires,key->ptr) == DICT_OK;
461 462
}

463
void setExpire(redisDb *db, robj *key, time_t when) {
464 465 466
    dictEntry *de;

    /* Reuse the sds from the main dict in the expire dict */
467 468 469
    de = dictFind(db->dict,key->ptr);
    redisAssert(de != NULL);
    dictReplace(db->expires,dictGetEntryKey(de),(void*)when);
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
}

/* Return the expire time of the specified key, or -1 if no expire
 * is associated with this key (i.e. the key is non volatile) */
time_t getExpire(redisDb *db, robj *key) {
    dictEntry *de;

    /* No expire? return ASAP */
    if (dictSize(db->expires) == 0 ||
       (de = dictFind(db->expires,key->ptr)) == NULL) return -1;

    /* The entry was found in the expire dict, this means it should also
     * be present in the main dict (safety check). */
    redisAssert(dictFind(db->dict,key->ptr) != NULL);
    return (time_t) dictGetEntryVal(de);
}

487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
/* Propagate expires into slaves and the AOF file.
 * When a key expires in the master, a DEL operation for this key is sent
 * to all the slaves and the AOF file if enabled.
 *
 * This way the key expiry is centralized in one place, and since both
 * AOF and the master->slave link guarantee operation ordering, everything
 * will be consistent even if we allow write operations against expiring
 * keys. */
void propagateExpire(redisDb *db, robj *key) {
    robj *argv[2];

    argv[0] = createStringObject("DEL",3);
    argv[1] = key;
    incrRefCount(key);

    if (server.appendonly)
503
        feedAppendOnlyFile(server.delCommand,db->id,argv,2);
504 505 506
    if (listLength(server.slaves))
        replicationFeedSlaves(server.slaves,db->id,argv,2);

507 508
    decrRefCount(argv[0]);
    decrRefCount(argv[1]);
509 510
}

511 512
int expireIfNeeded(redisDb *db, robj *key) {
    time_t when = getExpire(db,key);
513 514 515 516 517 518 519 520 521 522 523 524

    /* If we are running in the context of a slave, return ASAP:
     * the slave key expiration is controlled by the master that will
     * send us synthesized DEL operations for expired keys.
     *
     * Still we try to return the right information to the caller, 
     * that is, 0 if we think the key should be still valid, 1 if
     * we think the key is expired at this time. */
    if (server.masterhost != NULL) {
        return time(NULL) > when;
    }

525 526 527 528 529 530 531
    if (when < 0) return 0;

    /* Return when this key has not expired */
    if (time(NULL) <= when) return 0;

    /* Delete the key */
    server.stat_expiredkeys++;
532
    propagateExpire(db,key);
533 534 535 536 537 538 539 540 541
    return dbDelete(db,key);
}

/*-----------------------------------------------------------------------------
 * Expires Commands
 *----------------------------------------------------------------------------*/

void expireGenericCommand(redisClient *c, robj *key, robj *param, long offset) {
    dictEntry *de;
542
    long seconds;
543 544 545 546 547 548 549 550 551 552 553 554 555

    if (getLongFromObjectOrReply(c, param, &seconds, NULL) != REDIS_OK) return;

    seconds -= offset;

    de = dictFind(c->db->dict,key->ptr);
    if (de == NULL) {
        addReply(c,shared.czero);
        return;
    }
    if (seconds <= 0) {
        if (dbDelete(c->db,key)) server.dirty++;
        addReply(c, shared.cone);
556
        signalModifiedKey(c->db,key);
557 558 559
        return;
    } else {
        time_t when = time(NULL)+seconds;
560 561
        setExpire(c->db,key,when);
        addReply(c,shared.cone);
562
        signalModifiedKey(c->db,key);
563
        server.dirty++;
564 565 566 567 568 569 570 571 572 573 574 575 576
        return;
    }
}

void expireCommand(redisClient *c) {
    expireGenericCommand(c,c->argv[1],c->argv[2],0);
}

void expireatCommand(redisClient *c) {
    expireGenericCommand(c,c->argv[1],c->argv[2],time(NULL));
}

void ttlCommand(redisClient *c) {
577
    time_t expire, ttl = -1;
578 579 580

    expire = getExpire(c->db,c->argv[1]);
    if (expire != -1) {
581
        ttl = (expire-time(NULL));
582 583
        if (ttl < 0) ttl = -1;
    }
584
    addReplyLongLong(c,(long long)ttl);
585
}
A
antirez 已提交
586 587 588 589 590 591 592 593

void persistCommand(redisClient *c) {
    dictEntry *de;

    de = dictFind(c->db->dict,c->argv[1]->ptr);
    if (de == NULL) {
        addReply(c,shared.czero);
    } else {
A
antirez 已提交
594
        if (removeExpire(c->db,c->argv[1])) {
A
antirez 已提交
595
            addReply(c,shared.cone);
A
antirez 已提交
596 597
            server.dirty++;
        } else {
A
antirez 已提交
598
            addReply(c,shared.czero);
A
antirez 已提交
599
        }
A
antirez 已提交
600 601
    }
}