db.c 24.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/*
 * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of Redis nor the names of its contributors may be used
 *     to endorse or promote products derived from this software without
 *     specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

30 31 32
#include "redis.h"

#include <signal.h>
33
#include <ctype.h>
34

35 36 37
void SlotToKeyAdd(robj *key);
void SlotToKeyDel(robj *key);

38 39 40 41 42 43 44
/*-----------------------------------------------------------------------------
 * C-level DB API
 *----------------------------------------------------------------------------*/

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

G
guiquanz 已提交
47
        /* Update the access time for the ageing algorithm.
48 49
         * Don't do it if we have a saving child, as this will trigger
         * a copy on write madness. */
A
antirez 已提交
50
        if (server.rdb_child_pid == -1 && server.aof_child_pid == -1)
51
            val->lru = server.lruclock;
52 53 54 55 56 57 58
        return val;
    } else {
        return NULL;
    }
}

robj *lookupKeyRead(redisDb *db, robj *key) {
59 60
    robj *val;

61
    expireIfNeeded(db,key);
62 63 64 65 66 67
    val = lookupKey(db,key);
    if (val == NULL)
        server.stat_keyspace_misses++;
    else
        server.stat_keyspace_hits++;
    return val;
68 69 70
}

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
    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;
}

87
/* Add the key to the DB. It's up to the caller to increment the reference
G
guiquanz 已提交
88
 * counter of the value if needed.
89 90 91 92 93 94
 *
 * 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);

95
    redisAssertWithInfo(NULL,key,retval == REDIS_OK);
96 97 98 99 100 101 102 103 104 105
 }

/* 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);
    
106
    redisAssertWithInfo(NULL,key,de != NULL);
107
    dictReplace(db->dict, key->ptr, val);
108 109
}

110 111
/* 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.
112
 *
113 114 115 116 117 118
 * 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);
119
    } else {
120
        dbOverwrite(db,key,val);
121
    }
122 123
    incrRefCount(val);
    removeExpire(db,key);
124
    signalModifiedKey(db,key);
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
}

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;

145
        key = dictGetKey(de);
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
        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);
162 163 164 165 166
    if (dictDelete(db->dict,key->ptr) == DICT_OK) {
        return 1;
    } else {
        return 0;
    }
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
}

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 200 201 202 203 204
/*-----------------------------------------------------------------------------
 * 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);
}

205 206 207 208 209 210
/*-----------------------------------------------------------------------------
 * Type agnostic commands operating on the key space
 *----------------------------------------------------------------------------*/

void flushdbCommand(redisClient *c) {
    server.dirty += dictSize(c->db->dict);
211
    signalFlushedDb(c->db->id);
212 213 214 215 216 217
    dictEmpty(c->db->dict);
    dictEmpty(c->db->expires);
    addReply(c,shared.ok);
}

void flushallCommand(redisClient *c) {
218
    signalFlushedDb(-1);
219 220
    server.dirty += emptyDb();
    addReply(c,shared.ok);
A
antirez 已提交
221
    if (server.rdb_child_pid != -1) {
222
        kill(server.rdb_child_pid,SIGUSR1);
A
antirez 已提交
223
        rdbRemoveTempFile(server.rdb_child_pid);
224
    }
225 226 227 228
    if (server.saveparamslen > 0) {
        /* Normally rdbSave() will reset dirty, but we don't want this here
         * as otherwise FLUSHALL will not be replicated nor put into the AOF. */
        int saved_dirty = server.dirty;
A
antirez 已提交
229
        rdbSave(server.rdb_filename);
230 231
        server.dirty = saved_dirty;
    }
232 233 234 235 236 237 238 239
    server.dirty++;
}

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

    for (j = 1; j < c->argc; j++) {
        if (dbDelete(c->db,c->argv[j])) {
240
            signalModifiedKey(c->db,c->argv[j]);
241 242
            notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,
                "del",c->argv[j],c->db->id);
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
            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) {
260 261 262 263 264
    long id;

    if (getLongFromObjectOrReply(c, c->argv[1], &id,
        "invalid DB index") != REDIS_OK)
        return;
265 266

    if (selectDb(c,id) == REDIS_ERR) {
267
        addReplyError(c,"invalid DB index");
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
    } 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 已提交
289
    int plen = sdslen(pattern), allkeys;
290
    unsigned long numkeys = 0;
291
    void *replylen = addDeferredMultiBulkLength(c);
292

293
    di = dictGetSafeIterator(c->db->dict);
A
antirez 已提交
294
    allkeys = (pattern[0] == '*' && pattern[1] == '\0');
295
    while((de = dictNext(di)) != NULL) {
296
        sds key = dictGetKey(de);
297 298
        robj *keyobj;

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

P
Pieter Noordhuis 已提交
312 313 314 315 316 317 318 319 320 321
void scanCallback(void *privdata, const dictEntry *de) {
    list *keys = (list *)privdata;
    sds key = dictGetKey(de);
    robj *kobj = createStringObject(key, sdslen(key));
    listAddNodeTail(keys, kobj);
}

void scanCommand(redisClient *c) {
    int rv;
    int i, j;
322
    char buf[REDIS_LONGSTR_SIZE];
P
Pieter Noordhuis 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
    list *keys = listCreate();
    listNode *ln, *ln_;
    unsigned long cursor = 0;
    long count = 1;
    sds pat;
    int patlen, patnoop = 1;

    /* Use sscanf because we need an *unsigned* long */
    rv = sscanf(c->argv[1]->ptr, "%lu", &cursor);
    if (rv != 1) {
        addReplyError(c, "invalid cursor");
        goto cleanup;
    }

    i = 2;
    while (i < c->argc) {
        j = c->argc - i;
        if (!strcasecmp(c->argv[i]->ptr, "count") && j >= 2) {
            if (getLongFromObjectOrReply(c, c->argv[i+1], &count, NULL) != REDIS_OK) {
                goto cleanup;
            }

            if (count < 1) {
                addReply(c,shared.syntaxerr);
                goto cleanup;
            }

            i += 2;
351
        } else if (!strcasecmp(c->argv[i]->ptr, "match") && j >= 2) {
P
Pieter Noordhuis 已提交
352 353 354
            pat = c->argv[i+1]->ptr;
            patlen = sdslen(pat);

A
antirez 已提交
355
            /* The pattern is a no-op if == "*" */
P
Pieter Noordhuis 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
            patnoop = (pat[0] == '*' && patlen == 1);

            i += 2;
        } else {
            addReply(c,shared.syntaxerr);
            goto cleanup;
        }
    }

    do {
        cursor = dictScan(c->db->dict, cursor, scanCallback, keys);
    } while (cursor && listLength(keys) < count);

    /* Filter keys */
    ln = listFirst(keys);
    while (ln) {
        robj *kobj = listNodeValue(ln);
        ln_ = listNextNode(ln);

        /* Keep key iff pattern matches and it hasn't expired */
        if ((patnoop || stringmatchlen(pat, patlen, kobj->ptr, sdslen(kobj->ptr), 0)) &&
            (expireIfNeeded(c->db, kobj) == 0))
        {
            /* Keep */
        } else {
            decrRefCount(kobj);
            listDelNode(keys, ln);
        }

        ln = ln_;
    }

    addReplyMultiBulkLen(c, 2);

    rv = snprintf(buf, sizeof(buf), "%lu", cursor);
    redisAssert(rv < sizeof(buf));
    addReplyBulkCBuffer(c, buf, rv);

    addReplyMultiBulkLen(c, listLength(keys));
    while ((ln = listFirst(keys)) != NULL) {
        robj *kobj = listNodeValue(ln);
        addReplyBulk(c, kobj);
        decrRefCount(kobj);
        listDelNode(keys, ln);
    }

cleanup:
    while ((ln = listFirst(keys)) != NULL) {
        robj *kobj = listNodeValue(ln);
        decrRefCount(kobj);
        listDelNode(keys, ln);
    }

    listRelease(keys);
}

412
void dbsizeCommand(redisClient *c) {
413
    addReplyLongLong(c,dictSize(c->db->dict));
414 415 416
}

void lastsaveCommand(redisClient *c) {
417
    addReplyLongLong(c,server.lastsave);
418 419 420 421 422 423 424 425
}

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

    o = lookupKeyRead(c->db,c->argv[1]);
    if (o == NULL) {
426
        type = "none";
427 428
    } else {
        switch(o->type) {
429 430 431 432 433 434
        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;
435 436
        }
    }
437
    addReplyStatus(c,type);
438 439 440
}

void shutdownCommand(redisClient *c) {
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
    int flags = 0;

    if (c->argc > 2) {
        addReply(c,shared.syntaxerr);
        return;
    } else if (c->argc == 2) {
        if (!strcasecmp(c->argv[1]->ptr,"nosave")) {
            flags |= REDIS_SHUTDOWN_NOSAVE;
        } else if (!strcasecmp(c->argv[1]->ptr,"save")) {
            flags |= REDIS_SHUTDOWN_SAVE;
        } else {
            addReply(c,shared.syntaxerr);
            return;
        }
    }
A
antirez 已提交
456 457 458 459 460 461
    /* SHUTDOWN can be called even while the server is in "loading" state.
     * When this happens we need to make sure no attempt is performed to save
     * the dataset on shutdown (otherwise it could overwrite the current DB
     * with half-read data). */
    if (server.loading)
        flags = (flags & ~REDIS_SHUTDOWN_SAVE) | REDIS_SHUTDOWN_NOSAVE;
462
    if (prepareForShutdown(flags) == REDIS_OK) exit(0);
463
    addReplyError(c,"Errors trying to SHUTDOWN. Check logs.");
464 465 466 467
}

void renameGenericCommand(redisClient *c, int nx) {
    robj *o;
468
    long long expire;
469 470 471 472 473 474 475 476 477 478 479

    /* 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);
480
    expire = getExpire(c->db,c->argv[1]);
481
    if (lookupKeyWrite(c->db,c->argv[2]) != NULL) {
482 483 484 485 486
        if (nx) {
            decrRefCount(o);
            addReply(c,shared.czero);
            return;
        }
A
antirez 已提交
487 488
        /* Overwrite: delete the old key before creating the new one
         * with the same name. */
489
        dbDelete(c->db,c->argv[2]);
490
    }
491 492
    dbAdd(c->db,c->argv[2],o);
    if (expire != -1) setExpire(c->db,c->argv[2],expire);
493
    dbDelete(c->db,c->argv[1]);
494 495
    signalModifiedKey(c->db,c->argv[1]);
    signalModifiedKey(c->db,c->argv[2]);
496 497 498 499
    notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"rename_from",
        c->argv[1],c->db->id);
    notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"rename_to",
        c->argv[2],c->db->id);
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
    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;
    }

541 542
    /* Return zero if the key already exists in the target DB */
    if (lookupKeyWrite(dst,c->argv[1]) != NULL) {
543 544 545
        addReply(c,shared.czero);
        return;
    }
546
    dbAdd(dst,c->argv[1],o);
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
    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. */
562
    redisAssertWithInfo(NULL,key,dictFind(db->dict,key->ptr) != NULL);
A
antirez 已提交
563
    return dictDelete(db->expires,key->ptr) == DICT_OK;
564 565
}

566 567
void setExpire(redisDb *db, robj *key, long long when) {
    dictEntry *kde, *de;
568 569

    /* Reuse the sds from the main dict in the expire dict */
570 571 572 573
    kde = dictFind(db->dict,key->ptr);
    redisAssertWithInfo(NULL,key,kde != NULL);
    de = dictReplaceRaw(db->expires,dictGetKey(kde));
    dictSetSignedIntegerVal(de,when);
574 575 576 577
}

/* 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) */
578
long long getExpire(redisDb *db, robj *key) {
579 580 581 582 583 584 585 586
    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). */
587
    redisAssertWithInfo(NULL,key,dictFind(db->dict,key->ptr) != NULL);
588
    return dictGetSignedIntegerVal(de);
589 590
}

591 592 593 594 595 596 597 598 599 600 601
/* 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];

602
    argv[0] = shared.del;
603
    argv[1] = key;
604 605
    incrRefCount(argv[0]);
    incrRefCount(argv[1]);
606

607
    if (server.aof_state != REDIS_AOF_OFF)
608
        feedAppendOnlyFile(server.delCommand,db->id,argv,2);
609
    replicationFeedSlaves(server.slaves,db->id,argv,2);
610

611 612
    decrRefCount(argv[0]);
    decrRefCount(argv[1]);
613 614
}

615
int expireIfNeeded(redisDb *db, robj *key) {
616
    long long when = getExpire(db,key);
617

618 619
    if (when < 0) return 0; /* No expire for this key */

620 621 622
    /* Don't expire anything while loading. It will be done later. */
    if (server.loading) return 0;

623 624 625 626 627 628 629 630
    /* 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) {
631
        return mstime() > when;
632 633
    }

634
    /* Return when this key has not expired */
635
    if (mstime() <= when) return 0;
636 637 638

    /* Delete the key */
    server.stat_expiredkeys++;
639
    propagateExpire(db,key);
640 641
    notifyKeyspaceEvent(REDIS_NOTIFY_EXPIRED,
        "expired",key,db->id);
642 643 644 645 646 647 648
    return dbDelete(db,key);
}

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

649 650 651 652 653 654
/* This is the generic command implementation for EXPIRE, PEXPIRE, EXPIREAT
 * and PEXPIREAT. Because the commad second argument may be relative or absolute
 * the "basetime" argument is used to signal what the base time is (either 0
 * for *AT variants of the command, or the current time for relative expires).
 *
 * unit is either UNIT_SECONDS or UNIT_MILLISECONDS, and is only used for
G
guiquanz 已提交
655
 * the argv[2] parameter. The basetime is always specified in milliseconds. */
656
void expireGenericCommand(redisClient *c, long long basetime, int unit) {
657
    robj *key = c->argv[1], *param = c->argv[2];
658
    long long when; /* unix time in milliseconds when the key will expire. */
659

660
    if (getLongLongFromObjectOrReply(c, param, &when, NULL) != REDIS_OK)
661
        return;
662

663 664
    if (unit == UNIT_SECONDS) when *= 1000;
    when += basetime;
665

666 667
    /* No key, return zero. */
    if (lookupKeyRead(c->db,key) == NULL) {
668 669 670
        addReply(c,shared.czero);
        return;
    }
671

672 673 674 675 676 677
    /* EXPIRE with negative TTL, or EXPIREAT with a timestamp into the past
     * should never be executed as a DEL when load the AOF or in the context
     * of a slave instance.
     *
     * Instead we take the other branch of the IF statement setting an expire
     * (possibly in the past) and wait for an explicit DEL from the master. */
678
    if (when <= mstime() && !server.loading && !server.masterhost) {
679 680
        robj *aux;

681
        redisAssertWithInfo(c,key,dbDelete(c->db,key));
682 683 684 685 686 687
        server.dirty++;

        /* Replicate/AOF this as an explicit DEL. */
        aux = createStringObject("DEL",3);
        rewriteClientCommandVector(c,2,aux,key);
        decrRefCount(aux);
688
        signalModifiedKey(c->db,key);
689
        notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",key,c->db->id);
690
        addReply(c, shared.cone);
691 692
        return;
    } else {
693
        setExpire(c->db,key,when);
694
        addReply(c,shared.cone);
695
        signalModifiedKey(c->db,key);
696
        notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"expire",key,c->db->id);
697
        server.dirty++;
698 699 700 701 702
        return;
    }
}

void expireCommand(redisClient *c) {
703
    expireGenericCommand(c,mstime(),UNIT_SECONDS);
704 705 706
}

void expireatCommand(redisClient *c) {
707
    expireGenericCommand(c,0,UNIT_SECONDS);
708 709
}

710
void pexpireCommand(redisClient *c) {
711
    expireGenericCommand(c,mstime(),UNIT_MILLISECONDS);
712
}
713

714
void pexpireatCommand(redisClient *c) {
715
    expireGenericCommand(c,0,UNIT_MILLISECONDS);
716 717 718 719
}

void ttlGenericCommand(redisClient *c, int output_ms) {
    long long expire, ttl = -1;
720

721
    /* If the key does not exist at all, return -2 */
A
antirez 已提交
722
    if (lookupKeyRead(c->db,c->argv[1]) == NULL) {
723 724 725 726 727
        addReplyLongLong(c,-2);
        return;
    }
    /* The key exists. Return -1 if it has no expire, or the actual
     * TTL value otherwise. */
A
antirez 已提交
728
    expire = getExpire(c->db,c->argv[1]);
729
    if (expire != -1) {
730
        ttl = expire-mstime();
A
antirez 已提交
731
        if (ttl < 0) ttl = 0;
732
    }
733 734 735
    if (ttl == -1) {
        addReplyLongLong(c,-1);
    } else {
736
        addReplyLongLong(c,output_ms ? ttl : ((ttl+500)/1000));
737
    }
738
}
A
antirez 已提交
739

740 741 742 743 744 745 746 747
void ttlCommand(redisClient *c) {
    ttlGenericCommand(c, 0);
}

void pttlCommand(redisClient *c) {
    ttlGenericCommand(c, 1);
}

A
antirez 已提交
748 749 750 751 752 753 754
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 已提交
755
        if (removeExpire(c->db,c->argv[1])) {
A
antirez 已提交
756
            addReply(c,shared.cone);
A
antirez 已提交
757 758
            server.dirty++;
        } else {
A
antirez 已提交
759
            addReply(c,shared.czero);
A
antirez 已提交
760
        }
A
antirez 已提交
761 762
    }
}
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780

/* -----------------------------------------------------------------------------
 * 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);
781
        keys[i++] = j;
782
    }
783
    *numkeys = i;
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
    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;
813
        return keys;
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
    } 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;
    }
831
    keys = zmalloc(sizeof(int)*num);
832 833 834 835
    for (i = 0; i < num; i++) keys[i] = 3+i;
    *numkeys = num;
    return keys;
}