db.c 19.2 KB
Newer Older
1 2 3 4
#include "redis.h"

#include <signal.h>

5 6 7
void SlotToKeyAdd(robj *key);
void SlotToKeyDel(robj *key);

8 9 10 11
/*-----------------------------------------------------------------------------
 * C-level DB API
 *----------------------------------------------------------------------------*/

A
antirez 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/* Important notes on lookup and disk store.
 *
 * When disk store is enabled on lookup we can have different cases.
 *
 * a) The key is in memory:
 *    - If the key is not in IO_SAVEINPROG state we can access it.
 *      As if it's just IO_SAVE this means we have the key in the IO queue
 *      but can't be accessed by the IO thread (it requires to be
 *      translated into an IO Job by the cache cron function.)
 *    - If the key is in IO_SAVEINPROG we can't touch the key and have
 *      to blocking wait completion of operations.
 * b) The key is not in memory:
 *    - If it's marked as non existing on disk as well (negative cache)
 *      we don't need to perform the disk access.
 *    - if the key MAY EXIST, but is not in memory, and it is marked as IO_SAVE
 *      then the key can only be a deleted one. As IO_SAVE keys are never
 *      evicted (dirty state), so the only possibility is that key was deleted.
 *    - if the key MAY EXIST we need to blocking load it.
 *      We check that the key is not in IO_SAVEINPROG state before accessing
 *      the disk object. If it is in this state, we wait.
 */

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

39 40 41 42 43
        /* 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;
44
        server.stat_keyspace_hits++;
45 46
        return val;
    } else {
47
        server.stat_keyspace_misses++;
48 49 50 51 52 53 54 55 56 57
        return NULL;
    }
}

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

robj *lookupKeyWrite(redisDb *db, robj *key) {
58
    expireIfNeeded(db,key);
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    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;
}

74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
/* Add the key to the DB. It's up to the caller to increment the reference
 * counte of the value if needed.
 *
 * The program is aborted if the key already exists. */
void dbAdd(redisDb *db, robj *key, robj *val) {
    sds copy = sdsdup(key->ptr);
    int retval = dictAdd(db->dict, copy, val);

    redisAssert(retval == REDIS_OK);
    if (server.cluster_enabled) SlotToKeyAdd(key);
 }

/* Overwrite an existing key with a new value. Incrementing the reference
 * count of the new value is up to the caller.
 * This function does not modify the expire time of the existing key.
 *
 * The program is aborted if the key was not already present. */
void dbOverwrite(redisDb *db, robj *key, robj *val) {
    struct dictEntry *de = dictFind(db->dict,key->ptr);
    
    redisAssert(de != NULL);
    dictReplace(db->dict, key->ptr, val);
96 97
}

98 99
/* High level Set operation. This function can be used in order to set
 * a key, whatever it was existing or not, to a new object.
100
 *
101 102 103 104 105 106
 * 1) The ref count of the value object is incremented.
 * 2) clients WATCHing for the destination key notified.
 * 3) The expire time of the key is reset (the key is made persistent). */
void setKey(redisDb *db, robj *key, robj *val) {
    if (lookupKeyWrite(db,key) == NULL) {
        dbAdd(db,key,val);
107
    } else {
108
        dbOverwrite(db,key,val);
109
    }
110 111 112
    incrRefCount(val);
    removeExpire(db,key);
    touchWatchedKey(db,key);
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
}

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) {
    /* 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);
150 151 152 153 154 155
    if (dictDelete(db->dict,key->ptr) == DICT_OK) {
        if (server.cluster_enabled) SlotToKeyDel(key);
        return 1;
    } else {
        return 0;
    }
156 157
}

158 159
/* Empty the whole database.
 * If diskstore is enabled this function will just flush the in-memory cache. */
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
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;
}

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
/*-----------------------------------------------------------------------------
 * 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);
}

void signalFlushedDb(int dbid) {
    touchWatchedKeysOnFlush(dbid);
}

196 197 198 199 200 201
/*-----------------------------------------------------------------------------
 * Type agnostic commands operating on the key space
 *----------------------------------------------------------------------------*/

void flushdbCommand(redisClient *c) {
    server.dirty += dictSize(c->db->dict);
202
    signalFlushedDb(c->db->id);
203 204 205 206 207 208
    dictEmpty(c->db->dict);
    dictEmpty(c->db->expires);
    addReply(c,shared.ok);
}

void flushallCommand(redisClient *c) {
209
    signalFlushedDb(-1);
210 211 212 213 214 215
    server.dirty += emptyDb();
    addReply(c,shared.ok);
    if (server.bgsavechildpid != -1) {
        kill(server.bgsavechildpid,SIGKILL);
        rdbRemoveTempFile(server.bgsavechildpid);
    }
A
antirez 已提交
216
    rdbSave(server.dbfilename);
217 218 219 220 221 222 223 224
    server.dirty++;
}

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

    for (j = 1; j < c->argc; j++) {
        if (dbDelete(c->db,c->argv[j])) {
225
            signalModifiedKey(c->db,c->argv[j]);
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
            server.dirty++;
            deleted++;
        }
    }
    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);

245
    if (server.cluster_enabled && id != 0) {
A
antirez 已提交
246 247 248
        addReplyError(c,"SELECT is not allowed in cluster mode");
        return;
    }
249
    if (selectDb(c,id) == REDIS_ERR) {
250
        addReplyError(c,"invalid DB index");
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
    } 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 已提交
272
    int plen = sdslen(pattern), allkeys;
273
    unsigned long numkeys = 0;
274
    void *replylen = addDeferredMultiBulkLength(c);
275 276

    di = dictGetIterator(c->db->dict);
A
antirez 已提交
277
    allkeys = (pattern[0] == '*' && pattern[1] == '\0');
278 279 280 281
    while((de = dictNext(di)) != NULL) {
        sds key = dictGetEntryKey(de);
        robj *keyobj;

A
antirez 已提交
282
        if (allkeys || stringmatchlen(pattern,plen,key,sdslen(key),0)) {
283 284 285 286 287 288 289 290 291
            keyobj = createStringObject(key,sdslen(key));
            if (expireIfNeeded(c->db,keyobj) == 0) {
                addReplyBulk(c,keyobj);
                numkeys++;
            }
            decrRefCount(keyobj);
        }
    }
    dictReleaseIterator(di);
292
    setDeferredMultiBulkLength(c,replylen,numkeys);
293 294 295
}

void dbsizeCommand(redisClient *c) {
296
    addReplyLongLong(c,dictSize(c->db->dict));
297 298 299
}

void lastsaveCommand(redisClient *c) {
300
    addReplyLongLong(c,server.lastsave);
301 302 303 304 305 306 307 308
}

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

    o = lookupKeyRead(c->db,c->argv[1]);
    if (o == NULL) {
309
        type = "none";
310 311
    } else {
        switch(o->type) {
312 313 314 315 316 317
        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;
318 319
        }
    }
320
    addReplyStatus(c,type);
321 322 323 324 325
}

void shutdownCommand(redisClient *c) {
    if (prepareForShutdown() == REDIS_OK)
        exit(0);
326
    addReplyError(c,"Errors trying to SHUTDOWN. Check logs.");
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
}

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);
342
    if (lookupKeyWrite(c->db,c->argv[2]) != NULL) {
343 344 345 346 347
        if (nx) {
            decrRefCount(o);
            addReply(c,shared.czero);
            return;
        }
348 349 350
        dbOverwrite(c->db,c->argv[2],o);
    } else {
        dbAdd(c->db,c->argv[2],o);
351 352
    }
    dbDelete(c->db,c->argv[1]);
353 354
    signalModifiedKey(c->db,c->argv[1]);
    signalModifiedKey(c->db,c->argv[2]);
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
    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;

A
antirez 已提交
372 373 374 375 376
    if (server.cluster_enabled) {
        addReplyError(c,"MOVE is not allowed in cluster mode");
        return;
    }

377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    /* 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;
    }

401 402
    /* Return zero if the key already exists in the target DB */
    if (lookupKeyWrite(dst,c->argv[1]) != NULL) {
403 404 405
        addReply(c,shared.czero);
        return;
    }
406
    dbAdd(dst,c->argv[1],o);
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
    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 已提交
423
    return dictDelete(db->expires,key->ptr) == DICT_OK;
424 425
}

426
void setExpire(redisDb *db, robj *key, time_t when) {
427 428 429
    dictEntry *de;

    /* Reuse the sds from the main dict in the expire dict */
430 431 432
    de = dictFind(db->dict,key->ptr);
    redisAssert(de != NULL);
    dictReplace(db->expires,dictGetEntryKey(de),(void*)when);
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
}

/* 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);
}

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
/* 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)
466
        feedAppendOnlyFile(server.delCommand,db->id,argv,2);
467 468 469
    if (listLength(server.slaves))
        replicationFeedSlaves(server.slaves,db->id,argv,2);

470 471
    decrRefCount(argv[0]);
    decrRefCount(argv[1]);
472 473
}

474 475
int expireIfNeeded(redisDb *db, robj *key) {
    time_t when = getExpire(db,key);
476

477 478
    if (when < 0) return 0; /* No expire for this key */

479 480 481
    /* Don't expire anything while loading. It will be done later. */
    if (server.loading) return 0;

482 483 484 485 486 487 488 489 490 491 492
    /* 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;
    }

493 494 495 496 497
    /* Return when this key has not expired */
    if (time(NULL) <= when) return 0;

    /* Delete the key */
    server.stat_expiredkeys++;
498
    propagateExpire(db,key);
499 500 501 502 503 504 505 506 507
    return dbDelete(db,key);
}

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

void expireGenericCommand(redisClient *c, robj *key, robj *param, long offset) {
    dictEntry *de;
508
    long seconds;
509 510 511 512 513 514 515 516 517 518

    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;
    }
519
    if (seconds <= 0 && !server.loading) {
520 521
        if (dbDelete(c->db,key)) server.dirty++;
        addReply(c, shared.cone);
522
        signalModifiedKey(c->db,key);
523 524 525
        return;
    } else {
        time_t when = time(NULL)+seconds;
526 527
        setExpire(c->db,key,when);
        addReply(c,shared.cone);
528
        signalModifiedKey(c->db,key);
529
        server.dirty++;
530 531 532 533 534 535 536 537 538 539 540 541 542
        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) {
543
    time_t expire, ttl = -1;
544 545 546

    expire = getExpire(c->db,c->argv[1]);
    if (expire != -1) {
547
        ttl = (expire-time(NULL));
548 549
        if (ttl < 0) ttl = -1;
    }
550
    addReplyLongLong(c,(long long)ttl);
551
}
A
antirez 已提交
552 553 554 555 556 557 558 559

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 已提交
560
        if (removeExpire(c->db,c->argv[1])) {
A
antirez 已提交
561
            addReply(c,shared.cone);
A
antirez 已提交
562 563
            server.dirty++;
        } else {
A
antirez 已提交
564
            addReply(c,shared.czero);
A
antirez 已提交
565
        }
A
antirez 已提交
566 567
    }
}
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585

/* -----------------------------------------------------------------------------
 * API to get key arguments from commands
 * ---------------------------------------------------------------------------*/

int *getKeysUsingCommandTable(struct redisCommand *cmd,robj **argv, int argc, int *numkeys) {
    int j, i = 0, last, *keys;
    REDIS_NOTUSED(argv);

    if (cmd->firstkey == 0) {
        *numkeys = 0;
        return NULL;
    }
    last = cmd->lastkey;
    if (last < 0) last = argc+last;
    keys = zmalloc(sizeof(int)*((last - cmd->firstkey)+1));
    for (j = cmd->firstkey; j <= last; j += cmd->keystep) {
        redisAssert(j < argc);
586
        keys[i++] = j;
587
    }
588
    *numkeys = i;
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
    return keys;
}

int *getKeysFromCommand(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
    if (cmd->getkeys_proc) {
        return cmd->getkeys_proc(cmd,argv,argc,numkeys,flags);
    } else {
        return getKeysUsingCommandTable(cmd,argv,argc,numkeys);
    }
}

void getKeysFreeResult(int *result) {
    zfree(result);
}

int *noPreloadGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
    if (flags & REDIS_GETKEYS_PRELOAD) {
        *numkeys = 0;
        return NULL;
    } else {
        return getKeysUsingCommandTable(cmd,argv,argc,numkeys);
    }
}

int *renameGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
    if (flags & REDIS_GETKEYS_PRELOAD) {
        int *keys = zmalloc(sizeof(int));
        *numkeys = 1;
        keys[0] = 1;
618
        return keys;
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
    } else {
        return getKeysUsingCommandTable(cmd,argv,argc,numkeys);
    }
}

int *zunionInterGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
    int i, num, *keys;
    REDIS_NOTUSED(cmd);
    REDIS_NOTUSED(flags);

    num = atoi(argv[2]->ptr);
    /* Sanity check. Don't return any key if the command is going to
     * reply with syntax error. */
    if (num > (argc-3)) {
        *numkeys = 0;
        return NULL;
    }
636
    keys = zmalloc(sizeof(int)*num);
637 638 639 640
    for (i = 0; i < num; i++) keys[i] = 3+i;
    *numkeys = num;
    return keys;
}
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657

/* Slot to Key API. This is used by Redis Cluster in order to obtain in
 * a fast way a key that belongs to a specified hash slot. This is useful
 * while rehashing the cluster. */
void SlotToKeyAdd(robj *key) {
    unsigned int hashslot = keyHashSlot(key->ptr,sdslen(key->ptr));

    zslInsert(server.cluster.slots_to_keys,hashslot,key);
    incrRefCount(key);
}

void SlotToKeyDel(robj *key) {
    unsigned int hashslot = keyHashSlot(key->ptr,sdslen(key->ptr));

    zslDelete(server.cluster.slots_to_keys,hashslot,key);
}

A
antirez 已提交
658
unsigned int GetKeysInSlot(unsigned int hashslot, robj **keys, unsigned int count) {
659 660
    zskiplistNode *n;
    zrangespec range;
A
antirez 已提交
661
    int j = 0;
662 663 664 665 666

    range.min = range.max = hashslot;
    range.minex = range.maxex = 0;
    
    n = zslFirstInRange(server.cluster.slots_to_keys, range);
A
antirez 已提交
667 668 669 670 671
    while(n && n->score == hashslot && count--) {
        keys[j++] = n->obj;
        n = n->level[0].forward;
    }
    return j;
672
}