1 /* 2 * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com> 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions are met: 7 * 8 * * Redistributions of source code must retain the above copyright notice, 9 * this list of conditions and the following disclaimer. 10 * * Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * * Neither the name of Redis nor the names of its contributors may be used 14 * to endorse or promote products derived from this software without 15 * specific prior written permission. 16 * 17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 18 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 21 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 27 * POSSIBILITY OF SUCH DAMAGE. 28 */ 29 30 #include "redis.h" 31 #include "cluster.h" 32 33 #include <signal.h> 34 #include <ctype.h> 35 36 void slotToKeyAdd(robj *key); 37 void slotToKeyDel(robj *key); 38 void slotToKeyFlush(void); 39 40 /*----------------------------------------------------------------------------- 41 * C-level DB API 42 *----------------------------------------------------------------------------*/ 43 44 robj *lookupKey(redisDb *db, robj *key) { 45 dictEntry *de = dictFind(db->dict,key->ptr); 46 if (de) { 47 robj *val = dictGetVal(de); 48 49 /* Update the access time for the ageing algorithm. 50 * Don't do it if we have a saving child, as this will trigger 51 * a copy on write madness. */ 52 if (server.rdb_child_pid == -1 && server.aof_child_pid == -1) 53 val->lru = LRU_CLOCK(); 54 return val; 55 } else { 56 return NULL; 57 } 58 } 59 60 robj *lookupKeyRead(redisDb *db, robj *key) { 61 robj *val; 62 63 expireIfNeeded(db,key); 64 val = lookupKey(db,key); 65 if (val == NULL) 66 server.stat_keyspace_misses++; 67 else 68 server.stat_keyspace_hits++; 69 return val; 70 } 71 72 robj *lookupKeyWrite(redisDb *db, robj *key) { 73 expireIfNeeded(db,key); 74 return lookupKey(db,key); 75 } 76 77 robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply) { 78 robj *o = lookupKeyRead(c->db, key); 79 if (!o) addReply(c,reply); 80 return o; 81 } 82 83 robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply) { 84 robj *o = lookupKeyWrite(c->db, key); 85 if (!o) addReply(c,reply); 86 return o; 87 } 88 89 /* Add the key to the DB. It's up to the caller to increment the reference 90 * counter of the value if needed. 91 * 92 * The program is aborted if the key already exists. */ 93 void dbAdd(redisDb *db, robj *key, robj *val) { 94 sds copy = sdsdup(key->ptr); 95 int retval = dictAdd(db->dict, copy, val); 96 97 redisAssertWithInfo(NULL,key,retval == REDIS_OK); 98 if (val->type == REDIS_LIST) signalListAsReady(db, key); 99 if (server.cluster_enabled) slotToKeyAdd(key); 100 } 101 102 /* Overwrite an existing key with a new value. Incrementing the reference 103 * count of the new value is up to the caller. 104 * This function does not modify the expire time of the existing key. 105 * 106 * The program is aborted if the key was not already present. */ 107 void dbOverwrite(redisDb *db, robj *key, robj *val) { 108 dictEntry *de = dictFind(db->dict,key->ptr); 109 110 redisAssertWithInfo(NULL,key,de != NULL); 111 dictReplace(db->dict, key->ptr, val); 112 } 113 114 /* High level Set operation. This function can be used in order to set 115 * a key, whatever it was existing or not, to a new object. 116 * 117 * 1) The ref count of the value object is incremented. 118 * 2) clients WATCHing for the destination key notified. 119 * 3) The expire time of the key is reset (the key is made persistent). */ 120 void setKey(redisDb *db, robj *key, robj *val) { 121 if (lookupKeyWrite(db,key) == NULL) { 122 dbAdd(db,key,val); 123 } else { 124 dbOverwrite(db,key,val); 125 } 126 incrRefCount(val); 127 removeExpire(db,key); 128 signalModifiedKey(db,key); 129 } 130 131 int dbExists(redisDb *db, robj *key) { 132 return dictFind(db->dict,key->ptr) != NULL; 133 } 134 135 /* Return a random key, in form of a Redis object. 136 * If there are no keys, NULL is returned. 137 * 138 * The function makes sure to return keys not already expired. */ 139 robj *dbRandomKey(redisDb *db) { 140 dictEntry *de; 141 142 while(1) { 143 sds key; 144 robj *keyobj; 145 146 de = dictGetRandomKey(db->dict); 147 if (de == NULL) return NULL; 148 149 key = dictGetKey(de); 150 keyobj = createStringObject(key,sdslen(key)); 151 if (dictFind(db->expires,key)) { 152 if (expireIfNeeded(db,keyobj)) { 153 decrRefCount(keyobj); 154 continue; /* search for another key. This expired. */ 155 } 156 } 157 return keyobj; 158 } 159 } 160 161 /* Delete a key, value, and associated expiration entry if any, from the DB */ 162 int dbDelete(redisDb *db, robj *key) { 163 /* Deleting an entry from the expires dict will not free the sds of 164 * the key, because it is shared with the main dictionary. */ 165 if (dictSize(db->expires) > 0) dictDelete(db->expires,key->ptr); 166 if (dictDelete(db->dict,key->ptr) == DICT_OK) { 167 if (server.cluster_enabled) slotToKeyDel(key); 168 return 1; 169 } else { 170 return 0; 171 } 172 } 173 174 /* Prepare the string object stored at 'key' to be modified destructively 175 * to implement commands like SETBIT or APPEND. 176 * 177 * An object is usually ready to be modified unless one of the two conditions 178 * are true: 179 * 180 * 1) The object 'o' is shared (refcount > 1), we don't want to affect 181 * other users. 182 * 2) The object encoding is not "RAW". 183 * 184 * If the object is found in one of the above conditions (or both) by the 185 * function, an unshared / not-encoded copy of the string object is stored 186 * at 'key' in the specified 'db'. Otherwise the object 'o' itself is 187 * returned. 188 * 189 * USAGE: 190 * 191 * The object 'o' is what the caller already obtained by looking up 'key' 192 * in 'db', the usage pattern looks like this: 193 * 194 * o = lookupKeyWrite(db,key); 195 * if (checkType(c,o,REDIS_STRING)) return; 196 * o = dbUnshareStringValue(db,key,o); 197 * 198 * At this point the caller is ready to modify the object, for example 199 * using an sdscat() call to append some data, or anything else. 200 */ 201 robj *dbUnshareStringValue(redisDb *db, robj *key, robj *o) { 202 redisAssert(o->type == REDIS_STRING); 203 if (o->refcount != 1 || o->encoding != REDIS_ENCODING_RAW) { 204 robj *decoded = getDecodedObject(o); 205 o = createRawStringObject(decoded->ptr, sdslen(decoded->ptr)); 206 decrRefCount(decoded); 207 dbOverwrite(db,key,o); 208 } 209 return o; 210 } 211 212 long long emptyDb(void(callback)(void*)) { 213 int j; 214 long long removed = 0; 215 216 for (j = 0; j < server.dbnum; j++) { 217 removed += dictSize(server.db[j].dict); 218 dictEmpty(server.db[j].dict,callback); 219 dictEmpty(server.db[j].expires,callback); 220 } 221 if (server.cluster_enabled) slotToKeyFlush(); 222 return removed; 223 } 224 225 int selectDb(redisClient *c, int id) { 226 if (id < 0 || id >= server.dbnum) 227 return REDIS_ERR; 228 c->db = &server.db[id]; 229 return REDIS_OK; 230 } 231 232 /*----------------------------------------------------------------------------- 233 * Hooks for key space changes. 234 * 235 * Every time a key in the database is modified the function 236 * signalModifiedKey() is called. 237 * 238 * Every time a DB is flushed the function signalFlushDb() is called. 239 *----------------------------------------------------------------------------*/ 240 241 void signalModifiedKey(redisDb *db, robj *key) { 242 touchWatchedKey(db,key); 243 } 244 245 void signalFlushedDb(int dbid) { 246 touchWatchedKeysOnFlush(dbid); 247 } 248 249 /*----------------------------------------------------------------------------- 250 * Type agnostic commands operating on the key space 251 *----------------------------------------------------------------------------*/ 252 253 void flushdbCommand(redisClient *c) { 254 server.dirty += dictSize(c->db->dict); 255 signalFlushedDb(c->db->id); 256 dictEmpty(c->db->dict,NULL); 257 dictEmpty(c->db->expires,NULL); 258 if (server.cluster_enabled) slotToKeyFlush(); 259 addReply(c,shared.ok); 260 } 261 262 void flushallCommand(redisClient *c) { 263 signalFlushedDb(-1); 264 server.dirty += emptyDb(NULL); 265 addReply(c,shared.ok); 266 if (server.rdb_child_pid != -1) { 267 kill(server.rdb_child_pid,SIGUSR1); 268 rdbRemoveTempFile(server.rdb_child_pid); 269 } 270 if (server.saveparamslen > 0) { 271 /* Normally rdbSave() will reset dirty, but we don't want this here 272 * as otherwise FLUSHALL will not be replicated nor put into the AOF. */ 273 int saved_dirty = server.dirty; 274 rdbSave(server.rdb_filename); 275 server.dirty = saved_dirty; 276 } 277 server.dirty++; 278 } 279 280 void delCommand(redisClient *c) { 281 int deleted = 0, j; 282 283 for (j = 1; j < c->argc; j++) { 284 expireIfNeeded(c->db,c->argv[j]); 285 if (dbDelete(c->db,c->argv[j])) { 286 signalModifiedKey(c->db,c->argv[j]); 287 notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC, 288 "del",c->argv[j],c->db->id); 289 server.dirty++; 290 deleted++; 291 } 292 } 293 addReplyLongLong(c,deleted); 294 } 295 296 void existsCommand(redisClient *c) { 297 expireIfNeeded(c->db,c->argv[1]); 298 if (dbExists(c->db,c->argv[1])) { 299 addReply(c, shared.cone); 300 } else { 301 addReply(c, shared.czero); 302 } 303 } 304 305 void selectCommand(redisClient *c) { 306 long id; 307 308 if (getLongFromObjectOrReply(c, c->argv[1], &id, 309 "invalid DB index") != REDIS_OK) 310 return; 311 312 if (server.cluster_enabled && id != 0) { 313 addReplyError(c,"SELECT is not allowed in cluster mode"); 314 return; 315 } 316 if (selectDb(c,id) == REDIS_ERR) { 317 addReplyError(c,"invalid DB index"); 318 } else { 319 addReply(c,shared.ok); 320 } 321 } 322 323 void randomkeyCommand(redisClient *c) { 324 robj *key; 325 326 if ((key = dbRandomKey(c->db)) == NULL) { 327 addReply(c,shared.nullbulk); 328 return; 329 } 330 331 addReplyBulk(c,key); 332 decrRefCount(key); 333 } 334 335 void keysCommand(redisClient *c) { 336 dictIterator *di; 337 dictEntry *de; 338 sds pattern = c->argv[1]->ptr; 339 int plen = sdslen(pattern), allkeys; 340 unsigned long numkeys = 0; 341 void *replylen = addDeferredMultiBulkLength(c); 342 343 di = dictGetSafeIterator(c->db->dict); 344 allkeys = (pattern[0] == '*' && pattern[1] == '\0'); 345 while((de = dictNext(di)) != NULL) { 346 sds key = dictGetKey(de); 347 robj *keyobj; 348 349 if (allkeys || stringmatchlen(pattern,plen,key,sdslen(key),0)) { 350 keyobj = createStringObject(key,sdslen(key)); 351 if (expireIfNeeded(c->db,keyobj) == 0) { 352 addReplyBulk(c,keyobj); 353 numkeys++; 354 } 355 decrRefCount(keyobj); 356 } 357 } 358 dictReleaseIterator(di); 359 setDeferredMultiBulkLength(c,replylen,numkeys); 360 } 361 362 /* This callback is used by scanGenericCommand in order to collect elements 363 * returned by the dictionary iterator into a list. */ 364 void scanCallback(void *privdata, const dictEntry *de) { 365 void **pd = (void**) privdata; 366 list *keys = pd[0]; 367 robj *o = pd[1]; 368 robj *key, *val = NULL; 369 370 if (o == NULL) { 371 sds sdskey = dictGetKey(de); 372 key = createStringObject(sdskey, sdslen(sdskey)); 373 } else if (o->type == REDIS_SET) { 374 key = dictGetKey(de); 375 incrRefCount(key); 376 } else if (o->type == REDIS_HASH) { 377 key = dictGetKey(de); 378 incrRefCount(key); 379 val = dictGetVal(de); 380 incrRefCount(val); 381 } else if (o->type == REDIS_ZSET) { 382 key = dictGetKey(de); 383 incrRefCount(key); 384 val = createStringObjectFromLongDouble(*(double*)dictGetVal(de)); 385 } else { 386 redisPanic("Type not handled in SCAN callback."); 387 } 388 389 listAddNodeTail(keys, key); 390 if (val) listAddNodeTail(keys, val); 391 } 392 393 /* Try to parse a SCAN cursor stored at object 'o': 394 * if the cursor is valid, store it as unsigned integer into *cursor and 395 * returns REDIS_OK. Otherwise return REDIS_ERR and send an error to the 396 * client. */ 397 int parseScanCursorOrReply(redisClient *c, robj *o, unsigned long *cursor) { 398 char *eptr; 399 400 /* Use strtoul() because we need an *unsigned* long, so 401 * getLongLongFromObject() does not cover the whole cursor space. */ 402 errno = 0; 403 *cursor = strtoul(o->ptr, &eptr, 10); 404 if (isspace(((char*)o->ptr)[0]) || eptr[0] != '\0' || errno == ERANGE) 405 { 406 addReplyError(c, "invalid cursor"); 407 return REDIS_ERR; 408 } 409 return REDIS_OK; 410 } 411 412 /* This command implements SCAN, HSCAN and SSCAN commands. 413 * If object 'o' is passed, then it must be a Hash or Set object, otherwise 414 * if 'o' is NULL the command will operate on the dictionary associated with 415 * the current database. 416 * 417 * When 'o' is not NULL the function assumes that the first argument in 418 * the client arguments vector is a key so it skips it before iterating 419 * in order to parse options. 420 * 421 * In the case of a Hash object the function returns both the field and value 422 * of every element on the Hash. */ 423 void scanGenericCommand(redisClient *c, robj *o, unsigned long cursor) { 424 int rv; 425 int i, j; 426 char buf[REDIS_LONGSTR_SIZE]; 427 list *keys = listCreate(); 428 listNode *node, *nextnode; 429 long count = 10; 430 sds pat; 431 int patlen, use_pattern = 0; 432 dict *ht; 433 434 /* Object must be NULL (to iterate keys names), or the type of the object 435 * must be Set, Sorted Set, or Hash. */ 436 redisAssert(o == NULL || o->type == REDIS_SET || o->type == REDIS_HASH || 437 o->type == REDIS_ZSET); 438 439 /* Set i to the first option argument. The previous one is the cursor. */ 440 i = (o == NULL) ? 2 : 3; /* Skip the key argument if needed. */ 441 442 /* Step 1: Parse options. */ 443 while (i < c->argc) { 444 j = c->argc - i; 445 if (!strcasecmp(c->argv[i]->ptr, "count") && j >= 2) { 446 if (getLongFromObjectOrReply(c, c->argv[i+1], &count, NULL) 447 != REDIS_OK) 448 { 449 goto cleanup; 450 } 451 452 if (count < 1) { 453 addReply(c,shared.syntaxerr); 454 goto cleanup; 455 } 456 457 i += 2; 458 } else if (!strcasecmp(c->argv[i]->ptr, "match") && j >= 2) { 459 pat = c->argv[i+1]->ptr; 460 patlen = sdslen(pat); 461 462 /* The pattern always matches if it is exactly "*", so it is 463 * equivalent to disabling it. */ 464 use_pattern = !(pat[0] == '*' && patlen == 1); 465 466 i += 2; 467 } else { 468 addReply(c,shared.syntaxerr); 469 goto cleanup; 470 } 471 } 472 473 /* Step 2: Iterate the collection. 474 * 475 * Note that if the object is encoded with a ziplist, intset, or any other 476 * representation that is not a hash table, we are sure that it is also 477 * composed of a small number of elements. So to avoid taking state we 478 * just return everything inside the object in a single call, setting the 479 * cursor to zero to signal the end of the iteration. */ 480 481 /* Handle the case of a hash table. */ 482 ht = NULL; 483 if (o == NULL) { 484 ht = c->db->dict; 485 } else if (o->type == REDIS_SET && o->encoding == REDIS_ENCODING_HT) { 486 ht = o->ptr; 487 } else if (o->type == REDIS_HASH && o->encoding == REDIS_ENCODING_HT) { 488 ht = o->ptr; 489 count *= 2; /* We return key / value for this type. */ 490 } else if (o->type == REDIS_ZSET && o->encoding == REDIS_ENCODING_SKIPLIST) { 491 zset *zs = o->ptr; 492 ht = zs->dict; 493 count *= 2; /* We return key / value for this type. */ 494 } 495 496 if (ht) { 497 void *privdata[2]; 498 499 /* We pass two pointers to the callback: the list to which it will 500 * add new elements, and the object containing the dictionary so that 501 * it is possible to fetch more data in a type-dependent way. */ 502 privdata[0] = keys; 503 privdata[1] = o; 504 do { 505 cursor = dictScan(ht, cursor, scanCallback, privdata); 506 } while (cursor && listLength(keys) < count); 507 } else if (o->type == REDIS_SET) { 508 int pos = 0; 509 int64_t ll; 510 511 while(intsetGet(o->ptr,pos++,&ll)) 512 listAddNodeTail(keys,createStringObjectFromLongLong(ll)); 513 cursor = 0; 514 } else if (o->type == REDIS_HASH || o->type == REDIS_ZSET) { 515 unsigned char *p = ziplistIndex(o->ptr,0); 516 unsigned char *vstr; 517 unsigned int vlen; 518 long long vll; 519 520 while(p) { 521 ziplistGet(p,&vstr,&vlen,&vll); 522 listAddNodeTail(keys, 523 (vstr != NULL) ? createStringObject((char*)vstr,vlen) : 524 createStringObjectFromLongLong(vll)); 525 p = ziplistNext(o->ptr,p); 526 } 527 cursor = 0; 528 } else { 529 redisPanic("Not handled encoding in SCAN."); 530 } 531 532 /* Step 3: Filter elements. */ 533 node = listFirst(keys); 534 while (node) { 535 robj *kobj = listNodeValue(node); 536 nextnode = listNextNode(node); 537 int filter = 0; 538 539 /* Filter element if it does not match the pattern. */ 540 if (!filter && use_pattern) { 541 if (sdsEncodedObject(kobj)) { 542 if (!stringmatchlen(pat, patlen, kobj->ptr, sdslen(kobj->ptr), 0)) 543 filter = 1; 544 } else { 545 char buf[REDIS_LONGSTR_SIZE]; 546 int len; 547 548 redisAssert(kobj->encoding == REDIS_ENCODING_INT); 549 len = ll2string(buf,sizeof(buf),(long)kobj->ptr); 550 if (!stringmatchlen(pat, patlen, buf, len, 0)) filter = 1; 551 } 552 } 553 554 /* Filter element if it is an expired key. */ 555 if (!filter && o == NULL && expireIfNeeded(c->db, kobj)) filter = 1; 556 557 /* Remove the element and its associted value if needed. */ 558 if (filter) { 559 decrRefCount(kobj); 560 listDelNode(keys, node); 561 } 562 563 /* If this is a hash or a sorted set, we have a flat list of 564 * key-value elements, so if this element was filtered, remove the 565 * value, or skip it if it was not filtered: we only match keys. */ 566 if (o && (o->type == REDIS_ZSET || o->type == REDIS_HASH)) { 567 node = nextnode; 568 nextnode = listNextNode(node); 569 if (filter) { 570 kobj = listNodeValue(node); 571 decrRefCount(kobj); 572 listDelNode(keys, node); 573 } 574 } 575 node = nextnode; 576 } 577 578 /* Step 4: Reply to the client. */ 579 addReplyMultiBulkLen(c, 2); 580 rv = snprintf(buf, sizeof(buf), "%lu", cursor); 581 redisAssert(rv < sizeof(buf)); 582 addReplyBulkCBuffer(c, buf, rv); 583 584 addReplyMultiBulkLen(c, listLength(keys)); 585 while ((node = listFirst(keys)) != NULL) { 586 robj *kobj = listNodeValue(node); 587 addReplyBulk(c, kobj); 588 decrRefCount(kobj); 589 listDelNode(keys, node); 590 } 591 592 cleanup: 593 listSetFreeMethod(keys,decrRefCountVoid); 594 listRelease(keys); 595 } 596 597 /* The SCAN command completely relies on scanGenericCommand. */ 598 void scanCommand(redisClient *c) { 599 unsigned long cursor; 600 if (parseScanCursorOrReply(c,c->argv[1],&cursor) == REDIS_ERR) return; 601 scanGenericCommand(c,NULL,cursor); 602 } 603 604 void dbsizeCommand(redisClient *c) { 605 addReplyLongLong(c,dictSize(c->db->dict)); 606 } 607 608 void lastsaveCommand(redisClient *c) { 609 addReplyLongLong(c,server.lastsave); 610 } 611 612 void typeCommand(redisClient *c) { 613 robj *o; 614 char *type; 615 616 o = lookupKeyRead(c->db,c->argv[1]); 617 if (o == NULL) { 618 type = "none"; 619 } else { 620 switch(o->type) { 621 case REDIS_STRING: type = "string"; break; 622 case REDIS_LIST: type = "list"; break; 623 case REDIS_SET: type = "set"; break; 624 case REDIS_ZSET: type = "zset"; break; 625 case REDIS_HASH: type = "hash"; break; 626 default: type = "unknown"; break; 627 } 628 } 629 addReplyStatus(c,type); 630 } 631 632 void shutdownCommand(redisClient *c) { 633 int flags = 0; 634 635 if (c->argc > 2) { 636 addReply(c,shared.syntaxerr); 637 return; 638 } else if (c->argc == 2) { 639 if (!strcasecmp(c->argv[1]->ptr,"nosave")) { 640 flags |= REDIS_SHUTDOWN_NOSAVE; 641 } else if (!strcasecmp(c->argv[1]->ptr,"save")) { 642 flags |= REDIS_SHUTDOWN_SAVE; 643 } else { 644 addReply(c,shared.syntaxerr); 645 return; 646 } 647 } 648 /* When SHUTDOWN is called while the server is loading a dataset in 649 * memory we need to make sure no attempt is performed to save 650 * the dataset on shutdown (otherwise it could overwrite the current DB 651 * with half-read data). 652 * 653 * Also when in Sentinel mode clear the SAVE flag and force NOSAVE. */ 654 if (server.loading || server.sentinel_mode) 655 flags = (flags & ~REDIS_SHUTDOWN_SAVE) | REDIS_SHUTDOWN_NOSAVE; 656 if (prepareForShutdown(flags) == REDIS_OK) exit(0); 657 addReplyError(c,"Errors trying to SHUTDOWN. Check logs."); 658 } 659 660 void renameGenericCommand(redisClient *c, int nx) { 661 robj *o; 662 long long expire; 663 664 /* To use the same key as src and dst is probably an error */ 665 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) { 666 addReply(c,shared.sameobjecterr); 667 return; 668 } 669 670 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL) 671 return; 672 673 incrRefCount(o); 674 expire = getExpire(c->db,c->argv[1]); 675 if (lookupKeyWrite(c->db,c->argv[2]) != NULL) { 676 if (nx) { 677 decrRefCount(o); 678 addReply(c,shared.czero); 679 return; 680 } 681 /* Overwrite: delete the old key before creating the new one 682 * with the same name. */ 683 dbDelete(c->db,c->argv[2]); 684 } 685 dbAdd(c->db,c->argv[2],o); 686 if (expire != -1) setExpire(c->db,c->argv[2],expire); 687 dbDelete(c->db,c->argv[1]); 688 signalModifiedKey(c->db,c->argv[1]); 689 signalModifiedKey(c->db,c->argv[2]); 690 notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"rename_from", 691 c->argv[1],c->db->id); 692 notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"rename_to", 693 c->argv[2],c->db->id); 694 server.dirty++; 695 addReply(c,nx ? shared.cone : shared.ok); 696 } 697 698 void renameCommand(redisClient *c) { 699 renameGenericCommand(c,0); 700 } 701 702 void renamenxCommand(redisClient *c) { 703 renameGenericCommand(c,1); 704 } 705 706 void moveCommand(redisClient *c) { 707 robj *o; 708 redisDb *src, *dst; 709 int srcid; 710 711 if (server.cluster_enabled) { 712 addReplyError(c,"MOVE is not allowed in cluster mode"); 713 return; 714 } 715 716 /* Obtain source and target DB pointers */ 717 src = c->db; 718 srcid = c->db->id; 719 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) { 720 addReply(c,shared.outofrangeerr); 721 return; 722 } 723 dst = c->db; 724 selectDb(c,srcid); /* Back to the source DB */ 725 726 /* If the user is moving using as target the same 727 * DB as the source DB it is probably an error. */ 728 if (src == dst) { 729 addReply(c,shared.sameobjecterr); 730 return; 731 } 732 733 /* Check if the element exists and get a reference */ 734 o = lookupKeyWrite(c->db,c->argv[1]); 735 if (!o) { 736 addReply(c,shared.czero); 737 return; 738 } 739 740 /* Return zero if the key already exists in the target DB */ 741 if (lookupKeyWrite(dst,c->argv[1]) != NULL) { 742 addReply(c,shared.czero); 743 return; 744 } 745 dbAdd(dst,c->argv[1],o); 746 incrRefCount(o); 747 748 /* OK! key moved, free the entry in the source DB */ 749 dbDelete(src,c->argv[1]); 750 server.dirty++; 751 addReply(c,shared.cone); 752 } 753 754 /*----------------------------------------------------------------------------- 755 * Expires API 756 *----------------------------------------------------------------------------*/ 757 758 int removeExpire(redisDb *db, robj *key) { 759 /* An expire may only be removed if there is a corresponding entry in the 760 * main dict. Otherwise, the key will never be freed. */ 761 redisAssertWithInfo(NULL,key,dictFind(db->dict,key->ptr) != NULL); 762 return dictDelete(db->expires,key->ptr) == DICT_OK; 763 } 764 765 void setExpire(redisDb *db, robj *key, long long when) { 766 dictEntry *kde, *de; 767 768 /* Reuse the sds from the main dict in the expire dict */ 769 kde = dictFind(db->dict,key->ptr); 770 redisAssertWithInfo(NULL,key,kde != NULL); 771 de = dictReplaceRaw(db->expires,dictGetKey(kde)); 772 dictSetSignedIntegerVal(de,when); 773 } 774 775 /* Return the expire time of the specified key, or -1 if no expire 776 * is associated with this key (i.e. the key is non volatile) */ 777 long long getExpire(redisDb *db, robj *key) { 778 dictEntry *de; 779 780 /* No expire? return ASAP */ 781 if (dictSize(db->expires) == 0 || 782 (de = dictFind(db->expires,key->ptr)) == NULL) return -1; 783 784 /* The entry was found in the expire dict, this means it should also 785 * be present in the main dict (safety check). */ 786 redisAssertWithInfo(NULL,key,dictFind(db->dict,key->ptr) != NULL); 787 return dictGetSignedIntegerVal(de); 788 } 789 790 /* Propagate expires into slaves and the AOF file. 791 * When a key expires in the master, a DEL operation for this key is sent 792 * to all the slaves and the AOF file if enabled. 793 * 794 * This way the key expiry is centralized in one place, and since both 795 * AOF and the master->slave link guarantee operation ordering, everything 796 * will be consistent even if we allow write operations against expiring 797 * keys. */ 798 void propagateExpire(redisDb *db, robj *key) { 799 robj *argv[2]; 800 801 argv[0] = shared.del; 802 argv[1] = key; 803 incrRefCount(argv[0]); 804 incrRefCount(argv[1]); 805 806 if (server.aof_state != REDIS_AOF_OFF) 807 feedAppendOnlyFile(server.delCommand,db->id,argv,2); 808 replicationFeedSlaves(server.slaves,db->id,argv,2); 809 810 decrRefCount(argv[0]); 811 decrRefCount(argv[1]); 812 } 813 814 int expireIfNeeded(redisDb *db, robj *key) { 815 mstime_t when = getExpire(db,key); 816 mstime_t now; 817 818 if (when < 0) return 0; /* No expire for this key */ 819 820 /* Don't expire anything while loading. It will be done later. */ 821 if (server.loading) return 0; 822 823 /* If we are in the context of a Lua script, we claim that time is 824 * blocked to when the Lua script started. This way a key can expire 825 * only the first time it is accessed and not in the middle of the 826 * script execution, making propagation to slaves / AOF consistent. 827 * See issue #1525 on Github for more information. */ 828 now = server.lua_caller ? server.lua_time_start : mstime(); 829 830 /* If we are running in the context of a slave, return ASAP: 831 * the slave key expiration is controlled by the master that will 832 * send us synthesized DEL operations for expired keys. 833 * 834 * Still we try to return the right information to the caller, 835 * that is, 0 if we think the key should be still valid, 1 if 836 * we think the key is expired at this time. */ 837 if (server.masterhost != NULL) return now > when; 838 839 /* Return when this key has not expired */ 840 if (now <= when) return 0; 841 842 /* Delete the key */ 843 server.stat_expiredkeys++; 844 propagateExpire(db,key); 845 notifyKeyspaceEvent(REDIS_NOTIFY_EXPIRED, 846 "expired",key,db->id); 847 return dbDelete(db,key); 848 } 849 850 /*----------------------------------------------------------------------------- 851 * Expires Commands 852 *----------------------------------------------------------------------------*/ 853 854 /* This is the generic command implementation for EXPIRE, PEXPIRE, EXPIREAT 855 * and PEXPIREAT. Because the commad second argument may be relative or absolute 856 * the "basetime" argument is used to signal what the base time is (either 0 857 * for *AT variants of the command, or the current time for relative expires). 858 * 859 * unit is either UNIT_SECONDS or UNIT_MILLISECONDS, and is only used for 860 * the argv[2] parameter. The basetime is always specified in milliseconds. */ 861 void expireGenericCommand(redisClient *c, long long basetime, int unit) { 862 robj *key = c->argv[1], *param = c->argv[2]; 863 long long when; /* unix time in milliseconds when the key will expire. */ 864 865 if (getLongLongFromObjectOrReply(c, param, &when, NULL) != REDIS_OK) 866 return; 867 868 if (unit == UNIT_SECONDS) when *= 1000; 869 when += basetime; 870 871 /* No key, return zero. */ 872 if (lookupKeyRead(c->db,key) == NULL) { 873 addReply(c,shared.czero); 874 return; 875 } 876 877 /* EXPIRE with negative TTL, or EXPIREAT with a timestamp into the past 878 * should never be executed as a DEL when load the AOF or in the context 879 * of a slave instance. 880 * 881 * Instead we take the other branch of the IF statement setting an expire 882 * (possibly in the past) and wait for an explicit DEL from the master. */ 883 if (when <= mstime() && !server.loading && !server.masterhost) { 884 robj *aux; 885 886 redisAssertWithInfo(c,key,dbDelete(c->db,key)); 887 server.dirty++; 888 889 /* Replicate/AOF this as an explicit DEL. */ 890 aux = createStringObject("DEL",3); 891 rewriteClientCommandVector(c,2,aux,key); 892 decrRefCount(aux); 893 signalModifiedKey(c->db,key); 894 notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",key,c->db->id); 895 addReply(c, shared.cone); 896 return; 897 } else { 898 setExpire(c->db,key,when); 899 addReply(c,shared.cone); 900 signalModifiedKey(c->db,key); 901 notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"expire",key,c->db->id); 902 server.dirty++; 903 return; 904 } 905 } 906 907 void expireCommand(redisClient *c) { 908 expireGenericCommand(c,mstime(),UNIT_SECONDS); 909 } 910 911 void expireatCommand(redisClient *c) { 912 expireGenericCommand(c,0,UNIT_SECONDS); 913 } 914 915 void pexpireCommand(redisClient *c) { 916 expireGenericCommand(c,mstime(),UNIT_MILLISECONDS); 917 } 918 919 void pexpireatCommand(redisClient *c) { 920 expireGenericCommand(c,0,UNIT_MILLISECONDS); 921 } 922 923 void ttlGenericCommand(redisClient *c, int output_ms) { 924 long long expire, ttl = -1; 925 926 /* If the key does not exist at all, return -2 */ 927 if (lookupKeyRead(c->db,c->argv[1]) == NULL) { 928 addReplyLongLong(c,-2); 929 return; 930 } 931 /* The key exists. Return -1 if it has no expire, or the actual 932 * TTL value otherwise. */ 933 expire = getExpire(c->db,c->argv[1]); 934 if (expire != -1) { 935 ttl = expire-mstime(); 936 if (ttl < 0) ttl = 0; 937 } 938 if (ttl == -1) { 939 addReplyLongLong(c,-1); 940 } else { 941 addReplyLongLong(c,output_ms ? ttl : ((ttl+500)/1000)); 942 } 943 } 944 945 void ttlCommand(redisClient *c) { 946 ttlGenericCommand(c, 0); 947 } 948 949 void pttlCommand(redisClient *c) { 950 ttlGenericCommand(c, 1); 951 } 952 953 void persistCommand(redisClient *c) { 954 dictEntry *de; 955 956 de = dictFind(c->db->dict,c->argv[1]->ptr); 957 if (de == NULL) { 958 addReply(c,shared.czero); 959 } else { 960 if (removeExpire(c->db,c->argv[1])) { 961 addReply(c,shared.cone); 962 server.dirty++; 963 } else { 964 addReply(c,shared.czero); 965 } 966 } 967 } 968 969 /* ----------------------------------------------------------------------------- 970 * API to get key arguments from commands 971 * ---------------------------------------------------------------------------*/ 972 973 /* The base case is to use the keys position as given in the command table 974 * (firstkey, lastkey, step). */ 975 int *getKeysUsingCommandTable(struct redisCommand *cmd,robj **argv, int argc, int *numkeys) { 976 int j, i = 0, last, *keys; 977 REDIS_NOTUSED(argv); 978 979 if (cmd->firstkey == 0) { 980 *numkeys = 0; 981 return NULL; 982 } 983 last = cmd->lastkey; 984 if (last < 0) last = argc+last; 985 keys = zmalloc(sizeof(int)*((last - cmd->firstkey)+1)); 986 for (j = cmd->firstkey; j <= last; j += cmd->keystep) { 987 redisAssert(j < argc); 988 keys[i++] = j; 989 } 990 *numkeys = i; 991 return keys; 992 } 993 994 /* Return all the arguments that are keys in the command passed via argc / argv. 995 * 996 * The command returns the positions of all the key arguments inside the array, 997 * so the actual return value is an heap allocated array of integers. The 998 * length of the array is returned by reference into *numkeys. 999 * 1000 * 'cmd' must be point to the corresponding entry into the redisCommand 1001 * table, according to the command name in argv[0]. 1002 * 1003 * This function uses the command table if a command-specific helper function 1004 * is not required, otherwise it calls the command-specific function. */ 1005 int *getKeysFromCommand(struct redisCommand *cmd, robj **argv, int argc, int *numkeys) { 1006 if (cmd->getkeys_proc) { 1007 return cmd->getkeys_proc(cmd,argv,argc,numkeys); 1008 } else { 1009 return getKeysUsingCommandTable(cmd,argv,argc,numkeys); 1010 } 1011 } 1012 1013 /* Free the result of getKeysFromCommand. */ 1014 void getKeysFreeResult(int *result) { 1015 zfree(result); 1016 } 1017 1018 /* Helper function to extract keys from following commands: 1019 * ZUNIONSTORE <destkey> <num-keys> <key> <key> ... <key> <options> 1020 * ZINTERSTORE <destkey> <num-keys> <key> <key> ... <key> <options> */ 1021 int *zunionInterGetKeys(struct redisCommand *cmd, robj **argv, int argc, int *numkeys) { 1022 int i, num, *keys; 1023 REDIS_NOTUSED(cmd); 1024 1025 num = atoi(argv[2]->ptr); 1026 /* Sanity check. Don't return any key if the command is going to 1027 * reply with syntax error. */ 1028 if (num > (argc-3)) { 1029 *numkeys = 0; 1030 return NULL; 1031 } 1032 1033 /* Keys in z{union,inter}store come from two places: 1034 * argv[1] = storage key, 1035 * argv[3...n] = keys to intersect */ 1036 keys = zmalloc(sizeof(int)*(num+1)); 1037 1038 /* Add all key positions for argv[3...n] to keys[] */ 1039 for (i = 0; i < num; i++) keys[i] = 3+i; 1040 1041 /* Finally add the argv[1] key position (the storage key target). */ 1042 keys[num] = 1; 1043 *numkeys = num+1; /* Total keys = {union,inter} keys + storage key */ 1044 return keys; 1045 } 1046 1047 /* Helper function to extract keys from the following commands: 1048 * EVAL <script> <num-keys> <key> <key> ... <key> [more stuff] 1049 * EVALSHA <script> <num-keys> <key> <key> ... <key> [more stuff] */ 1050 int *evalGetKeys(struct redisCommand *cmd, robj **argv, int argc, int *numkeys) { 1051 int i, num, *keys; 1052 REDIS_NOTUSED(cmd); 1053 1054 num = atoi(argv[2]->ptr); 1055 /* Sanity check. Don't return any key if the command is going to 1056 * reply with syntax error. */ 1057 if (num > (argc-3)) { 1058 *numkeys = 0; 1059 return NULL; 1060 } 1061 1062 keys = zmalloc(sizeof(int)*num); 1063 *numkeys = num; 1064 1065 /* Add all key positions for argv[3...n] to keys[] */ 1066 for (i = 0; i < num; i++) keys[i] = 3+i; 1067 1068 return keys; 1069 } 1070 1071 /* Helper function to extract keys from the SORT command. 1072 * 1073 * SORT <sort-key> ... STORE <store-key> ... 1074 * 1075 * The first argument of SORT is always a key, however a list of options 1076 * follow in SQL-alike style. Here we parse just the minimum in order to 1077 * correctly identify keys in the "STORE" option. */ 1078 int *sortGetKeys(struct redisCommand *cmd, robj **argv, int argc, int *numkeys) { 1079 int i, j, num, *keys; 1080 REDIS_NOTUSED(cmd); 1081 1082 num = 0; 1083 keys = zmalloc(sizeof(int)*2); /* Alloc 2 places for the worst case. */ 1084 1085 keys[num++] = 1; /* <sort-key> is always present. */ 1086 1087 /* Search for STORE option. By default we consider options to don't 1088 * have arguments, so if we find an unknown option name we scan the 1089 * next. However there are options with 1 or 2 arguments, so we 1090 * provide a list here in order to skip the right number of args. */ 1091 struct { 1092 char *name; 1093 int skip; 1094 } skiplist[] = { 1095 {"limit", 2}, 1096 {"get", 1}, 1097 {"by", 1}, 1098 {NULL, 0} /* End of elements. */ 1099 }; 1100 1101 for (i = 2; i < argc; i++) { 1102 for (j = 0; skiplist[j].name != NULL; j++) { 1103 if (!strcasecmp(argv[i]->ptr,skiplist[j].name)) { 1104 i += skiplist[j].skip; 1105 break; 1106 } else if (!strcasecmp(argv[i]->ptr,"store") && i+1 < argc) { 1107 /* Note: we don't increment "num" here and continue the loop 1108 * to be sure to process the *last* "STORE" option if multiple 1109 * ones are provided. This is same behavior as SORT. */ 1110 keys[num] = i+1; /* <store-key> */ 1111 break; 1112 } 1113 } 1114 } 1115 *numkeys = num; 1116 return keys; 1117 } 1118 1119 /* Slot to Key API. This is used by Redis Cluster in order to obtain in 1120 * a fast way a key that belongs to a specified hash slot. This is useful 1121 * while rehashing the cluster. */ 1122 void slotToKeyAdd(robj *key) { 1123 unsigned int hashslot = keyHashSlot(key->ptr,sdslen(key->ptr)); 1124 1125 zslInsert(server.cluster->slots_to_keys,hashslot,key); 1126 incrRefCount(key); 1127 } 1128 1129 void slotToKeyDel(robj *key) { 1130 unsigned int hashslot = keyHashSlot(key->ptr,sdslen(key->ptr)); 1131 1132 zslDelete(server.cluster->slots_to_keys,hashslot,key); 1133 } 1134 1135 void slotToKeyFlush(void) { 1136 zslFree(server.cluster->slots_to_keys); 1137 server.cluster->slots_to_keys = zslCreate(); 1138 } 1139 1140 unsigned int getKeysInSlot(unsigned int hashslot, robj **keys, unsigned int count) { 1141 zskiplistNode *n; 1142 zrangespec range; 1143 int j = 0; 1144 1145 range.min = range.max = hashslot; 1146 range.minex = range.maxex = 0; 1147 1148 n = zslFirstInRange(server.cluster->slots_to_keys, &range); 1149 while(n && n->score == hashslot && count--) { 1150 keys[j++] = n->obj; 1151 n = n->level[0].forward; 1152 } 1153 return j; 1154 } 1155 1156 /* Remove all the keys in the specified hash slot. 1157 * The number of removed items is returned. */ 1158 unsigned int delKeysInSlot(unsigned int hashslot) { 1159 zskiplistNode *n; 1160 zrangespec range; 1161 int j = 0; 1162 1163 range.min = range.max = hashslot; 1164 range.minex = range.maxex = 0; 1165 1166 n = zslFirstInRange(server.cluster->slots_to_keys, &range); 1167 while(n && n->score == hashslot) { 1168 robj *key = n->obj; 1169 n = n->level[0].forward; /* Go to the next item before freeing it. */ 1170 incrRefCount(key); /* Protect the object while freeing it. */ 1171 dbDelete(&server.db[0],key); 1172 decrRefCount(key); 1173 j++; 1174 } 1175 return j; 1176 } 1177 1178 unsigned int countKeysInSlot(unsigned int hashslot) { 1179 zskiplist *zsl = server.cluster->slots_to_keys; 1180 zskiplistNode *zn; 1181 zrangespec range; 1182 int rank, count = 0; 1183 1184 range.min = range.max = hashslot; 1185 range.minex = range.maxex = 0; 1186 1187 /* Find first element in range */ 1188 zn = zslFirstInRange(zsl, &range); 1189 1190 /* Use rank of first element, if any, to determine preliminary count */ 1191 if (zn != NULL) { 1192 rank = zslGetRank(zsl, zn->score, zn->obj); 1193 count = (zsl->length - (rank - 1)); 1194 1195 /* Find last element in range */ 1196 zn = zslLastInRange(zsl, &range); 1197 1198 /* Use rank of last element, if any, to determine the actual count */ 1199 if (zn != NULL) { 1200 rank = zslGetRank(zsl, zn->score, zn->obj); 1201 count -= (zsl->length - rank); 1202 } 1203 } 1204 return count; 1205 } 1206