]> git.saurik.com Git - redis.git/blob - src/db.c
Merge pull request #63 from djanowski/tcl
[redis.git] / src / db.c
1 #include "redis.h"
2
3 #include <signal.h>
4
5 void SlotToKeyAdd(robj *key);
6 void SlotToKeyDel(robj *key);
7
8 /*-----------------------------------------------------------------------------
9 * C-level DB API
10 *----------------------------------------------------------------------------*/
11
12 /* Important notes on lookup and disk store.
13 *
14 * When disk store is enabled on lookup we can have different cases.
15 *
16 * a) The key is in memory:
17 * - If the key is not in IO_SAVEINPROG state we can access it.
18 * As if it's just IO_SAVE this means we have the key in the IO queue
19 * but can't be accessed by the IO thread (it requires to be
20 * translated into an IO Job by the cache cron function.)
21 * - If the key is in IO_SAVEINPROG we can't touch the key and have
22 * to blocking wait completion of operations.
23 * b) The key is not in memory:
24 * - If it's marked as non existing on disk as well (negative cache)
25 * we don't need to perform the disk access.
26 * - if the key MAY EXIST, but is not in memory, and it is marked as IO_SAVE
27 * then the key can only be a deleted one. As IO_SAVE keys are never
28 * evicted (dirty state), so the only possibility is that key was deleted.
29 * - if the key MAY EXIST we need to blocking load it.
30 * We check that the key is not in IO_SAVEINPROG state before accessing
31 * the disk object. If it is in this state, we wait.
32 */
33
34 void lookupWaitBusyKey(redisDb *db, robj *key) {
35 /* FIXME: wait just for this key, not everything */
36 waitEmptyIOJobsQueue();
37 processAllPendingIOJobs();
38 redisAssert((cacheScheduleIOGetFlags(db,key) & REDIS_IO_SAVEINPROG) == 0);
39 }
40
41 robj *lookupKey(redisDb *db, robj *key) {
42 dictEntry *de = dictFind(db->dict,key->ptr);
43 if (de) {
44 robj *val = dictGetEntryVal(de);
45
46 /* Update the access time for the aging algorithm.
47 * Don't do it if we have a saving child, as this will trigger
48 * a copy on write madness. */
49 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1)
50 val->lru = server.lruclock;
51
52 if (server.ds_enabled &&
53 cacheScheduleIOGetFlags(db,key) & REDIS_IO_SAVEINPROG)
54 {
55 /* Need to wait for the key to get unbusy */
56 redisLog(REDIS_DEBUG,"Lookup found a key in SAVEINPROG state. Waiting. (Key was in the cache)");
57 lookupWaitBusyKey(db,key);
58 }
59 server.stat_keyspace_hits++;
60 return val;
61 } else {
62 time_t expire;
63 robj *val;
64
65 /* Key not found in the in memory hash table, but if disk store is
66 * enabled we may have this key on disk. If so load it in memory
67 * in a blocking way. */
68 if (server.ds_enabled && cacheKeyMayExist(db,key)) {
69 long flags = cacheScheduleIOGetFlags(db,key);
70
71 /* They key is not in cache, but it has a SAVE op in queue?
72 * The only possibility is that the key was deleted, since
73 * dirty keys are not evicted. */
74 if (flags & REDIS_IO_SAVE) {
75 server.stat_keyspace_misses++;
76 return NULL;
77 }
78
79 /* At this point we need to blocking load the key in memory.
80 * The first thing we do is waiting here if the key is busy. */
81 if (flags & REDIS_IO_SAVEINPROG) {
82 redisLog(REDIS_DEBUG,"Lookup found a key in SAVEINPROG state. Waiting (while force loading).");
83 lookupWaitBusyKey(db,key);
84 }
85
86 redisLog(REDIS_DEBUG,"Force loading key %s via lookup", key->ptr);
87 val = dsGet(db,key,&expire);
88 if (val) {
89 dbAdd(db,key,val);
90 if (expire != -1) setExpire(db,key,expire);
91 server.stat_keyspace_hits++;
92 return val;
93 } else {
94 cacheSetKeyDoesNotExist(db,key);
95 }
96 }
97 server.stat_keyspace_misses++;
98 return NULL;
99 }
100 }
101
102 robj *lookupKeyRead(redisDb *db, robj *key) {
103 expireIfNeeded(db,key);
104 return lookupKey(db,key);
105 }
106
107 robj *lookupKeyWrite(redisDb *db, robj *key) {
108 expireIfNeeded(db,key);
109 return lookupKey(db,key);
110 }
111
112 robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply) {
113 robj *o = lookupKeyRead(c->db, key);
114 if (!o) addReply(c,reply);
115 return o;
116 }
117
118 robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply) {
119 robj *o = lookupKeyWrite(c->db, key);
120 if (!o) addReply(c,reply);
121 return o;
122 }
123
124 /* Add the key to the DB. It's up to the caller to increment the reference
125 * counte of the value if needed.
126 *
127 * The program is aborted if the key already exists. */
128 void dbAdd(redisDb *db, robj *key, robj *val) {
129 sds copy = sdsdup(key->ptr);
130 int retval = dictAdd(db->dict, copy, val);
131
132 redisAssert(retval == REDIS_OK);
133 if (server.ds_enabled) cacheSetKeyMayExist(db,key);
134 if (server.cluster_enabled) SlotToKeyAdd(key);
135 }
136
137 /* Overwrite an existing key with a new value. Incrementing the reference
138 * count of the new value is up to the caller.
139 * This function does not modify the expire time of the existing key.
140 *
141 * The program is aborted if the key was not already present. */
142 void dbOverwrite(redisDb *db, robj *key, robj *val) {
143 struct dictEntry *de = dictFind(db->dict,key->ptr);
144
145 redisAssert(de != NULL);
146 dictReplace(db->dict, key->ptr, val);
147 if (server.ds_enabled) cacheSetKeyMayExist(db,key);
148 }
149
150 /* High level Set operation. This function can be used in order to set
151 * a key, whatever it was existing or not, to a new object.
152 *
153 * 1) The ref count of the value object is incremented.
154 * 2) clients WATCHing for the destination key notified.
155 * 3) The expire time of the key is reset (the key is made persistent). */
156 void setKey(redisDb *db, robj *key, robj *val) {
157 if (lookupKeyWrite(db,key) == NULL) {
158 dbAdd(db,key,val);
159 } else {
160 dbOverwrite(db,key,val);
161 }
162 incrRefCount(val);
163 removeExpire(db,key);
164 touchWatchedKey(db,key);
165 }
166
167 int dbExists(redisDb *db, robj *key) {
168 return dictFind(db->dict,key->ptr) != NULL;
169 }
170
171 /* Return a random key, in form of a Redis object.
172 * If there are no keys, NULL is returned.
173 *
174 * The function makes sure to return keys not already expired. */
175 robj *dbRandomKey(redisDb *db) {
176 struct dictEntry *de;
177
178 while(1) {
179 sds key;
180 robj *keyobj;
181
182 de = dictGetRandomKey(db->dict);
183 if (de == NULL) return NULL;
184
185 key = dictGetEntryKey(de);
186 keyobj = createStringObject(key,sdslen(key));
187 if (dictFind(db->expires,key)) {
188 if (expireIfNeeded(db,keyobj)) {
189 decrRefCount(keyobj);
190 continue; /* search for another key. This expired. */
191 }
192 }
193 return keyobj;
194 }
195 }
196
197 /* Delete a key, value, and associated expiration entry if any, from the DB */
198 int dbDelete(redisDb *db, robj *key) {
199 /* If diskstore is enabled make sure to awake waiting clients for this key
200 * as it is not really useful to wait for a key already deleted to be
201 * loaded from disk. */
202 if (server.ds_enabled) {
203 handleClientsBlockedOnSwappedKey(db,key);
204 cacheSetKeyDoesNotExist(db,key);
205 }
206
207 /* Deleting an entry from the expires dict will not free the sds of
208 * the key, because it is shared with the main dictionary. */
209 if (dictSize(db->expires) > 0) dictDelete(db->expires,key->ptr);
210 if (dictDelete(db->dict,key->ptr) == DICT_OK) {
211 if (server.cluster_enabled) SlotToKeyDel(key);
212 return 1;
213 } else {
214 return 0;
215 }
216 }
217
218 /* Empty the whole database.
219 * If diskstore is enabled this function will just flush the in-memory cache. */
220 long long emptyDb() {
221 int j;
222 long long removed = 0;
223
224 for (j = 0; j < server.dbnum; j++) {
225 removed += dictSize(server.db[j].dict);
226 dictEmpty(server.db[j].dict);
227 dictEmpty(server.db[j].expires);
228 if (server.ds_enabled) dictEmpty(server.db[j].io_negcache);
229 }
230 return removed;
231 }
232
233 int selectDb(redisClient *c, int id) {
234 if (id < 0 || id >= server.dbnum)
235 return REDIS_ERR;
236 c->db = &server.db[id];
237 return REDIS_OK;
238 }
239
240 /*-----------------------------------------------------------------------------
241 * Hooks for key space changes.
242 *
243 * Every time a key in the database is modified the function
244 * signalModifiedKey() is called.
245 *
246 * Every time a DB is flushed the function signalFlushDb() is called.
247 *----------------------------------------------------------------------------*/
248
249 void signalModifiedKey(redisDb *db, robj *key) {
250 touchWatchedKey(db,key);
251 if (server.ds_enabled)
252 cacheScheduleIO(db,key,REDIS_IO_SAVE);
253 }
254
255 void signalFlushedDb(int dbid) {
256 touchWatchedKeysOnFlush(dbid);
257 }
258
259 /*-----------------------------------------------------------------------------
260 * Type agnostic commands operating on the key space
261 *----------------------------------------------------------------------------*/
262
263 void flushdbCommand(redisClient *c) {
264 server.dirty += dictSize(c->db->dict);
265 signalFlushedDb(c->db->id);
266 dictEmpty(c->db->dict);
267 dictEmpty(c->db->expires);
268 if (server.ds_enabled) dsFlushDb(c->db->id);
269 addReply(c,shared.ok);
270 }
271
272 void flushallCommand(redisClient *c) {
273 signalFlushedDb(-1);
274 server.dirty += emptyDb();
275 addReply(c,shared.ok);
276 if (server.bgsavechildpid != -1) {
277 kill(server.bgsavechildpid,SIGKILL);
278 rdbRemoveTempFile(server.bgsavechildpid);
279 }
280 if (server.ds_enabled)
281 dsFlushDb(-1);
282 else
283 rdbSave(server.dbfilename);
284 server.dirty++;
285 }
286
287 void delCommand(redisClient *c) {
288 int deleted = 0, j;
289
290 for (j = 1; j < c->argc; j++) {
291 if (server.ds_enabled) {
292 lookupKeyRead(c->db,c->argv[j]);
293 /* FIXME: this can be optimized a lot, no real need to load
294 * a possibly huge value. */
295 }
296 if (dbDelete(c->db,c->argv[j])) {
297 signalModifiedKey(c->db,c->argv[j]);
298 server.dirty++;
299 deleted++;
300 } else if (server.ds_enabled) {
301 if (cacheKeyMayExist(c->db,c->argv[j]) &&
302 dsExists(c->db,c->argv[j]))
303 {
304 cacheScheduleIO(c->db,c->argv[j],REDIS_IO_SAVE);
305 deleted = 1;
306 }
307 }
308 }
309 addReplyLongLong(c,deleted);
310 }
311
312 void existsCommand(redisClient *c) {
313 expireIfNeeded(c->db,c->argv[1]);
314 if (dbExists(c->db,c->argv[1])) {
315 addReply(c, shared.cone);
316 } else {
317 addReply(c, shared.czero);
318 }
319 }
320
321 void selectCommand(redisClient *c) {
322 int id = atoi(c->argv[1]->ptr);
323
324 if (server.cluster_enabled && id != 0) {
325 addReplyError(c,"SELECT is not allowed in cluster mode");
326 return;
327 }
328 if (selectDb(c,id) == REDIS_ERR) {
329 addReplyError(c,"invalid DB index");
330 } else {
331 addReply(c,shared.ok);
332 }
333 }
334
335 void randomkeyCommand(redisClient *c) {
336 robj *key;
337
338 if ((key = dbRandomKey(c->db)) == NULL) {
339 addReply(c,shared.nullbulk);
340 return;
341 }
342
343 addReplyBulk(c,key);
344 decrRefCount(key);
345 }
346
347 void keysCommand(redisClient *c) {
348 dictIterator *di;
349 dictEntry *de;
350 sds pattern = c->argv[1]->ptr;
351 int plen = sdslen(pattern), allkeys;
352 unsigned long numkeys = 0;
353 void *replylen = addDeferredMultiBulkLength(c);
354
355 di = dictGetIterator(c->db->dict);
356 allkeys = (pattern[0] == '*' && pattern[1] == '\0');
357 while((de = dictNext(di)) != NULL) {
358 sds key = dictGetEntryKey(de);
359 robj *keyobj;
360
361 if (allkeys || stringmatchlen(pattern,plen,key,sdslen(key),0)) {
362 keyobj = createStringObject(key,sdslen(key));
363 if (expireIfNeeded(c->db,keyobj) == 0) {
364 addReplyBulk(c,keyobj);
365 numkeys++;
366 }
367 decrRefCount(keyobj);
368 }
369 }
370 dictReleaseIterator(di);
371 setDeferredMultiBulkLength(c,replylen,numkeys);
372 }
373
374 void dbsizeCommand(redisClient *c) {
375 addReplyLongLong(c,dictSize(c->db->dict));
376 }
377
378 void lastsaveCommand(redisClient *c) {
379 addReplyLongLong(c,server.lastsave);
380 }
381
382 void typeCommand(redisClient *c) {
383 robj *o;
384 char *type;
385
386 o = lookupKeyRead(c->db,c->argv[1]);
387 if (o == NULL) {
388 type = "none";
389 } else {
390 switch(o->type) {
391 case REDIS_STRING: type = "string"; break;
392 case REDIS_LIST: type = "list"; break;
393 case REDIS_SET: type = "set"; break;
394 case REDIS_ZSET: type = "zset"; break;
395 case REDIS_HASH: type = "hash"; break;
396 default: type = "unknown"; break;
397 }
398 }
399 addReplyStatus(c,type);
400 }
401
402 void shutdownCommand(redisClient *c) {
403 if (prepareForShutdown() == REDIS_OK)
404 exit(0);
405 addReplyError(c,"Errors trying to SHUTDOWN. Check logs.");
406 }
407
408 void renameGenericCommand(redisClient *c, int nx) {
409 robj *o;
410
411 /* To use the same key as src and dst is probably an error */
412 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
413 addReply(c,shared.sameobjecterr);
414 return;
415 }
416
417 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
418 return;
419
420 incrRefCount(o);
421 if (lookupKeyWrite(c->db,c->argv[2]) != NULL) {
422 if (nx) {
423 decrRefCount(o);
424 addReply(c,shared.czero);
425 return;
426 }
427 dbOverwrite(c->db,c->argv[2],o);
428 } else {
429 dbAdd(c->db,c->argv[2],o);
430 }
431 dbDelete(c->db,c->argv[1]);
432 signalModifiedKey(c->db,c->argv[1]);
433 signalModifiedKey(c->db,c->argv[2]);
434 server.dirty++;
435 addReply(c,nx ? shared.cone : shared.ok);
436 }
437
438 void renameCommand(redisClient *c) {
439 renameGenericCommand(c,0);
440 }
441
442 void renamenxCommand(redisClient *c) {
443 renameGenericCommand(c,1);
444 }
445
446 void moveCommand(redisClient *c) {
447 robj *o;
448 redisDb *src, *dst;
449 int srcid;
450
451 if (server.cluster_enabled) {
452 addReplyError(c,"MOVE is not allowed in cluster mode");
453 return;
454 }
455
456 /* Obtain source and target DB pointers */
457 src = c->db;
458 srcid = c->db->id;
459 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
460 addReply(c,shared.outofrangeerr);
461 return;
462 }
463 dst = c->db;
464 selectDb(c,srcid); /* Back to the source DB */
465
466 /* If the user is moving using as target the same
467 * DB as the source DB it is probably an error. */
468 if (src == dst) {
469 addReply(c,shared.sameobjecterr);
470 return;
471 }
472
473 /* Check if the element exists and get a reference */
474 o = lookupKeyWrite(c->db,c->argv[1]);
475 if (!o) {
476 addReply(c,shared.czero);
477 return;
478 }
479
480 /* Return zero if the key already exists in the target DB */
481 if (lookupKeyWrite(dst,c->argv[1]) != NULL) {
482 addReply(c,shared.czero);
483 return;
484 }
485 dbAdd(dst,c->argv[1],o);
486 incrRefCount(o);
487
488 /* OK! key moved, free the entry in the source DB */
489 dbDelete(src,c->argv[1]);
490 server.dirty++;
491 addReply(c,shared.cone);
492 }
493
494 /*-----------------------------------------------------------------------------
495 * Expires API
496 *----------------------------------------------------------------------------*/
497
498 int removeExpire(redisDb *db, robj *key) {
499 /* An expire may only be removed if there is a corresponding entry in the
500 * main dict. Otherwise, the key will never be freed. */
501 redisAssert(dictFind(db->dict,key->ptr) != NULL);
502 return dictDelete(db->expires,key->ptr) == DICT_OK;
503 }
504
505 void setExpire(redisDb *db, robj *key, time_t when) {
506 dictEntry *de;
507
508 /* Reuse the sds from the main dict in the expire dict */
509 de = dictFind(db->dict,key->ptr);
510 redisAssert(de != NULL);
511 dictReplace(db->expires,dictGetEntryKey(de),(void*)when);
512 }
513
514 /* Return the expire time of the specified key, or -1 if no expire
515 * is associated with this key (i.e. the key is non volatile) */
516 time_t getExpire(redisDb *db, robj *key) {
517 dictEntry *de;
518
519 /* No expire? return ASAP */
520 if (dictSize(db->expires) == 0 ||
521 (de = dictFind(db->expires,key->ptr)) == NULL) return -1;
522
523 /* The entry was found in the expire dict, this means it should also
524 * be present in the main dict (safety check). */
525 redisAssert(dictFind(db->dict,key->ptr) != NULL);
526 return (time_t) dictGetEntryVal(de);
527 }
528
529 /* Propagate expires into slaves and the AOF file.
530 * When a key expires in the master, a DEL operation for this key is sent
531 * to all the slaves and the AOF file if enabled.
532 *
533 * This way the key expiry is centralized in one place, and since both
534 * AOF and the master->slave link guarantee operation ordering, everything
535 * will be consistent even if we allow write operations against expiring
536 * keys. */
537 void propagateExpire(redisDb *db, robj *key) {
538 robj *argv[2];
539
540 argv[0] = createStringObject("DEL",3);
541 argv[1] = key;
542 incrRefCount(key);
543
544 if (server.appendonly)
545 feedAppendOnlyFile(server.delCommand,db->id,argv,2);
546 if (listLength(server.slaves))
547 replicationFeedSlaves(server.slaves,db->id,argv,2);
548
549 decrRefCount(argv[0]);
550 decrRefCount(argv[1]);
551 }
552
553 int expireIfNeeded(redisDb *db, robj *key) {
554 time_t when = getExpire(db,key);
555
556 if (when < 0) return 0; /* No expire for this key */
557
558 /* If we are running in the context of a slave, return ASAP:
559 * the slave key expiration is controlled by the master that will
560 * send us synthesized DEL operations for expired keys.
561 *
562 * Still we try to return the right information to the caller,
563 * that is, 0 if we think the key should be still valid, 1 if
564 * we think the key is expired at this time. */
565 if (server.masterhost != NULL) {
566 return time(NULL) > when;
567 }
568
569 /* Return when this key has not expired */
570 if (time(NULL) <= when) return 0;
571
572 /* Delete the key */
573 server.stat_expiredkeys++;
574 propagateExpire(db,key);
575 return dbDelete(db,key);
576 }
577
578 /*-----------------------------------------------------------------------------
579 * Expires Commands
580 *----------------------------------------------------------------------------*/
581
582 void expireGenericCommand(redisClient *c, robj *key, robj *param, long offset) {
583 dictEntry *de;
584 long seconds;
585
586 if (getLongFromObjectOrReply(c, param, &seconds, NULL) != REDIS_OK) return;
587
588 seconds -= offset;
589
590 de = dictFind(c->db->dict,key->ptr);
591 if (de == NULL) {
592 addReply(c,shared.czero);
593 return;
594 }
595 if (seconds <= 0) {
596 if (dbDelete(c->db,key)) server.dirty++;
597 addReply(c, shared.cone);
598 signalModifiedKey(c->db,key);
599 return;
600 } else {
601 time_t when = time(NULL)+seconds;
602 setExpire(c->db,key,when);
603 addReply(c,shared.cone);
604 signalModifiedKey(c->db,key);
605 server.dirty++;
606 return;
607 }
608 }
609
610 void expireCommand(redisClient *c) {
611 expireGenericCommand(c,c->argv[1],c->argv[2],0);
612 }
613
614 void expireatCommand(redisClient *c) {
615 expireGenericCommand(c,c->argv[1],c->argv[2],time(NULL));
616 }
617
618 void ttlCommand(redisClient *c) {
619 time_t expire, ttl = -1;
620
621 if (server.ds_enabled) lookupKeyRead(c->db,c->argv[1]);
622 expire = getExpire(c->db,c->argv[1]);
623 if (expire != -1) {
624 ttl = (expire-time(NULL));
625 if (ttl < 0) ttl = -1;
626 }
627 addReplyLongLong(c,(long long)ttl);
628 }
629
630 void persistCommand(redisClient *c) {
631 dictEntry *de;
632
633 de = dictFind(c->db->dict,c->argv[1]->ptr);
634 if (de == NULL) {
635 addReply(c,shared.czero);
636 } else {
637 if (removeExpire(c->db,c->argv[1])) {
638 addReply(c,shared.cone);
639 server.dirty++;
640 } else {
641 addReply(c,shared.czero);
642 }
643 }
644 }
645
646 /* -----------------------------------------------------------------------------
647 * API to get key arguments from commands
648 * ---------------------------------------------------------------------------*/
649
650 int *getKeysUsingCommandTable(struct redisCommand *cmd,robj **argv, int argc, int *numkeys) {
651 int j, i = 0, last, *keys;
652 REDIS_NOTUSED(argv);
653
654 if (cmd->firstkey == 0) {
655 *numkeys = 0;
656 return NULL;
657 }
658 last = cmd->lastkey;
659 if (last < 0) last = argc+last;
660 keys = zmalloc(sizeof(int)*((last - cmd->firstkey)+1));
661 for (j = cmd->firstkey; j <= last; j += cmd->keystep) {
662 redisAssert(j < argc);
663 keys[i++] = j;
664 }
665 *numkeys = i;
666 return keys;
667 }
668
669 int *getKeysFromCommand(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
670 if (cmd->getkeys_proc) {
671 return cmd->getkeys_proc(cmd,argv,argc,numkeys,flags);
672 } else {
673 return getKeysUsingCommandTable(cmd,argv,argc,numkeys);
674 }
675 }
676
677 void getKeysFreeResult(int *result) {
678 zfree(result);
679 }
680
681 int *noPreloadGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
682 if (flags & REDIS_GETKEYS_PRELOAD) {
683 *numkeys = 0;
684 return NULL;
685 } else {
686 return getKeysUsingCommandTable(cmd,argv,argc,numkeys);
687 }
688 }
689
690 int *renameGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
691 if (flags & REDIS_GETKEYS_PRELOAD) {
692 int *keys = zmalloc(sizeof(int));
693 *numkeys = 1;
694 keys[0] = 1;
695 return keys;
696 } else {
697 return getKeysUsingCommandTable(cmd,argv,argc,numkeys);
698 }
699 }
700
701 int *zunionInterGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
702 int i, num, *keys;
703 REDIS_NOTUSED(cmd);
704 REDIS_NOTUSED(flags);
705
706 num = atoi(argv[2]->ptr);
707 /* Sanity check. Don't return any key if the command is going to
708 * reply with syntax error. */
709 if (num > (argc-3)) {
710 *numkeys = 0;
711 return NULL;
712 }
713 keys = zmalloc(sizeof(int)*num);
714 for (i = 0; i < num; i++) keys[i] = 3+i;
715 *numkeys = num;
716 return keys;
717 }
718
719 /* Slot to Key API. This is used by Redis Cluster in order to obtain in
720 * a fast way a key that belongs to a specified hash slot. This is useful
721 * while rehashing the cluster. */
722 void SlotToKeyAdd(robj *key) {
723 unsigned int hashslot = keyHashSlot(key->ptr,sdslen(key->ptr));
724
725 zslInsert(server.cluster.slots_to_keys,hashslot,key);
726 incrRefCount(key);
727 }
728
729 void SlotToKeyDel(robj *key) {
730 unsigned int hashslot = keyHashSlot(key->ptr,sdslen(key->ptr));
731
732 zslDelete(server.cluster.slots_to_keys,hashslot,key);
733 }
734
735 unsigned int GetKeysInSlot(unsigned int hashslot, robj **keys, unsigned int count) {
736 zskiplistNode *n;
737 zrangespec range;
738 int j = 0;
739
740 range.min = range.max = hashslot;
741 range.minex = range.maxex = 0;
742
743 n = zslFirstInRange(server.cluster.slots_to_keys, range);
744 while(n && n->score == hashslot && count--) {
745 keys[j++] = n->obj;
746 n = n->level[0].forward;
747 }
748 return j;
749 }