]> git.saurik.com Git - redis.git/blob - redis.c
57300649cd20f464ef13efbacfba848671acd119
[redis.git] / redis.c
1 /*
2 * Copyright (c) 2006-2009, 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 #define REDIS_VERSION "1.3.2"
31
32 #include "fmacros.h"
33 #include "config.h"
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <time.h>
39 #include <unistd.h>
40 #define __USE_POSIX199309
41 #include <signal.h>
42
43 #ifdef HAVE_BACKTRACE
44 #include <execinfo.h>
45 #include <ucontext.h>
46 #endif /* HAVE_BACKTRACE */
47
48 #include <sys/wait.h>
49 #include <errno.h>
50 #include <assert.h>
51 #include <ctype.h>
52 #include <stdarg.h>
53 #include <inttypes.h>
54 #include <arpa/inet.h>
55 #include <sys/stat.h>
56 #include <fcntl.h>
57 #include <sys/time.h>
58 #include <sys/resource.h>
59 #include <sys/uio.h>
60 #include <limits.h>
61 #include <math.h>
62
63 #if defined(__sun)
64 #include "solarisfixes.h"
65 #endif
66
67 #include "redis.h"
68 #include "ae.h" /* Event driven programming library */
69 #include "sds.h" /* Dynamic safe strings */
70 #include "anet.h" /* Networking the easy way */
71 #include "dict.h" /* Hash tables */
72 #include "adlist.h" /* Linked lists */
73 #include "zmalloc.h" /* total memory usage aware version of malloc/free */
74 #include "lzf.h" /* LZF compression library */
75 #include "pqsort.h" /* Partial qsort for SORT+LIMIT */
76
77 /* Error codes */
78 #define REDIS_OK 0
79 #define REDIS_ERR -1
80
81 /* Static server configuration */
82 #define REDIS_SERVERPORT 6379 /* TCP port */
83 #define REDIS_MAXIDLETIME (60*5) /* default client timeout */
84 #define REDIS_IOBUF_LEN 1024
85 #define REDIS_LOADBUF_LEN 1024
86 #define REDIS_STATIC_ARGS 4
87 #define REDIS_DEFAULT_DBNUM 16
88 #define REDIS_CONFIGLINE_MAX 1024
89 #define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
90 #define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
91 #define REDIS_EXPIRELOOKUPS_PER_CRON 100 /* try to expire 100 keys/second */
92 #define REDIS_MAX_WRITE_PER_EVENT (1024*64)
93 #define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */
94
95 /* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */
96 #define REDIS_WRITEV_THRESHOLD 3
97 /* Max number of iovecs used for each writev call */
98 #define REDIS_WRITEV_IOVEC_COUNT 256
99
100 /* Hash table parameters */
101 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
102
103 /* Command flags */
104 #define REDIS_CMD_BULK 1 /* Bulk write command */
105 #define REDIS_CMD_INLINE 2 /* Inline command */
106 /* REDIS_CMD_DENYOOM reserves a longer comment: all the commands marked with
107 this flags will return an error when the 'maxmemory' option is set in the
108 config file and the server is using more than maxmemory bytes of memory.
109 In short this commands are denied on low memory conditions. */
110 #define REDIS_CMD_DENYOOM 4
111
112 /* Object types */
113 #define REDIS_STRING 0
114 #define REDIS_LIST 1
115 #define REDIS_SET 2
116 #define REDIS_ZSET 3
117 #define REDIS_HASH 4
118
119 /* Objects encoding */
120 #define REDIS_ENCODING_RAW 0 /* Raw representation */
121 #define REDIS_ENCODING_INT 1 /* Encoded as integer */
122
123 /* Object types only used for dumping to disk */
124 #define REDIS_EXPIRETIME 253
125 #define REDIS_SELECTDB 254
126 #define REDIS_EOF 255
127
128 /* Defines related to the dump file format. To store 32 bits lengths for short
129 * keys requires a lot of space, so we check the most significant 2 bits of
130 * the first byte to interpreter the length:
131 *
132 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
133 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
134 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
135 * 11|000000 this means: specially encoded object will follow. The six bits
136 * number specify the kind of object that follows.
137 * See the REDIS_RDB_ENC_* defines.
138 *
139 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
140 * values, will fit inside. */
141 #define REDIS_RDB_6BITLEN 0
142 #define REDIS_RDB_14BITLEN 1
143 #define REDIS_RDB_32BITLEN 2
144 #define REDIS_RDB_ENCVAL 3
145 #define REDIS_RDB_LENERR UINT_MAX
146
147 /* When a length of a string object stored on disk has the first two bits
148 * set, the remaining two bits specify a special encoding for the object
149 * accordingly to the following defines: */
150 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
151 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
152 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
153 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
154
155 /* Virtual memory object->where field. */
156 #define REDIS_VM_MEMORY 0 /* The object is on memory */
157 #define REDIS_VM_SWAPPED 1 /* The object is on disk */
158 #define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
159 #define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
160
161 /* Virtual memory static configuration stuff.
162 * Check vmFindContiguousPages() to know more about this magic numbers. */
163 #define REDIS_VM_MAX_NEAR_PAGES 65536
164 #define REDIS_VM_MAX_RANDOM_JUMP 4096
165
166 /* Client flags */
167 #define REDIS_CLOSE 1 /* This client connection should be closed ASAP */
168 #define REDIS_SLAVE 2 /* This client is a slave server */
169 #define REDIS_MASTER 4 /* This client is a master server */
170 #define REDIS_MONITOR 8 /* This client is a slave monitor, see MONITOR */
171 #define REDIS_MULTI 16 /* This client is in a MULTI context */
172 #define REDIS_BLOCKED 32 /* The client is waiting in a blocking operation */
173
174 /* Slave replication state - slave side */
175 #define REDIS_REPL_NONE 0 /* No active replication */
176 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
177 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
178
179 /* Slave replication state - from the point of view of master
180 * Note that in SEND_BULK and ONLINE state the slave receives new updates
181 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
182 * to start the next background saving in order to send updates to it. */
183 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
184 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
185 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
186 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
187
188 /* List related stuff */
189 #define REDIS_HEAD 0
190 #define REDIS_TAIL 1
191
192 /* Sort operations */
193 #define REDIS_SORT_GET 0
194 #define REDIS_SORT_ASC 1
195 #define REDIS_SORT_DESC 2
196 #define REDIS_SORTKEY_MAX 1024
197
198 /* Log levels */
199 #define REDIS_DEBUG 0
200 #define REDIS_NOTICE 1
201 #define REDIS_WARNING 2
202
203 /* Anti-warning macro... */
204 #define REDIS_NOTUSED(V) ((void) V)
205
206 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
207 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
208
209 /* Append only defines */
210 #define APPENDFSYNC_NO 0
211 #define APPENDFSYNC_ALWAYS 1
212 #define APPENDFSYNC_EVERYSEC 2
213
214 /* We can print the stacktrace, so our assert is defined this way: */
215 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e),exit(1)))
216 static void _redisAssert(char *estr);
217
218 /*================================= Data types ============================== */
219
220 /* A redis object, that is a type able to hold a string / list / set */
221
222 /* The VM object structure */
223 struct redisObjectVM {
224 off_t page; /* the page at witch the object is stored on disk */
225 off_t usedpages; /* number of pages used on disk */
226 time_t atime; /* Last access time */
227 } vm;
228
229 /* The actual Redis Object */
230 typedef struct redisObject {
231 void *ptr;
232 unsigned char type;
233 unsigned char encoding;
234 unsigned char storage; /* If this object is a key, where is the value?
235 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
236 unsigned char vtype; /* If this object is a key, and value is swapped out,
237 * this is the type of the swapped out object. */
238 int refcount;
239 /* VM fields, this are only allocated if VM is active, otherwise the
240 * object allocation function will just allocate
241 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
242 * Redis without VM active will not have any overhead. */
243 struct redisObjectVM vm;
244 } robj;
245
246 /* Macro used to initalize a Redis object allocated on the stack.
247 * Note that this macro is taken near the structure definition to make sure
248 * we'll update it when the structure is changed, to avoid bugs like
249 * bug #85 introduced exactly in this way. */
250 #define initStaticStringObject(_var,_ptr) do { \
251 _var.refcount = 1; \
252 _var.type = REDIS_STRING; \
253 _var.encoding = REDIS_ENCODING_RAW; \
254 _var.ptr = _ptr; \
255 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
256 } while(0);
257
258 typedef struct redisDb {
259 dict *dict; /* The keyspace for this DB */
260 dict *expires; /* Timeout of keys with a timeout set */
261 dict *blockingkeys; /* Keys with clients waiting for data (BLPOP) */
262 int id;
263 } redisDb;
264
265 /* Client MULTI/EXEC state */
266 typedef struct multiCmd {
267 robj **argv;
268 int argc;
269 struct redisCommand *cmd;
270 } multiCmd;
271
272 typedef struct multiState {
273 multiCmd *commands; /* Array of MULTI commands */
274 int count; /* Total number of MULTI commands */
275 } multiState;
276
277 /* With multiplexing we need to take per-clinet state.
278 * Clients are taken in a liked list. */
279 typedef struct redisClient {
280 int fd;
281 redisDb *db;
282 int dictid;
283 sds querybuf;
284 robj **argv, **mbargv;
285 int argc, mbargc;
286 int bulklen; /* bulk read len. -1 if not in bulk read mode */
287 int multibulk; /* multi bulk command format active */
288 list *reply;
289 int sentlen;
290 time_t lastinteraction; /* time of the last interaction, used for timeout */
291 int flags; /* REDIS_CLOSE | REDIS_SLAVE | REDIS_MONITOR */
292 /* REDIS_MULTI */
293 int slaveseldb; /* slave selected db, if this client is a slave */
294 int authenticated; /* when requirepass is non-NULL */
295 int replstate; /* replication state if this is a slave */
296 int repldbfd; /* replication DB file descriptor */
297 long repldboff; /* replication DB file offset */
298 off_t repldbsize; /* replication DB file size */
299 multiState mstate; /* MULTI/EXEC state */
300 robj **blockingkeys; /* The key we waiting to terminate a blocking
301 * operation such as BLPOP. Otherwise NULL. */
302 int blockingkeysnum; /* Number of blocking keys */
303 time_t blockingto; /* Blocking operation timeout. If UNIX current time
304 * is >= blockingto then the operation timed out. */
305 } redisClient;
306
307 struct saveparam {
308 time_t seconds;
309 int changes;
310 };
311
312 /* Global server state structure */
313 struct redisServer {
314 int port;
315 int fd;
316 redisDb *db;
317 dict *sharingpool; /* Poll used for object sharing */
318 unsigned int sharingpoolsize;
319 long long dirty; /* changes to DB from the last save */
320 list *clients;
321 list *slaves, *monitors;
322 char neterr[ANET_ERR_LEN];
323 aeEventLoop *el;
324 int cronloops; /* number of times the cron function run */
325 list *objfreelist; /* A list of freed objects to avoid malloc() */
326 time_t lastsave; /* Unix time of last save succeeede */
327 size_t usedmemory; /* Used memory in megabytes */
328 /* Fields used only for stats */
329 time_t stat_starttime; /* server start time */
330 long long stat_numcommands; /* number of processed commands */
331 long long stat_numconnections; /* number of connections received */
332 /* Configuration */
333 int verbosity;
334 int glueoutputbuf;
335 int maxidletime;
336 int dbnum;
337 int daemonize;
338 int appendonly;
339 int appendfsync;
340 time_t lastfsync;
341 int appendfd;
342 int appendseldb;
343 char *pidfile;
344 pid_t bgsavechildpid;
345 pid_t bgrewritechildpid;
346 sds bgrewritebuf; /* buffer taken by parent during oppend only rewrite */
347 struct saveparam *saveparams;
348 int saveparamslen;
349 char *logfile;
350 char *bindaddr;
351 char *dbfilename;
352 char *appendfilename;
353 char *requirepass;
354 int shareobjects;
355 int rdbcompression;
356 /* Replication related */
357 int isslave;
358 char *masterauth;
359 char *masterhost;
360 int masterport;
361 redisClient *master; /* client that is master for this slave */
362 int replstate;
363 unsigned int maxclients;
364 unsigned long long maxmemory;
365 unsigned int blockedclients;
366 /* Sort parameters - qsort_r() is only available under BSD so we
367 * have to take this state global, in order to pass it to sortCompare() */
368 int sort_desc;
369 int sort_alpha;
370 int sort_bypattern;
371 /* Virtual memory configuration */
372 int vm_enabled;
373 off_t vm_page_size;
374 off_t vm_pages;
375 unsigned long long vm_max_memory;
376 /* Virtual memory state */
377 FILE *vm_fp;
378 int vm_fd;
379 off_t vm_next_page; /* Next probably empty page */
380 off_t vm_near_pages; /* Number of pages allocated sequentially */
381 unsigned char *vm_bitmap; /* Bitmap of free/used pages */
382 time_t unixtime; /* Unix time sampled every second. */
383 };
384
385 typedef void redisCommandProc(redisClient *c);
386 struct redisCommand {
387 char *name;
388 redisCommandProc *proc;
389 int arity;
390 int flags;
391 };
392
393 struct redisFunctionSym {
394 char *name;
395 unsigned long pointer;
396 };
397
398 typedef struct _redisSortObject {
399 robj *obj;
400 union {
401 double score;
402 robj *cmpobj;
403 } u;
404 } redisSortObject;
405
406 typedef struct _redisSortOperation {
407 int type;
408 robj *pattern;
409 } redisSortOperation;
410
411 /* ZSETs use a specialized version of Skiplists */
412
413 typedef struct zskiplistNode {
414 struct zskiplistNode **forward;
415 struct zskiplistNode *backward;
416 double score;
417 robj *obj;
418 } zskiplistNode;
419
420 typedef struct zskiplist {
421 struct zskiplistNode *header, *tail;
422 unsigned long length;
423 int level;
424 } zskiplist;
425
426 typedef struct zset {
427 dict *dict;
428 zskiplist *zsl;
429 } zset;
430
431 /* Our shared "common" objects */
432
433 struct sharedObjectsStruct {
434 robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *pong, *space,
435 *colon, *nullbulk, *nullmultibulk, *queued,
436 *emptymultibulk, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
437 *outofrangeerr, *plus,
438 *select0, *select1, *select2, *select3, *select4,
439 *select5, *select6, *select7, *select8, *select9;
440 } shared;
441
442 /* Global vars that are actally used as constants. The following double
443 * values are used for double on-disk serialization, and are initialized
444 * at runtime to avoid strange compiler optimizations. */
445
446 static double R_Zero, R_PosInf, R_NegInf, R_Nan;
447
448 /*================================ Prototypes =============================== */
449
450 static void freeStringObject(robj *o);
451 static void freeListObject(robj *o);
452 static void freeSetObject(robj *o);
453 static void decrRefCount(void *o);
454 static robj *createObject(int type, void *ptr);
455 static void freeClient(redisClient *c);
456 static int rdbLoad(char *filename);
457 static void addReply(redisClient *c, robj *obj);
458 static void addReplySds(redisClient *c, sds s);
459 static void incrRefCount(robj *o);
460 static int rdbSaveBackground(char *filename);
461 static robj *createStringObject(char *ptr, size_t len);
462 static robj *dupStringObject(robj *o);
463 static void replicationFeedSlaves(list *slaves, struct redisCommand *cmd, int dictid, robj **argv, int argc);
464 static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc);
465 static int syncWithMaster(void);
466 static robj *tryObjectSharing(robj *o);
467 static int tryObjectEncoding(robj *o);
468 static robj *getDecodedObject(robj *o);
469 static int removeExpire(redisDb *db, robj *key);
470 static int expireIfNeeded(redisDb *db, robj *key);
471 static int deleteIfVolatile(redisDb *db, robj *key);
472 static int deleteKey(redisDb *db, robj *key);
473 static time_t getExpire(redisDb *db, robj *key);
474 static int setExpire(redisDb *db, robj *key, time_t when);
475 static void updateSlavesWaitingBgsave(int bgsaveerr);
476 static void freeMemoryIfNeeded(void);
477 static int processCommand(redisClient *c);
478 static void setupSigSegvAction(void);
479 static void rdbRemoveTempFile(pid_t childpid);
480 static void aofRemoveTempFile(pid_t childpid);
481 static size_t stringObjectLen(robj *o);
482 static void processInputBuffer(redisClient *c);
483 static zskiplist *zslCreate(void);
484 static void zslFree(zskiplist *zsl);
485 static void zslInsert(zskiplist *zsl, double score, robj *obj);
486 static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask);
487 static void initClientMultiState(redisClient *c);
488 static void freeClientMultiState(redisClient *c);
489 static void queueMultiCommand(redisClient *c, struct redisCommand *cmd);
490 static void unblockClient(redisClient *c);
491 static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele);
492 static void vmInit(void);
493 static void vmMarkPagesFree(off_t page, off_t count);
494 static robj *vmLoadObject(robj *key);
495 static int vmSwapOneObject(void);
496
497 static void authCommand(redisClient *c);
498 static void pingCommand(redisClient *c);
499 static void echoCommand(redisClient *c);
500 static void setCommand(redisClient *c);
501 static void setnxCommand(redisClient *c);
502 static void getCommand(redisClient *c);
503 static void delCommand(redisClient *c);
504 static void existsCommand(redisClient *c);
505 static void incrCommand(redisClient *c);
506 static void decrCommand(redisClient *c);
507 static void incrbyCommand(redisClient *c);
508 static void decrbyCommand(redisClient *c);
509 static void selectCommand(redisClient *c);
510 static void randomkeyCommand(redisClient *c);
511 static void keysCommand(redisClient *c);
512 static void dbsizeCommand(redisClient *c);
513 static void lastsaveCommand(redisClient *c);
514 static void saveCommand(redisClient *c);
515 static void bgsaveCommand(redisClient *c);
516 static void bgrewriteaofCommand(redisClient *c);
517 static void shutdownCommand(redisClient *c);
518 static void moveCommand(redisClient *c);
519 static void renameCommand(redisClient *c);
520 static void renamenxCommand(redisClient *c);
521 static void lpushCommand(redisClient *c);
522 static void rpushCommand(redisClient *c);
523 static void lpopCommand(redisClient *c);
524 static void rpopCommand(redisClient *c);
525 static void llenCommand(redisClient *c);
526 static void lindexCommand(redisClient *c);
527 static void lrangeCommand(redisClient *c);
528 static void ltrimCommand(redisClient *c);
529 static void typeCommand(redisClient *c);
530 static void lsetCommand(redisClient *c);
531 static void saddCommand(redisClient *c);
532 static void sremCommand(redisClient *c);
533 static void smoveCommand(redisClient *c);
534 static void sismemberCommand(redisClient *c);
535 static void scardCommand(redisClient *c);
536 static void spopCommand(redisClient *c);
537 static void srandmemberCommand(redisClient *c);
538 static void sinterCommand(redisClient *c);
539 static void sinterstoreCommand(redisClient *c);
540 static void sunionCommand(redisClient *c);
541 static void sunionstoreCommand(redisClient *c);
542 static void sdiffCommand(redisClient *c);
543 static void sdiffstoreCommand(redisClient *c);
544 static void syncCommand(redisClient *c);
545 static void flushdbCommand(redisClient *c);
546 static void flushallCommand(redisClient *c);
547 static void sortCommand(redisClient *c);
548 static void lremCommand(redisClient *c);
549 static void rpoplpushcommand(redisClient *c);
550 static void infoCommand(redisClient *c);
551 static void mgetCommand(redisClient *c);
552 static void monitorCommand(redisClient *c);
553 static void expireCommand(redisClient *c);
554 static void expireatCommand(redisClient *c);
555 static void getsetCommand(redisClient *c);
556 static void ttlCommand(redisClient *c);
557 static void slaveofCommand(redisClient *c);
558 static void debugCommand(redisClient *c);
559 static void msetCommand(redisClient *c);
560 static void msetnxCommand(redisClient *c);
561 static void zaddCommand(redisClient *c);
562 static void zincrbyCommand(redisClient *c);
563 static void zrangeCommand(redisClient *c);
564 static void zrangebyscoreCommand(redisClient *c);
565 static void zrevrangeCommand(redisClient *c);
566 static void zcardCommand(redisClient *c);
567 static void zremCommand(redisClient *c);
568 static void zscoreCommand(redisClient *c);
569 static void zremrangebyscoreCommand(redisClient *c);
570 static void multiCommand(redisClient *c);
571 static void execCommand(redisClient *c);
572 static void blpopCommand(redisClient *c);
573 static void brpopCommand(redisClient *c);
574
575 /*================================= Globals ================================= */
576
577 /* Global vars */
578 static struct redisServer server; /* server global state */
579 static struct redisCommand cmdTable[] = {
580 {"get",getCommand,2,REDIS_CMD_INLINE},
581 {"set",setCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM},
582 {"setnx",setnxCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM},
583 {"del",delCommand,-2,REDIS_CMD_INLINE},
584 {"exists",existsCommand,2,REDIS_CMD_INLINE},
585 {"incr",incrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM},
586 {"decr",decrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM},
587 {"mget",mgetCommand,-2,REDIS_CMD_INLINE},
588 {"rpush",rpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM},
589 {"lpush",lpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM},
590 {"rpop",rpopCommand,2,REDIS_CMD_INLINE},
591 {"lpop",lpopCommand,2,REDIS_CMD_INLINE},
592 {"brpop",brpopCommand,-3,REDIS_CMD_INLINE},
593 {"blpop",blpopCommand,-3,REDIS_CMD_INLINE},
594 {"llen",llenCommand,2,REDIS_CMD_INLINE},
595 {"lindex",lindexCommand,3,REDIS_CMD_INLINE},
596 {"lset",lsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM},
597 {"lrange",lrangeCommand,4,REDIS_CMD_INLINE},
598 {"ltrim",ltrimCommand,4,REDIS_CMD_INLINE},
599 {"lrem",lremCommand,4,REDIS_CMD_BULK},
600 {"rpoplpush",rpoplpushcommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM},
601 {"sadd",saddCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM},
602 {"srem",sremCommand,3,REDIS_CMD_BULK},
603 {"smove",smoveCommand,4,REDIS_CMD_BULK},
604 {"sismember",sismemberCommand,3,REDIS_CMD_BULK},
605 {"scard",scardCommand,2,REDIS_CMD_INLINE},
606 {"spop",spopCommand,2,REDIS_CMD_INLINE},
607 {"srandmember",srandmemberCommand,2,REDIS_CMD_INLINE},
608 {"sinter",sinterCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM},
609 {"sinterstore",sinterstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM},
610 {"sunion",sunionCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM},
611 {"sunionstore",sunionstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM},
612 {"sdiff",sdiffCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM},
613 {"sdiffstore",sdiffstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM},
614 {"smembers",sinterCommand,2,REDIS_CMD_INLINE},
615 {"zadd",zaddCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM},
616 {"zincrby",zincrbyCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM},
617 {"zrem",zremCommand,3,REDIS_CMD_BULK},
618 {"zremrangebyscore",zremrangebyscoreCommand,4,REDIS_CMD_INLINE},
619 {"zrange",zrangeCommand,-4,REDIS_CMD_INLINE},
620 {"zrangebyscore",zrangebyscoreCommand,-4,REDIS_CMD_INLINE},
621 {"zrevrange",zrevrangeCommand,-4,REDIS_CMD_INLINE},
622 {"zcard",zcardCommand,2,REDIS_CMD_INLINE},
623 {"zscore",zscoreCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM},
624 {"incrby",incrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM},
625 {"decrby",decrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM},
626 {"getset",getsetCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM},
627 {"mset",msetCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM},
628 {"msetnx",msetnxCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM},
629 {"randomkey",randomkeyCommand,1,REDIS_CMD_INLINE},
630 {"select",selectCommand,2,REDIS_CMD_INLINE},
631 {"move",moveCommand,3,REDIS_CMD_INLINE},
632 {"rename",renameCommand,3,REDIS_CMD_INLINE},
633 {"renamenx",renamenxCommand,3,REDIS_CMD_INLINE},
634 {"expire",expireCommand,3,REDIS_CMD_INLINE},
635 {"expireat",expireatCommand,3,REDIS_CMD_INLINE},
636 {"keys",keysCommand,2,REDIS_CMD_INLINE},
637 {"dbsize",dbsizeCommand,1,REDIS_CMD_INLINE},
638 {"auth",authCommand,2,REDIS_CMD_INLINE},
639 {"ping",pingCommand,1,REDIS_CMD_INLINE},
640 {"echo",echoCommand,2,REDIS_CMD_BULK},
641 {"save",saveCommand,1,REDIS_CMD_INLINE},
642 {"bgsave",bgsaveCommand,1,REDIS_CMD_INLINE},
643 {"bgrewriteaof",bgrewriteaofCommand,1,REDIS_CMD_INLINE},
644 {"shutdown",shutdownCommand,1,REDIS_CMD_INLINE},
645 {"lastsave",lastsaveCommand,1,REDIS_CMD_INLINE},
646 {"type",typeCommand,2,REDIS_CMD_INLINE},
647 {"multi",multiCommand,1,REDIS_CMD_INLINE},
648 {"exec",execCommand,1,REDIS_CMD_INLINE},
649 {"sync",syncCommand,1,REDIS_CMD_INLINE},
650 {"flushdb",flushdbCommand,1,REDIS_CMD_INLINE},
651 {"flushall",flushallCommand,1,REDIS_CMD_INLINE},
652 {"sort",sortCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM},
653 {"info",infoCommand,1,REDIS_CMD_INLINE},
654 {"monitor",monitorCommand,1,REDIS_CMD_INLINE},
655 {"ttl",ttlCommand,2,REDIS_CMD_INLINE},
656 {"slaveof",slaveofCommand,3,REDIS_CMD_INLINE},
657 {"debug",debugCommand,-2,REDIS_CMD_INLINE},
658 {NULL,NULL,0,0}
659 };
660
661 /*============================ Utility functions ============================ */
662
663 /* Glob-style pattern matching. */
664 int stringmatchlen(const char *pattern, int patternLen,
665 const char *string, int stringLen, int nocase)
666 {
667 while(patternLen) {
668 switch(pattern[0]) {
669 case '*':
670 while (pattern[1] == '*') {
671 pattern++;
672 patternLen--;
673 }
674 if (patternLen == 1)
675 return 1; /* match */
676 while(stringLen) {
677 if (stringmatchlen(pattern+1, patternLen-1,
678 string, stringLen, nocase))
679 return 1; /* match */
680 string++;
681 stringLen--;
682 }
683 return 0; /* no match */
684 break;
685 case '?':
686 if (stringLen == 0)
687 return 0; /* no match */
688 string++;
689 stringLen--;
690 break;
691 case '[':
692 {
693 int not, match;
694
695 pattern++;
696 patternLen--;
697 not = pattern[0] == '^';
698 if (not) {
699 pattern++;
700 patternLen--;
701 }
702 match = 0;
703 while(1) {
704 if (pattern[0] == '\\') {
705 pattern++;
706 patternLen--;
707 if (pattern[0] == string[0])
708 match = 1;
709 } else if (pattern[0] == ']') {
710 break;
711 } else if (patternLen == 0) {
712 pattern--;
713 patternLen++;
714 break;
715 } else if (pattern[1] == '-' && patternLen >= 3) {
716 int start = pattern[0];
717 int end = pattern[2];
718 int c = string[0];
719 if (start > end) {
720 int t = start;
721 start = end;
722 end = t;
723 }
724 if (nocase) {
725 start = tolower(start);
726 end = tolower(end);
727 c = tolower(c);
728 }
729 pattern += 2;
730 patternLen -= 2;
731 if (c >= start && c <= end)
732 match = 1;
733 } else {
734 if (!nocase) {
735 if (pattern[0] == string[0])
736 match = 1;
737 } else {
738 if (tolower((int)pattern[0]) == tolower((int)string[0]))
739 match = 1;
740 }
741 }
742 pattern++;
743 patternLen--;
744 }
745 if (not)
746 match = !match;
747 if (!match)
748 return 0; /* no match */
749 string++;
750 stringLen--;
751 break;
752 }
753 case '\\':
754 if (patternLen >= 2) {
755 pattern++;
756 patternLen--;
757 }
758 /* fall through */
759 default:
760 if (!nocase) {
761 if (pattern[0] != string[0])
762 return 0; /* no match */
763 } else {
764 if (tolower((int)pattern[0]) != tolower((int)string[0]))
765 return 0; /* no match */
766 }
767 string++;
768 stringLen--;
769 break;
770 }
771 pattern++;
772 patternLen--;
773 if (stringLen == 0) {
774 while(*pattern == '*') {
775 pattern++;
776 patternLen--;
777 }
778 break;
779 }
780 }
781 if (patternLen == 0 && stringLen == 0)
782 return 1;
783 return 0;
784 }
785
786 static void redisLog(int level, const char *fmt, ...) {
787 va_list ap;
788 FILE *fp;
789
790 fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a");
791 if (!fp) return;
792
793 va_start(ap, fmt);
794 if (level >= server.verbosity) {
795 char *c = ".-*";
796 char buf[64];
797 time_t now;
798
799 now = time(NULL);
800 strftime(buf,64,"%d %b %H:%M:%S",localtime(&now));
801 fprintf(fp,"%s %c ",buf,c[level]);
802 vfprintf(fp, fmt, ap);
803 fprintf(fp,"\n");
804 fflush(fp);
805 }
806 va_end(ap);
807
808 if (server.logfile) fclose(fp);
809 }
810
811 /*====================== Hash table type implementation ==================== */
812
813 /* This is an hash table type that uses the SDS dynamic strings libary as
814 * keys and radis objects as values (objects can hold SDS strings,
815 * lists, sets). */
816
817 static void dictVanillaFree(void *privdata, void *val)
818 {
819 DICT_NOTUSED(privdata);
820 zfree(val);
821 }
822
823 static void dictListDestructor(void *privdata, void *val)
824 {
825 DICT_NOTUSED(privdata);
826 listRelease((list*)val);
827 }
828
829 static int sdsDictKeyCompare(void *privdata, const void *key1,
830 const void *key2)
831 {
832 int l1,l2;
833 DICT_NOTUSED(privdata);
834
835 l1 = sdslen((sds)key1);
836 l2 = sdslen((sds)key2);
837 if (l1 != l2) return 0;
838 return memcmp(key1, key2, l1) == 0;
839 }
840
841 static void dictRedisObjectDestructor(void *privdata, void *val)
842 {
843 DICT_NOTUSED(privdata);
844
845 if (val == NULL) return; /* Values of swapped out keys as set to NULL */
846 decrRefCount(val);
847 }
848
849 static int dictObjKeyCompare(void *privdata, const void *key1,
850 const void *key2)
851 {
852 const robj *o1 = key1, *o2 = key2;
853 return sdsDictKeyCompare(privdata,o1->ptr,o2->ptr);
854 }
855
856 static unsigned int dictObjHash(const void *key) {
857 const robj *o = key;
858 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
859 }
860
861 static int dictEncObjKeyCompare(void *privdata, const void *key1,
862 const void *key2)
863 {
864 robj *o1 = (robj*) key1, *o2 = (robj*) key2;
865 int cmp;
866
867 o1 = getDecodedObject(o1);
868 o2 = getDecodedObject(o2);
869 cmp = sdsDictKeyCompare(privdata,o1->ptr,o2->ptr);
870 decrRefCount(o1);
871 decrRefCount(o2);
872 return cmp;
873 }
874
875 static unsigned int dictEncObjHash(const void *key) {
876 robj *o = (robj*) key;
877
878 o = getDecodedObject(o);
879 unsigned int hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
880 decrRefCount(o);
881 return hash;
882 }
883
884 static dictType setDictType = {
885 dictEncObjHash, /* hash function */
886 NULL, /* key dup */
887 NULL, /* val dup */
888 dictEncObjKeyCompare, /* key compare */
889 dictRedisObjectDestructor, /* key destructor */
890 NULL /* val destructor */
891 };
892
893 static dictType zsetDictType = {
894 dictEncObjHash, /* hash function */
895 NULL, /* key dup */
896 NULL, /* val dup */
897 dictEncObjKeyCompare, /* key compare */
898 dictRedisObjectDestructor, /* key destructor */
899 dictVanillaFree /* val destructor of malloc(sizeof(double)) */
900 };
901
902 static dictType hashDictType = {
903 dictObjHash, /* hash function */
904 NULL, /* key dup */
905 NULL, /* val dup */
906 dictObjKeyCompare, /* key compare */
907 dictRedisObjectDestructor, /* key destructor */
908 dictRedisObjectDestructor /* val destructor */
909 };
910
911 /* Keylist hash table type has unencoded redis objects as keys and
912 * lists as values. It's used for blocking operations (BLPOP) */
913 static dictType keylistDictType = {
914 dictObjHash, /* hash function */
915 NULL, /* key dup */
916 NULL, /* val dup */
917 dictObjKeyCompare, /* key compare */
918 dictRedisObjectDestructor, /* key destructor */
919 dictListDestructor /* val destructor */
920 };
921
922 /* ========================= Random utility functions ======================= */
923
924 /* Redis generally does not try to recover from out of memory conditions
925 * when allocating objects or strings, it is not clear if it will be possible
926 * to report this condition to the client since the networking layer itself
927 * is based on heap allocation for send buffers, so we simply abort.
928 * At least the code will be simpler to read... */
929 static void oom(const char *msg) {
930 redisLog(REDIS_WARNING, "%s: Out of memory\n",msg);
931 sleep(1);
932 abort();
933 }
934
935 /* ====================== Redis server networking stuff ===================== */
936 static void closeTimedoutClients(void) {
937 redisClient *c;
938 listNode *ln;
939 time_t now = time(NULL);
940
941 listRewind(server.clients);
942 while ((ln = listYield(server.clients)) != NULL) {
943 c = listNodeValue(ln);
944 if (server.maxidletime &&
945 !(c->flags & REDIS_SLAVE) && /* no timeout for slaves */
946 !(c->flags & REDIS_MASTER) && /* no timeout for masters */
947 (now - c->lastinteraction > server.maxidletime))
948 {
949 redisLog(REDIS_DEBUG,"Closing idle client");
950 freeClient(c);
951 } else if (c->flags & REDIS_BLOCKED) {
952 if (c->blockingto != 0 && c->blockingto < now) {
953 addReply(c,shared.nullmultibulk);
954 unblockClient(c);
955 }
956 }
957 }
958 }
959
960 static int htNeedsResize(dict *dict) {
961 long long size, used;
962
963 size = dictSlots(dict);
964 used = dictSize(dict);
965 return (size && used && size > DICT_HT_INITIAL_SIZE &&
966 (used*100/size < REDIS_HT_MINFILL));
967 }
968
969 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
970 * we resize the hash table to save memory */
971 static void tryResizeHashTables(void) {
972 int j;
973
974 for (j = 0; j < server.dbnum; j++) {
975 if (htNeedsResize(server.db[j].dict)) {
976 redisLog(REDIS_DEBUG,"The hash table %d is too sparse, resize it...",j);
977 dictResize(server.db[j].dict);
978 redisLog(REDIS_DEBUG,"Hash table %d resized.",j);
979 }
980 if (htNeedsResize(server.db[j].expires))
981 dictResize(server.db[j].expires);
982 }
983 }
984
985 /* A background saving child (BGSAVE) terminated its work. Handle this. */
986 void backgroundSaveDoneHandler(int statloc) {
987 int exitcode = WEXITSTATUS(statloc);
988 int bysignal = WIFSIGNALED(statloc);
989
990 if (!bysignal && exitcode == 0) {
991 redisLog(REDIS_NOTICE,
992 "Background saving terminated with success");
993 server.dirty = 0;
994 server.lastsave = time(NULL);
995 } else if (!bysignal && exitcode != 0) {
996 redisLog(REDIS_WARNING, "Background saving error");
997 } else {
998 redisLog(REDIS_WARNING,
999 "Background saving terminated by signal");
1000 rdbRemoveTempFile(server.bgsavechildpid);
1001 }
1002 server.bgsavechildpid = -1;
1003 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1004 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1005 updateSlavesWaitingBgsave(exitcode == 0 ? REDIS_OK : REDIS_ERR);
1006 }
1007
1008 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1009 * Handle this. */
1010 void backgroundRewriteDoneHandler(int statloc) {
1011 int exitcode = WEXITSTATUS(statloc);
1012 int bysignal = WIFSIGNALED(statloc);
1013
1014 if (!bysignal && exitcode == 0) {
1015 int fd;
1016 char tmpfile[256];
1017
1018 redisLog(REDIS_NOTICE,
1019 "Background append only file rewriting terminated with success");
1020 /* Now it's time to flush the differences accumulated by the parent */
1021 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) server.bgrewritechildpid);
1022 fd = open(tmpfile,O_WRONLY|O_APPEND);
1023 if (fd == -1) {
1024 redisLog(REDIS_WARNING, "Not able to open the temp append only file produced by the child: %s", strerror(errno));
1025 goto cleanup;
1026 }
1027 /* Flush our data... */
1028 if (write(fd,server.bgrewritebuf,sdslen(server.bgrewritebuf)) !=
1029 (signed) sdslen(server.bgrewritebuf)) {
1030 redisLog(REDIS_WARNING, "Error or short write trying to flush the parent diff of the append log file in the child temp file: %s", strerror(errno));
1031 close(fd);
1032 goto cleanup;
1033 }
1034 redisLog(REDIS_NOTICE,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server.bgrewritebuf));
1035 /* Now our work is to rename the temp file into the stable file. And
1036 * switch the file descriptor used by the server for append only. */
1037 if (rename(tmpfile,server.appendfilename) == -1) {
1038 redisLog(REDIS_WARNING,"Can't rename the temp append only file into the stable one: %s", strerror(errno));
1039 close(fd);
1040 goto cleanup;
1041 }
1042 /* Mission completed... almost */
1043 redisLog(REDIS_NOTICE,"Append only file successfully rewritten.");
1044 if (server.appendfd != -1) {
1045 /* If append only is actually enabled... */
1046 close(server.appendfd);
1047 server.appendfd = fd;
1048 fsync(fd);
1049 server.appendseldb = -1; /* Make sure it will issue SELECT */
1050 redisLog(REDIS_NOTICE,"The new append only file was selected for future appends.");
1051 } else {
1052 /* If append only is disabled we just generate a dump in this
1053 * format. Why not? */
1054 close(fd);
1055 }
1056 } else if (!bysignal && exitcode != 0) {
1057 redisLog(REDIS_WARNING, "Background append only file rewriting error");
1058 } else {
1059 redisLog(REDIS_WARNING,
1060 "Background append only file rewriting terminated by signal");
1061 }
1062 cleanup:
1063 sdsfree(server.bgrewritebuf);
1064 server.bgrewritebuf = sdsempty();
1065 aofRemoveTempFile(server.bgrewritechildpid);
1066 server.bgrewritechildpid = -1;
1067 }
1068
1069 static int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
1070 int j, loops = server.cronloops++;
1071 REDIS_NOTUSED(eventLoop);
1072 REDIS_NOTUSED(id);
1073 REDIS_NOTUSED(clientData);
1074
1075 /* We take a cached value of the unix time in the global state because
1076 * with virtual memory and aging there is to store the current time
1077 * in objects at every object access, and accuracy is not needed.
1078 * To access a global var is faster than calling time(NULL) */
1079 server.unixtime = time(NULL);
1080
1081 /* Update the global state with the amount of used memory */
1082 server.usedmemory = zmalloc_used_memory();
1083
1084 /* Show some info about non-empty databases */
1085 for (j = 0; j < server.dbnum; j++) {
1086 long long size, used, vkeys;
1087
1088 size = dictSlots(server.db[j].dict);
1089 used = dictSize(server.db[j].dict);
1090 vkeys = dictSize(server.db[j].expires);
1091 if (!(loops % 5) && (used || vkeys)) {
1092 redisLog(REDIS_DEBUG,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);
1093 /* dictPrintStats(server.dict); */
1094 }
1095 }
1096
1097 /* We don't want to resize the hash tables while a bacground saving
1098 * is in progress: the saving child is created using fork() that is
1099 * implemented with a copy-on-write semantic in most modern systems, so
1100 * if we resize the HT while there is the saving child at work actually
1101 * a lot of memory movements in the parent will cause a lot of pages
1102 * copied. */
1103 if (server.bgsavechildpid == -1) tryResizeHashTables();
1104
1105 /* Show information about connected clients */
1106 if (!(loops % 5)) {
1107 redisLog(REDIS_DEBUG,"%d clients connected (%d slaves), %zu bytes in use, %d shared objects",
1108 listLength(server.clients)-listLength(server.slaves),
1109 listLength(server.slaves),
1110 server.usedmemory,
1111 dictSize(server.sharingpool));
1112 }
1113
1114 /* Close connections of timedout clients */
1115 if ((server.maxidletime && !(loops % 10)) || server.blockedclients)
1116 closeTimedoutClients();
1117
1118 /* Check if a background saving or AOF rewrite in progress terminated */
1119 if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) {
1120 int statloc;
1121 pid_t pid;
1122
1123 if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
1124 if (pid == server.bgsavechildpid) {
1125 backgroundSaveDoneHandler(statloc);
1126 } else {
1127 backgroundRewriteDoneHandler(statloc);
1128 }
1129 }
1130 } else {
1131 /* If there is not a background saving in progress check if
1132 * we have to save now */
1133 time_t now = time(NULL);
1134 for (j = 0; j < server.saveparamslen; j++) {
1135 struct saveparam *sp = server.saveparams+j;
1136
1137 if (server.dirty >= sp->changes &&
1138 now-server.lastsave > sp->seconds) {
1139 redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
1140 sp->changes, sp->seconds);
1141 rdbSaveBackground(server.dbfilename);
1142 break;
1143 }
1144 }
1145 }
1146
1147 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1148 * will use few CPU cycles if there are few expiring keys, otherwise
1149 * it will get more aggressive to avoid that too much memory is used by
1150 * keys that can be removed from the keyspace. */
1151 for (j = 0; j < server.dbnum; j++) {
1152 int expired;
1153 redisDb *db = server.db+j;
1154
1155 /* Continue to expire if at the end of the cycle more than 25%
1156 * of the keys were expired. */
1157 do {
1158 long num = dictSize(db->expires);
1159 time_t now = time(NULL);
1160
1161 expired = 0;
1162 if (num > REDIS_EXPIRELOOKUPS_PER_CRON)
1163 num = REDIS_EXPIRELOOKUPS_PER_CRON;
1164 while (num--) {
1165 dictEntry *de;
1166 time_t t;
1167
1168 if ((de = dictGetRandomKey(db->expires)) == NULL) break;
1169 t = (time_t) dictGetEntryVal(de);
1170 if (now > t) {
1171 deleteKey(db,dictGetEntryKey(de));
1172 expired++;
1173 }
1174 }
1175 } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4);
1176 }
1177
1178 /* Swap a few keys on disk if we are over the memory limit and VM
1179 * is enbled. */
1180 while (server.vm_enabled && zmalloc_used_memory() > server.vm_max_memory) {
1181 if (vmSwapOneObject() == REDIS_ERR) {
1182 redisLog(REDIS_WARNING,"WARNING: vm-max-memory limit reached but unable to swap more objects out!");
1183 break;
1184 }
1185 }
1186
1187 /* Check if we should connect to a MASTER */
1188 if (server.replstate == REDIS_REPL_CONNECT) {
1189 redisLog(REDIS_NOTICE,"Connecting to MASTER...");
1190 if (syncWithMaster() == REDIS_OK) {
1191 redisLog(REDIS_NOTICE,"MASTER <-> SLAVE sync succeeded");
1192 }
1193 }
1194 return 1000;
1195 }
1196
1197 static void createSharedObjects(void) {
1198 shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n"));
1199 shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n"));
1200 shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n"));
1201 shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n"));
1202 shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n"));
1203 shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n"));
1204 shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n"));
1205 shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n"));
1206 shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n"));
1207 shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n"));
1208 shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n"));
1209 shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew(
1210 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1211 shared.nokeyerr = createObject(REDIS_STRING,sdsnew(
1212 "-ERR no such key\r\n"));
1213 shared.syntaxerr = createObject(REDIS_STRING,sdsnew(
1214 "-ERR syntax error\r\n"));
1215 shared.sameobjecterr = createObject(REDIS_STRING,sdsnew(
1216 "-ERR source and destination objects are the same\r\n"));
1217 shared.outofrangeerr = createObject(REDIS_STRING,sdsnew(
1218 "-ERR index out of range\r\n"));
1219 shared.space = createObject(REDIS_STRING,sdsnew(" "));
1220 shared.colon = createObject(REDIS_STRING,sdsnew(":"));
1221 shared.plus = createObject(REDIS_STRING,sdsnew("+"));
1222 shared.select0 = createStringObject("select 0\r\n",10);
1223 shared.select1 = createStringObject("select 1\r\n",10);
1224 shared.select2 = createStringObject("select 2\r\n",10);
1225 shared.select3 = createStringObject("select 3\r\n",10);
1226 shared.select4 = createStringObject("select 4\r\n",10);
1227 shared.select5 = createStringObject("select 5\r\n",10);
1228 shared.select6 = createStringObject("select 6\r\n",10);
1229 shared.select7 = createStringObject("select 7\r\n",10);
1230 shared.select8 = createStringObject("select 8\r\n",10);
1231 shared.select9 = createStringObject("select 9\r\n",10);
1232 }
1233
1234 static void appendServerSaveParams(time_t seconds, int changes) {
1235 server.saveparams = zrealloc(server.saveparams,sizeof(struct saveparam)*(server.saveparamslen+1));
1236 server.saveparams[server.saveparamslen].seconds = seconds;
1237 server.saveparams[server.saveparamslen].changes = changes;
1238 server.saveparamslen++;
1239 }
1240
1241 static void resetServerSaveParams() {
1242 zfree(server.saveparams);
1243 server.saveparams = NULL;
1244 server.saveparamslen = 0;
1245 }
1246
1247 static void initServerConfig() {
1248 server.dbnum = REDIS_DEFAULT_DBNUM;
1249 server.port = REDIS_SERVERPORT;
1250 server.verbosity = REDIS_DEBUG;
1251 server.maxidletime = REDIS_MAXIDLETIME;
1252 server.saveparams = NULL;
1253 server.logfile = NULL; /* NULL = log on standard output */
1254 server.bindaddr = NULL;
1255 server.glueoutputbuf = 1;
1256 server.daemonize = 0;
1257 server.appendonly = 0;
1258 server.appendfsync = APPENDFSYNC_ALWAYS;
1259 server.lastfsync = time(NULL);
1260 server.appendfd = -1;
1261 server.appendseldb = -1; /* Make sure the first time will not match */
1262 server.pidfile = "/var/run/redis.pid";
1263 server.dbfilename = "dump.rdb";
1264 server.appendfilename = "appendonly.aof";
1265 server.requirepass = NULL;
1266 server.shareobjects = 0;
1267 server.rdbcompression = 1;
1268 server.sharingpoolsize = 1024;
1269 server.maxclients = 0;
1270 server.blockedclients = 0;
1271 server.maxmemory = 0;
1272 server.vm_enabled = 0;
1273 server.vm_page_size = 256; /* 256 bytes per page */
1274 server.vm_pages = 1024*1024*100; /* 104 millions of pages */
1275 server.vm_max_memory = 1024LL*1024*1024*1; /* 1 GB of RAM */
1276
1277 resetServerSaveParams();
1278
1279 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1280 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1281 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1282 /* Replication related */
1283 server.isslave = 0;
1284 server.masterauth = NULL;
1285 server.masterhost = NULL;
1286 server.masterport = 6379;
1287 server.master = NULL;
1288 server.replstate = REDIS_REPL_NONE;
1289
1290 /* Double constants initialization */
1291 R_Zero = 0.0;
1292 R_PosInf = 1.0/R_Zero;
1293 R_NegInf = -1.0/R_Zero;
1294 R_Nan = R_Zero/R_Zero;
1295 }
1296
1297 static void initServer() {
1298 int j;
1299
1300 signal(SIGHUP, SIG_IGN);
1301 signal(SIGPIPE, SIG_IGN);
1302 setupSigSegvAction();
1303
1304 server.clients = listCreate();
1305 server.slaves = listCreate();
1306 server.monitors = listCreate();
1307 server.objfreelist = listCreate();
1308 createSharedObjects();
1309 server.el = aeCreateEventLoop();
1310 server.db = zmalloc(sizeof(redisDb)*server.dbnum);
1311 server.sharingpool = dictCreate(&setDictType,NULL);
1312 server.fd = anetTcpServer(server.neterr, server.port, server.bindaddr);
1313 if (server.fd == -1) {
1314 redisLog(REDIS_WARNING, "Opening TCP port: %s", server.neterr);
1315 exit(1);
1316 }
1317 for (j = 0; j < server.dbnum; j++) {
1318 server.db[j].dict = dictCreate(&hashDictType,NULL);
1319 server.db[j].expires = dictCreate(&setDictType,NULL);
1320 server.db[j].blockingkeys = dictCreate(&keylistDictType,NULL);
1321 server.db[j].id = j;
1322 }
1323 server.cronloops = 0;
1324 server.bgsavechildpid = -1;
1325 server.bgrewritechildpid = -1;
1326 server.bgrewritebuf = sdsempty();
1327 server.lastsave = time(NULL);
1328 server.dirty = 0;
1329 server.usedmemory = 0;
1330 server.stat_numcommands = 0;
1331 server.stat_numconnections = 0;
1332 server.stat_starttime = time(NULL);
1333 server.unixtime = time(NULL);
1334 aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
1335
1336 if (server.appendonly) {
1337 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
1338 if (server.appendfd == -1) {
1339 redisLog(REDIS_WARNING, "Can't open the append-only file: %s",
1340 strerror(errno));
1341 exit(1);
1342 }
1343 }
1344
1345 if (server.vm_enabled) vmInit();
1346 }
1347
1348 /* Empty the whole database */
1349 static long long emptyDb() {
1350 int j;
1351 long long removed = 0;
1352
1353 for (j = 0; j < server.dbnum; j++) {
1354 removed += dictSize(server.db[j].dict);
1355 dictEmpty(server.db[j].dict);
1356 dictEmpty(server.db[j].expires);
1357 }
1358 return removed;
1359 }
1360
1361 static int yesnotoi(char *s) {
1362 if (!strcasecmp(s,"yes")) return 1;
1363 else if (!strcasecmp(s,"no")) return 0;
1364 else return -1;
1365 }
1366
1367 /* I agree, this is a very rudimental way to load a configuration...
1368 will improve later if the config gets more complex */
1369 static void loadServerConfig(char *filename) {
1370 FILE *fp;
1371 char buf[REDIS_CONFIGLINE_MAX+1], *err = NULL;
1372 int linenum = 0;
1373 sds line = NULL;
1374
1375 if (filename[0] == '-' && filename[1] == '\0')
1376 fp = stdin;
1377 else {
1378 if ((fp = fopen(filename,"r")) == NULL) {
1379 redisLog(REDIS_WARNING,"Fatal error, can't open config file");
1380 exit(1);
1381 }
1382 }
1383
1384 while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL) {
1385 sds *argv;
1386 int argc, j;
1387
1388 linenum++;
1389 line = sdsnew(buf);
1390 line = sdstrim(line," \t\r\n");
1391
1392 /* Skip comments and blank lines*/
1393 if (line[0] == '#' || line[0] == '\0') {
1394 sdsfree(line);
1395 continue;
1396 }
1397
1398 /* Split into arguments */
1399 argv = sdssplitlen(line,sdslen(line)," ",1,&argc);
1400 sdstolower(argv[0]);
1401
1402 /* Execute config directives */
1403 if (!strcasecmp(argv[0],"timeout") && argc == 2) {
1404 server.maxidletime = atoi(argv[1]);
1405 if (server.maxidletime < 0) {
1406 err = "Invalid timeout value"; goto loaderr;
1407 }
1408 } else if (!strcasecmp(argv[0],"port") && argc == 2) {
1409 server.port = atoi(argv[1]);
1410 if (server.port < 1 || server.port > 65535) {
1411 err = "Invalid port"; goto loaderr;
1412 }
1413 } else if (!strcasecmp(argv[0],"bind") && argc == 2) {
1414 server.bindaddr = zstrdup(argv[1]);
1415 } else if (!strcasecmp(argv[0],"save") && argc == 3) {
1416 int seconds = atoi(argv[1]);
1417 int changes = atoi(argv[2]);
1418 if (seconds < 1 || changes < 0) {
1419 err = "Invalid save parameters"; goto loaderr;
1420 }
1421 appendServerSaveParams(seconds,changes);
1422 } else if (!strcasecmp(argv[0],"dir") && argc == 2) {
1423 if (chdir(argv[1]) == -1) {
1424 redisLog(REDIS_WARNING,"Can't chdir to '%s': %s",
1425 argv[1], strerror(errno));
1426 exit(1);
1427 }
1428 } else if (!strcasecmp(argv[0],"loglevel") && argc == 2) {
1429 if (!strcasecmp(argv[1],"debug")) server.verbosity = REDIS_DEBUG;
1430 else if (!strcasecmp(argv[1],"notice")) server.verbosity = REDIS_NOTICE;
1431 else if (!strcasecmp(argv[1],"warning")) server.verbosity = REDIS_WARNING;
1432 else {
1433 err = "Invalid log level. Must be one of debug, notice, warning";
1434 goto loaderr;
1435 }
1436 } else if (!strcasecmp(argv[0],"logfile") && argc == 2) {
1437 FILE *logfp;
1438
1439 server.logfile = zstrdup(argv[1]);
1440 if (!strcasecmp(server.logfile,"stdout")) {
1441 zfree(server.logfile);
1442 server.logfile = NULL;
1443 }
1444 if (server.logfile) {
1445 /* Test if we are able to open the file. The server will not
1446 * be able to abort just for this problem later... */
1447 logfp = fopen(server.logfile,"a");
1448 if (logfp == NULL) {
1449 err = sdscatprintf(sdsempty(),
1450 "Can't open the log file: %s", strerror(errno));
1451 goto loaderr;
1452 }
1453 fclose(logfp);
1454 }
1455 } else if (!strcasecmp(argv[0],"databases") && argc == 2) {
1456 server.dbnum = atoi(argv[1]);
1457 if (server.dbnum < 1) {
1458 err = "Invalid number of databases"; goto loaderr;
1459 }
1460 } else if (!strcasecmp(argv[0],"maxclients") && argc == 2) {
1461 server.maxclients = atoi(argv[1]);
1462 } else if (!strcasecmp(argv[0],"maxmemory") && argc == 2) {
1463 server.maxmemory = strtoll(argv[1], NULL, 10);
1464 } else if (!strcasecmp(argv[0],"slaveof") && argc == 3) {
1465 server.masterhost = sdsnew(argv[1]);
1466 server.masterport = atoi(argv[2]);
1467 server.replstate = REDIS_REPL_CONNECT;
1468 } else if (!strcasecmp(argv[0],"masterauth") && argc == 2) {
1469 server.masterauth = zstrdup(argv[1]);
1470 } else if (!strcasecmp(argv[0],"glueoutputbuf") && argc == 2) {
1471 if ((server.glueoutputbuf = yesnotoi(argv[1])) == -1) {
1472 err = "argument must be 'yes' or 'no'"; goto loaderr;
1473 }
1474 } else if (!strcasecmp(argv[0],"shareobjects") && argc == 2) {
1475 if ((server.shareobjects = yesnotoi(argv[1])) == -1) {
1476 err = "argument must be 'yes' or 'no'"; goto loaderr;
1477 }
1478 } else if (!strcasecmp(argv[0],"rdbcompression") && argc == 2) {
1479 if ((server.rdbcompression = yesnotoi(argv[1])) == -1) {
1480 err = "argument must be 'yes' or 'no'"; goto loaderr;
1481 }
1482 } else if (!strcasecmp(argv[0],"shareobjectspoolsize") && argc == 2) {
1483 server.sharingpoolsize = atoi(argv[1]);
1484 if (server.sharingpoolsize < 1) {
1485 err = "invalid object sharing pool size"; goto loaderr;
1486 }
1487 } else if (!strcasecmp(argv[0],"daemonize") && argc == 2) {
1488 if ((server.daemonize = yesnotoi(argv[1])) == -1) {
1489 err = "argument must be 'yes' or 'no'"; goto loaderr;
1490 }
1491 } else if (!strcasecmp(argv[0],"appendonly") && argc == 2) {
1492 if ((server.appendonly = yesnotoi(argv[1])) == -1) {
1493 err = "argument must be 'yes' or 'no'"; goto loaderr;
1494 }
1495 } else if (!strcasecmp(argv[0],"appendfsync") && argc == 2) {
1496 if (!strcasecmp(argv[1],"no")) {
1497 server.appendfsync = APPENDFSYNC_NO;
1498 } else if (!strcasecmp(argv[1],"always")) {
1499 server.appendfsync = APPENDFSYNC_ALWAYS;
1500 } else if (!strcasecmp(argv[1],"everysec")) {
1501 server.appendfsync = APPENDFSYNC_EVERYSEC;
1502 } else {
1503 err = "argument must be 'no', 'always' or 'everysec'";
1504 goto loaderr;
1505 }
1506 } else if (!strcasecmp(argv[0],"requirepass") && argc == 2) {
1507 server.requirepass = zstrdup(argv[1]);
1508 } else if (!strcasecmp(argv[0],"pidfile") && argc == 2) {
1509 server.pidfile = zstrdup(argv[1]);
1510 } else if (!strcasecmp(argv[0],"dbfilename") && argc == 2) {
1511 server.dbfilename = zstrdup(argv[1]);
1512 } else if (!strcasecmp(argv[0],"vm-enabled") && argc == 2) {
1513 if ((server.vm_enabled = yesnotoi(argv[1])) == -1) {
1514 err = "argument must be 'yes' or 'no'"; goto loaderr;
1515 }
1516 } else if (!strcasecmp(argv[0],"vm-max-memory") && argc == 2) {
1517 server.vm_max_memory = strtoll(argv[1], NULL, 10);
1518 } else if (!strcasecmp(argv[0],"vm-page-size") && argc == 2) {
1519 server.vm_page_size = strtoll(argv[1], NULL, 10);
1520 } else if (!strcasecmp(argv[0],"vm-pages") && argc == 2) {
1521 server.vm_pages = strtoll(argv[1], NULL, 10);
1522 } else {
1523 err = "Bad directive or wrong number of arguments"; goto loaderr;
1524 }
1525 for (j = 0; j < argc; j++)
1526 sdsfree(argv[j]);
1527 zfree(argv);
1528 sdsfree(line);
1529 }
1530 if (fp != stdin) fclose(fp);
1531 return;
1532
1533 loaderr:
1534 fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n");
1535 fprintf(stderr, "Reading the configuration file, at line %d\n", linenum);
1536 fprintf(stderr, ">>> '%s'\n", line);
1537 fprintf(stderr, "%s\n", err);
1538 exit(1);
1539 }
1540
1541 static void freeClientArgv(redisClient *c) {
1542 int j;
1543
1544 for (j = 0; j < c->argc; j++)
1545 decrRefCount(c->argv[j]);
1546 for (j = 0; j < c->mbargc; j++)
1547 decrRefCount(c->mbargv[j]);
1548 c->argc = 0;
1549 c->mbargc = 0;
1550 }
1551
1552 static void freeClient(redisClient *c) {
1553 listNode *ln;
1554
1555 /* Note that if the client we are freeing is blocked into a blocking
1556 * call, we have to set querybuf to NULL *before* to call unblockClient()
1557 * to avoid processInputBuffer() will get called. Also it is important
1558 * to remove the file events after this, because this call adds
1559 * the READABLE event. */
1560 sdsfree(c->querybuf);
1561 c->querybuf = NULL;
1562 if (c->flags & REDIS_BLOCKED)
1563 unblockClient(c);
1564
1565 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
1566 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
1567 listRelease(c->reply);
1568 freeClientArgv(c);
1569 close(c->fd);
1570 ln = listSearchKey(server.clients,c);
1571 redisAssert(ln != NULL);
1572 listDelNode(server.clients,ln);
1573 if (c->flags & REDIS_SLAVE) {
1574 if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1)
1575 close(c->repldbfd);
1576 list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves;
1577 ln = listSearchKey(l,c);
1578 redisAssert(ln != NULL);
1579 listDelNode(l,ln);
1580 }
1581 if (c->flags & REDIS_MASTER) {
1582 server.master = NULL;
1583 server.replstate = REDIS_REPL_CONNECT;
1584 }
1585 zfree(c->argv);
1586 zfree(c->mbargv);
1587 freeClientMultiState(c);
1588 zfree(c);
1589 }
1590
1591 #define GLUEREPLY_UP_TO (1024)
1592 static void glueReplyBuffersIfNeeded(redisClient *c) {
1593 int copylen = 0;
1594 char buf[GLUEREPLY_UP_TO];
1595 listNode *ln;
1596 robj *o;
1597
1598 listRewind(c->reply);
1599 while((ln = listYield(c->reply))) {
1600 int objlen;
1601
1602 o = ln->value;
1603 objlen = sdslen(o->ptr);
1604 if (copylen + objlen <= GLUEREPLY_UP_TO) {
1605 memcpy(buf+copylen,o->ptr,objlen);
1606 copylen += objlen;
1607 listDelNode(c->reply,ln);
1608 } else {
1609 if (copylen == 0) return;
1610 break;
1611 }
1612 }
1613 /* Now the output buffer is empty, add the new single element */
1614 o = createObject(REDIS_STRING,sdsnewlen(buf,copylen));
1615 listAddNodeHead(c->reply,o);
1616 }
1617
1618 static void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
1619 redisClient *c = privdata;
1620 int nwritten = 0, totwritten = 0, objlen;
1621 robj *o;
1622 REDIS_NOTUSED(el);
1623 REDIS_NOTUSED(mask);
1624
1625 /* Use writev() if we have enough buffers to send */
1626 if (!server.glueoutputbuf &&
1627 listLength(c->reply) > REDIS_WRITEV_THRESHOLD &&
1628 !(c->flags & REDIS_MASTER))
1629 {
1630 sendReplyToClientWritev(el, fd, privdata, mask);
1631 return;
1632 }
1633
1634 while(listLength(c->reply)) {
1635 if (server.glueoutputbuf && listLength(c->reply) > 1)
1636 glueReplyBuffersIfNeeded(c);
1637
1638 o = listNodeValue(listFirst(c->reply));
1639 objlen = sdslen(o->ptr);
1640
1641 if (objlen == 0) {
1642 listDelNode(c->reply,listFirst(c->reply));
1643 continue;
1644 }
1645
1646 if (c->flags & REDIS_MASTER) {
1647 /* Don't reply to a master */
1648 nwritten = objlen - c->sentlen;
1649 } else {
1650 nwritten = write(fd, ((char*)o->ptr)+c->sentlen, objlen - c->sentlen);
1651 if (nwritten <= 0) break;
1652 }
1653 c->sentlen += nwritten;
1654 totwritten += nwritten;
1655 /* If we fully sent the object on head go to the next one */
1656 if (c->sentlen == objlen) {
1657 listDelNode(c->reply,listFirst(c->reply));
1658 c->sentlen = 0;
1659 }
1660 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
1661 * bytes, in a single threaded server it's a good idea to serve
1662 * other clients as well, even if a very large request comes from
1663 * super fast link that is always able to accept data (in real world
1664 * scenario think about 'KEYS *' against the loopback interfae) */
1665 if (totwritten > REDIS_MAX_WRITE_PER_EVENT) break;
1666 }
1667 if (nwritten == -1) {
1668 if (errno == EAGAIN) {
1669 nwritten = 0;
1670 } else {
1671 redisLog(REDIS_DEBUG,
1672 "Error writing to client: %s", strerror(errno));
1673 freeClient(c);
1674 return;
1675 }
1676 }
1677 if (totwritten > 0) c->lastinteraction = time(NULL);
1678 if (listLength(c->reply) == 0) {
1679 c->sentlen = 0;
1680 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
1681 }
1682 }
1683
1684 static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask)
1685 {
1686 redisClient *c = privdata;
1687 int nwritten = 0, totwritten = 0, objlen, willwrite;
1688 robj *o;
1689 struct iovec iov[REDIS_WRITEV_IOVEC_COUNT];
1690 int offset, ion = 0;
1691 REDIS_NOTUSED(el);
1692 REDIS_NOTUSED(mask);
1693
1694 listNode *node;
1695 while (listLength(c->reply)) {
1696 offset = c->sentlen;
1697 ion = 0;
1698 willwrite = 0;
1699
1700 /* fill-in the iov[] array */
1701 for(node = listFirst(c->reply); node; node = listNextNode(node)) {
1702 o = listNodeValue(node);
1703 objlen = sdslen(o->ptr);
1704
1705 if (totwritten + objlen - offset > REDIS_MAX_WRITE_PER_EVENT)
1706 break;
1707
1708 if(ion == REDIS_WRITEV_IOVEC_COUNT)
1709 break; /* no more iovecs */
1710
1711 iov[ion].iov_base = ((char*)o->ptr) + offset;
1712 iov[ion].iov_len = objlen - offset;
1713 willwrite += objlen - offset;
1714 offset = 0; /* just for the first item */
1715 ion++;
1716 }
1717
1718 if(willwrite == 0)
1719 break;
1720
1721 /* write all collected blocks at once */
1722 if((nwritten = writev(fd, iov, ion)) < 0) {
1723 if (errno != EAGAIN) {
1724 redisLog(REDIS_DEBUG,
1725 "Error writing to client: %s", strerror(errno));
1726 freeClient(c);
1727 return;
1728 }
1729 break;
1730 }
1731
1732 totwritten += nwritten;
1733 offset = c->sentlen;
1734
1735 /* remove written robjs from c->reply */
1736 while (nwritten && listLength(c->reply)) {
1737 o = listNodeValue(listFirst(c->reply));
1738 objlen = sdslen(o->ptr);
1739
1740 if(nwritten >= objlen - offset) {
1741 listDelNode(c->reply, listFirst(c->reply));
1742 nwritten -= objlen - offset;
1743 c->sentlen = 0;
1744 } else {
1745 /* partial write */
1746 c->sentlen += nwritten;
1747 break;
1748 }
1749 offset = 0;
1750 }
1751 }
1752
1753 if (totwritten > 0)
1754 c->lastinteraction = time(NULL);
1755
1756 if (listLength(c->reply) == 0) {
1757 c->sentlen = 0;
1758 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
1759 }
1760 }
1761
1762 static struct redisCommand *lookupCommand(char *name) {
1763 int j = 0;
1764 while(cmdTable[j].name != NULL) {
1765 if (!strcasecmp(name,cmdTable[j].name)) return &cmdTable[j];
1766 j++;
1767 }
1768 return NULL;
1769 }
1770
1771 /* resetClient prepare the client to process the next command */
1772 static void resetClient(redisClient *c) {
1773 freeClientArgv(c);
1774 c->bulklen = -1;
1775 c->multibulk = 0;
1776 }
1777
1778 /* Call() is the core of Redis execution of a command */
1779 static void call(redisClient *c, struct redisCommand *cmd) {
1780 long long dirty;
1781
1782 dirty = server.dirty;
1783 cmd->proc(c);
1784 if (server.appendonly && server.dirty-dirty)
1785 feedAppendOnlyFile(cmd,c->db->id,c->argv,c->argc);
1786 if (server.dirty-dirty && listLength(server.slaves))
1787 replicationFeedSlaves(server.slaves,cmd,c->db->id,c->argv,c->argc);
1788 if (listLength(server.monitors))
1789 replicationFeedSlaves(server.monitors,cmd,c->db->id,c->argv,c->argc);
1790 server.stat_numcommands++;
1791 }
1792
1793 /* If this function gets called we already read a whole
1794 * command, argments are in the client argv/argc fields.
1795 * processCommand() execute the command or prepare the
1796 * server for a bulk read from the client.
1797 *
1798 * If 1 is returned the client is still alive and valid and
1799 * and other operations can be performed by the caller. Otherwise
1800 * if 0 is returned the client was destroied (i.e. after QUIT). */
1801 static int processCommand(redisClient *c) {
1802 struct redisCommand *cmd;
1803
1804 /* Free some memory if needed (maxmemory setting) */
1805 if (server.maxmemory) freeMemoryIfNeeded();
1806
1807 /* Handle the multi bulk command type. This is an alternative protocol
1808 * supported by Redis in order to receive commands that are composed of
1809 * multiple binary-safe "bulk" arguments. The latency of processing is
1810 * a bit higher but this allows things like multi-sets, so if this
1811 * protocol is used only for MSET and similar commands this is a big win. */
1812 if (c->multibulk == 0 && c->argc == 1 && ((char*)(c->argv[0]->ptr))[0] == '*') {
1813 c->multibulk = atoi(((char*)c->argv[0]->ptr)+1);
1814 if (c->multibulk <= 0) {
1815 resetClient(c);
1816 return 1;
1817 } else {
1818 decrRefCount(c->argv[c->argc-1]);
1819 c->argc--;
1820 return 1;
1821 }
1822 } else if (c->multibulk) {
1823 if (c->bulklen == -1) {
1824 if (((char*)c->argv[0]->ptr)[0] != '$') {
1825 addReplySds(c,sdsnew("-ERR multi bulk protocol error\r\n"));
1826 resetClient(c);
1827 return 1;
1828 } else {
1829 int bulklen = atoi(((char*)c->argv[0]->ptr)+1);
1830 decrRefCount(c->argv[0]);
1831 if (bulklen < 0 || bulklen > 1024*1024*1024) {
1832 c->argc--;
1833 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
1834 resetClient(c);
1835 return 1;
1836 }
1837 c->argc--;
1838 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
1839 return 1;
1840 }
1841 } else {
1842 c->mbargv = zrealloc(c->mbargv,(sizeof(robj*))*(c->mbargc+1));
1843 c->mbargv[c->mbargc] = c->argv[0];
1844 c->mbargc++;
1845 c->argc--;
1846 c->multibulk--;
1847 if (c->multibulk == 0) {
1848 robj **auxargv;
1849 int auxargc;
1850
1851 /* Here we need to swap the multi-bulk argc/argv with the
1852 * normal argc/argv of the client structure. */
1853 auxargv = c->argv;
1854 c->argv = c->mbargv;
1855 c->mbargv = auxargv;
1856
1857 auxargc = c->argc;
1858 c->argc = c->mbargc;
1859 c->mbargc = auxargc;
1860
1861 /* We need to set bulklen to something different than -1
1862 * in order for the code below to process the command without
1863 * to try to read the last argument of a bulk command as
1864 * a special argument. */
1865 c->bulklen = 0;
1866 /* continue below and process the command */
1867 } else {
1868 c->bulklen = -1;
1869 return 1;
1870 }
1871 }
1872 }
1873 /* -- end of multi bulk commands processing -- */
1874
1875 /* The QUIT command is handled as a special case. Normal command
1876 * procs are unable to close the client connection safely */
1877 if (!strcasecmp(c->argv[0]->ptr,"quit")) {
1878 freeClient(c);
1879 return 0;
1880 }
1881 cmd = lookupCommand(c->argv[0]->ptr);
1882 if (!cmd) {
1883 addReplySds(c,
1884 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
1885 (char*)c->argv[0]->ptr));
1886 resetClient(c);
1887 return 1;
1888 } else if ((cmd->arity > 0 && cmd->arity != c->argc) ||
1889 (c->argc < -cmd->arity)) {
1890 addReplySds(c,
1891 sdscatprintf(sdsempty(),
1892 "-ERR wrong number of arguments for '%s' command\r\n",
1893 cmd->name));
1894 resetClient(c);
1895 return 1;
1896 } else if (server.maxmemory && cmd->flags & REDIS_CMD_DENYOOM && zmalloc_used_memory() > server.maxmemory) {
1897 addReplySds(c,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
1898 resetClient(c);
1899 return 1;
1900 } else if (cmd->flags & REDIS_CMD_BULK && c->bulklen == -1) {
1901 int bulklen = atoi(c->argv[c->argc-1]->ptr);
1902
1903 decrRefCount(c->argv[c->argc-1]);
1904 if (bulklen < 0 || bulklen > 1024*1024*1024) {
1905 c->argc--;
1906 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
1907 resetClient(c);
1908 return 1;
1909 }
1910 c->argc--;
1911 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
1912 /* It is possible that the bulk read is already in the
1913 * buffer. Check this condition and handle it accordingly.
1914 * This is just a fast path, alternative to call processInputBuffer().
1915 * It's a good idea since the code is small and this condition
1916 * happens most of the times. */
1917 if ((signed)sdslen(c->querybuf) >= c->bulklen) {
1918 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
1919 c->argc++;
1920 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
1921 } else {
1922 return 1;
1923 }
1924 }
1925 /* Let's try to share objects on the command arguments vector */
1926 if (server.shareobjects) {
1927 int j;
1928 for(j = 1; j < c->argc; j++)
1929 c->argv[j] = tryObjectSharing(c->argv[j]);
1930 }
1931 /* Let's try to encode the bulk object to save space. */
1932 if (cmd->flags & REDIS_CMD_BULK)
1933 tryObjectEncoding(c->argv[c->argc-1]);
1934
1935 /* Check if the user is authenticated */
1936 if (server.requirepass && !c->authenticated && cmd->proc != authCommand) {
1937 addReplySds(c,sdsnew("-ERR operation not permitted\r\n"));
1938 resetClient(c);
1939 return 1;
1940 }
1941
1942 /* Exec the command */
1943 if (c->flags & REDIS_MULTI && cmd->proc != execCommand) {
1944 queueMultiCommand(c,cmd);
1945 addReply(c,shared.queued);
1946 } else {
1947 call(c,cmd);
1948 }
1949
1950 /* Prepare the client for the next command */
1951 if (c->flags & REDIS_CLOSE) {
1952 freeClient(c);
1953 return 0;
1954 }
1955 resetClient(c);
1956 return 1;
1957 }
1958
1959 static void replicationFeedSlaves(list *slaves, struct redisCommand *cmd, int dictid, robj **argv, int argc) {
1960 listNode *ln;
1961 int outc = 0, j;
1962 robj **outv;
1963 /* (args*2)+1 is enough room for args, spaces, newlines */
1964 robj *static_outv[REDIS_STATIC_ARGS*2+1];
1965
1966 if (argc <= REDIS_STATIC_ARGS) {
1967 outv = static_outv;
1968 } else {
1969 outv = zmalloc(sizeof(robj*)*(argc*2+1));
1970 }
1971
1972 for (j = 0; j < argc; j++) {
1973 if (j != 0) outv[outc++] = shared.space;
1974 if ((cmd->flags & REDIS_CMD_BULK) && j == argc-1) {
1975 robj *lenobj;
1976
1977 lenobj = createObject(REDIS_STRING,
1978 sdscatprintf(sdsempty(),"%lu\r\n",
1979 (unsigned long) stringObjectLen(argv[j])));
1980 lenobj->refcount = 0;
1981 outv[outc++] = lenobj;
1982 }
1983 outv[outc++] = argv[j];
1984 }
1985 outv[outc++] = shared.crlf;
1986
1987 /* Increment all the refcounts at start and decrement at end in order to
1988 * be sure to free objects if there is no slave in a replication state
1989 * able to be feed with commands */
1990 for (j = 0; j < outc; j++) incrRefCount(outv[j]);
1991 listRewind(slaves);
1992 while((ln = listYield(slaves))) {
1993 redisClient *slave = ln->value;
1994
1995 /* Don't feed slaves that are still waiting for BGSAVE to start */
1996 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) continue;
1997
1998 /* Feed all the other slaves, MONITORs and so on */
1999 if (slave->slaveseldb != dictid) {
2000 robj *selectcmd;
2001
2002 switch(dictid) {
2003 case 0: selectcmd = shared.select0; break;
2004 case 1: selectcmd = shared.select1; break;
2005 case 2: selectcmd = shared.select2; break;
2006 case 3: selectcmd = shared.select3; break;
2007 case 4: selectcmd = shared.select4; break;
2008 case 5: selectcmd = shared.select5; break;
2009 case 6: selectcmd = shared.select6; break;
2010 case 7: selectcmd = shared.select7; break;
2011 case 8: selectcmd = shared.select8; break;
2012 case 9: selectcmd = shared.select9; break;
2013 default:
2014 selectcmd = createObject(REDIS_STRING,
2015 sdscatprintf(sdsempty(),"select %d\r\n",dictid));
2016 selectcmd->refcount = 0;
2017 break;
2018 }
2019 addReply(slave,selectcmd);
2020 slave->slaveseldb = dictid;
2021 }
2022 for (j = 0; j < outc; j++) addReply(slave,outv[j]);
2023 }
2024 for (j = 0; j < outc; j++) decrRefCount(outv[j]);
2025 if (outv != static_outv) zfree(outv);
2026 }
2027
2028 static void processInputBuffer(redisClient *c) {
2029 again:
2030 /* Before to process the input buffer, make sure the client is not
2031 * waitig for a blocking operation such as BLPOP. Note that the first
2032 * iteration the client is never blocked, otherwise the processInputBuffer
2033 * would not be called at all, but after the execution of the first commands
2034 * in the input buffer the client may be blocked, and the "goto again"
2035 * will try to reiterate. The following line will make it return asap. */
2036 if (c->flags & REDIS_BLOCKED) return;
2037 if (c->bulklen == -1) {
2038 /* Read the first line of the query */
2039 char *p = strchr(c->querybuf,'\n');
2040 size_t querylen;
2041
2042 if (p) {
2043 sds query, *argv;
2044 int argc, j;
2045
2046 query = c->querybuf;
2047 c->querybuf = sdsempty();
2048 querylen = 1+(p-(query));
2049 if (sdslen(query) > querylen) {
2050 /* leave data after the first line of the query in the buffer */
2051 c->querybuf = sdscatlen(c->querybuf,query+querylen,sdslen(query)-querylen);
2052 }
2053 *p = '\0'; /* remove "\n" */
2054 if (*(p-1) == '\r') *(p-1) = '\0'; /* and "\r" if any */
2055 sdsupdatelen(query);
2056
2057 /* Now we can split the query in arguments */
2058 argv = sdssplitlen(query,sdslen(query)," ",1,&argc);
2059 sdsfree(query);
2060
2061 if (c->argv) zfree(c->argv);
2062 c->argv = zmalloc(sizeof(robj*)*argc);
2063
2064 for (j = 0; j < argc; j++) {
2065 if (sdslen(argv[j])) {
2066 c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);
2067 c->argc++;
2068 } else {
2069 sdsfree(argv[j]);
2070 }
2071 }
2072 zfree(argv);
2073 if (c->argc) {
2074 /* Execute the command. If the client is still valid
2075 * after processCommand() return and there is something
2076 * on the query buffer try to process the next command. */
2077 if (processCommand(c) && sdslen(c->querybuf)) goto again;
2078 } else {
2079 /* Nothing to process, argc == 0. Just process the query
2080 * buffer if it's not empty or return to the caller */
2081 if (sdslen(c->querybuf)) goto again;
2082 }
2083 return;
2084 } else if (sdslen(c->querybuf) >= REDIS_REQUEST_MAX_SIZE) {
2085 redisLog(REDIS_DEBUG, "Client protocol error");
2086 freeClient(c);
2087 return;
2088 }
2089 } else {
2090 /* Bulk read handling. Note that if we are at this point
2091 the client already sent a command terminated with a newline,
2092 we are reading the bulk data that is actually the last
2093 argument of the command. */
2094 int qbl = sdslen(c->querybuf);
2095
2096 if (c->bulklen <= qbl) {
2097 /* Copy everything but the final CRLF as final argument */
2098 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
2099 c->argc++;
2100 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
2101 /* Process the command. If the client is still valid after
2102 * the processing and there is more data in the buffer
2103 * try to parse it. */
2104 if (processCommand(c) && sdslen(c->querybuf)) goto again;
2105 return;
2106 }
2107 }
2108 }
2109
2110 static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
2111 redisClient *c = (redisClient*) privdata;
2112 char buf[REDIS_IOBUF_LEN];
2113 int nread;
2114 REDIS_NOTUSED(el);
2115 REDIS_NOTUSED(mask);
2116
2117 nread = read(fd, buf, REDIS_IOBUF_LEN);
2118 if (nread == -1) {
2119 if (errno == EAGAIN) {
2120 nread = 0;
2121 } else {
2122 redisLog(REDIS_DEBUG, "Reading from client: %s",strerror(errno));
2123 freeClient(c);
2124 return;
2125 }
2126 } else if (nread == 0) {
2127 redisLog(REDIS_DEBUG, "Client closed connection");
2128 freeClient(c);
2129 return;
2130 }
2131 if (nread) {
2132 c->querybuf = sdscatlen(c->querybuf, buf, nread);
2133 c->lastinteraction = time(NULL);
2134 } else {
2135 return;
2136 }
2137 processInputBuffer(c);
2138 }
2139
2140 static int selectDb(redisClient *c, int id) {
2141 if (id < 0 || id >= server.dbnum)
2142 return REDIS_ERR;
2143 c->db = &server.db[id];
2144 return REDIS_OK;
2145 }
2146
2147 static void *dupClientReplyValue(void *o) {
2148 incrRefCount((robj*)o);
2149 return 0;
2150 }
2151
2152 static redisClient *createClient(int fd) {
2153 redisClient *c = zmalloc(sizeof(*c));
2154
2155 anetNonBlock(NULL,fd);
2156 anetTcpNoDelay(NULL,fd);
2157 if (!c) return NULL;
2158 selectDb(c,0);
2159 c->fd = fd;
2160 c->querybuf = sdsempty();
2161 c->argc = 0;
2162 c->argv = NULL;
2163 c->bulklen = -1;
2164 c->multibulk = 0;
2165 c->mbargc = 0;
2166 c->mbargv = NULL;
2167 c->sentlen = 0;
2168 c->flags = 0;
2169 c->lastinteraction = time(NULL);
2170 c->authenticated = 0;
2171 c->replstate = REDIS_REPL_NONE;
2172 c->reply = listCreate();
2173 c->blockingkeys = NULL;
2174 c->blockingkeysnum = 0;
2175 listSetFreeMethod(c->reply,decrRefCount);
2176 listSetDupMethod(c->reply,dupClientReplyValue);
2177 if (aeCreateFileEvent(server.el, c->fd, AE_READABLE,
2178 readQueryFromClient, c) == AE_ERR) {
2179 freeClient(c);
2180 return NULL;
2181 }
2182 listAddNodeTail(server.clients,c);
2183 initClientMultiState(c);
2184 return c;
2185 }
2186
2187 static void addReply(redisClient *c, robj *obj) {
2188 if (listLength(c->reply) == 0 &&
2189 (c->replstate == REDIS_REPL_NONE ||
2190 c->replstate == REDIS_REPL_ONLINE) &&
2191 aeCreateFileEvent(server.el, c->fd, AE_WRITABLE,
2192 sendReplyToClient, c) == AE_ERR) return;
2193 listAddNodeTail(c->reply,getDecodedObject(obj));
2194 }
2195
2196 static void addReplySds(redisClient *c, sds s) {
2197 robj *o = createObject(REDIS_STRING,s);
2198 addReply(c,o);
2199 decrRefCount(o);
2200 }
2201
2202 static void addReplyDouble(redisClient *c, double d) {
2203 char buf[128];
2204
2205 snprintf(buf,sizeof(buf),"%.17g",d);
2206 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2207 (unsigned long) strlen(buf),buf));
2208 }
2209
2210 static void addReplyBulkLen(redisClient *c, robj *obj) {
2211 size_t len;
2212
2213 if (obj->encoding == REDIS_ENCODING_RAW) {
2214 len = sdslen(obj->ptr);
2215 } else {
2216 long n = (long)obj->ptr;
2217
2218 /* Compute how many bytes will take this integer as a radix 10 string */
2219 len = 1;
2220 if (n < 0) {
2221 len++;
2222 n = -n;
2223 }
2224 while((n = n/10) != 0) {
2225 len++;
2226 }
2227 }
2228 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",(unsigned long)len));
2229 }
2230
2231 static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
2232 int cport, cfd;
2233 char cip[128];
2234 redisClient *c;
2235 REDIS_NOTUSED(el);
2236 REDIS_NOTUSED(mask);
2237 REDIS_NOTUSED(privdata);
2238
2239 cfd = anetAccept(server.neterr, fd, cip, &cport);
2240 if (cfd == AE_ERR) {
2241 redisLog(REDIS_DEBUG,"Accepting client connection: %s", server.neterr);
2242 return;
2243 }
2244 redisLog(REDIS_DEBUG,"Accepted %s:%d", cip, cport);
2245 if ((c = createClient(cfd)) == NULL) {
2246 redisLog(REDIS_WARNING,"Error allocating resoures for the client");
2247 close(cfd); /* May be already closed, just ingore errors */
2248 return;
2249 }
2250 /* If maxclient directive is set and this is one client more... close the
2251 * connection. Note that we create the client instead to check before
2252 * for this condition, since now the socket is already set in nonblocking
2253 * mode and we can send an error for free using the Kernel I/O */
2254 if (server.maxclients && listLength(server.clients) > server.maxclients) {
2255 char *err = "-ERR max number of clients reached\r\n";
2256
2257 /* That's a best effort error message, don't check write errors */
2258 if (write(c->fd,err,strlen(err)) == -1) {
2259 /* Nothing to do, Just to avoid the warning... */
2260 }
2261 freeClient(c);
2262 return;
2263 }
2264 server.stat_numconnections++;
2265 }
2266
2267 /* ======================= Redis objects implementation ===================== */
2268
2269 static robj *createObject(int type, void *ptr) {
2270 robj *o;
2271
2272 if (listLength(server.objfreelist)) {
2273 listNode *head = listFirst(server.objfreelist);
2274 o = listNodeValue(head);
2275 listDelNode(server.objfreelist,head);
2276 } else {
2277 if (server.vm_enabled) {
2278 o = zmalloc(sizeof(*o));
2279 } else {
2280 o = zmalloc(sizeof(*o)-sizeof(struct redisObjectVM));
2281 }
2282 }
2283 o->type = type;
2284 o->encoding = REDIS_ENCODING_RAW;
2285 o->ptr = ptr;
2286 o->refcount = 1;
2287 if (server.vm_enabled) {
2288 o->vm.atime = server.unixtime;
2289 o->storage = REDIS_VM_MEMORY;
2290 }
2291 return o;
2292 }
2293
2294 static robj *createStringObject(char *ptr, size_t len) {
2295 return createObject(REDIS_STRING,sdsnewlen(ptr,len));
2296 }
2297
2298 static robj *dupStringObject(robj *o) {
2299 return createStringObject(o->ptr,sdslen(o->ptr));
2300 }
2301
2302 static robj *createListObject(void) {
2303 list *l = listCreate();
2304
2305 listSetFreeMethod(l,decrRefCount);
2306 return createObject(REDIS_LIST,l);
2307 }
2308
2309 static robj *createSetObject(void) {
2310 dict *d = dictCreate(&setDictType,NULL);
2311 return createObject(REDIS_SET,d);
2312 }
2313
2314 static robj *createZsetObject(void) {
2315 zset *zs = zmalloc(sizeof(*zs));
2316
2317 zs->dict = dictCreate(&zsetDictType,NULL);
2318 zs->zsl = zslCreate();
2319 return createObject(REDIS_ZSET,zs);
2320 }
2321
2322 static void freeStringObject(robj *o) {
2323 if (o->encoding == REDIS_ENCODING_RAW) {
2324 sdsfree(o->ptr);
2325 }
2326 }
2327
2328 static void freeListObject(robj *o) {
2329 listRelease((list*) o->ptr);
2330 }
2331
2332 static void freeSetObject(robj *o) {
2333 dictRelease((dict*) o->ptr);
2334 }
2335
2336 static void freeZsetObject(robj *o) {
2337 zset *zs = o->ptr;
2338
2339 dictRelease(zs->dict);
2340 zslFree(zs->zsl);
2341 zfree(zs);
2342 }
2343
2344 static void freeHashObject(robj *o) {
2345 dictRelease((dict*) o->ptr);
2346 }
2347
2348 static void incrRefCount(robj *o) {
2349 assert(!server.vm_enabled || o->storage == REDIS_VM_MEMORY);
2350 o->refcount++;
2351 }
2352
2353 static void decrRefCount(void *obj) {
2354 robj *o = obj;
2355
2356 /* REDIS_VM_SWAPPED */
2357 if (server.vm_enabled && o->storage == REDIS_VM_SWAPPED) {
2358 assert(o->refcount == 1);
2359 assert(o->type == REDIS_STRING);
2360 freeStringObject(o);
2361 vmMarkPagesFree(o->vm.page,o->vm.usedpages);
2362 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
2363 !listAddNodeHead(server.objfreelist,o))
2364 zfree(o);
2365 return;
2366 }
2367 /* REDIS_VM_MEMORY */
2368 if (--(o->refcount) == 0) {
2369 switch(o->type) {
2370 case REDIS_STRING: freeStringObject(o); break;
2371 case REDIS_LIST: freeListObject(o); break;
2372 case REDIS_SET: freeSetObject(o); break;
2373 case REDIS_ZSET: freeZsetObject(o); break;
2374 case REDIS_HASH: freeHashObject(o); break;
2375 default: redisAssert(0 != 0); break;
2376 }
2377 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
2378 !listAddNodeHead(server.objfreelist,o))
2379 zfree(o);
2380 }
2381 }
2382
2383 static robj *lookupKey(redisDb *db, robj *key) {
2384 dictEntry *de = dictFind(db->dict,key);
2385 if (de) {
2386 robj *key = dictGetEntryKey(de);
2387 robj *val = dictGetEntryVal(de);
2388
2389 if (server.vm_enabled) {
2390 if (key->storage == REDIS_VM_MEMORY) {
2391 /* Update the access time of the key for the aging algorithm. */
2392 key->vm.atime = server.unixtime;
2393 } else {
2394 /* Our value was swapped on disk. Bring it at home. */
2395 assert(val == NULL);
2396 val = vmLoadObject(key);
2397 dictGetEntryVal(de) = val;
2398 }
2399 }
2400 return val;
2401 } else {
2402 return NULL;
2403 }
2404 }
2405
2406 static robj *lookupKeyRead(redisDb *db, robj *key) {
2407 expireIfNeeded(db,key);
2408 return lookupKey(db,key);
2409 }
2410
2411 static robj *lookupKeyWrite(redisDb *db, robj *key) {
2412 deleteIfVolatile(db,key);
2413 return lookupKey(db,key);
2414 }
2415
2416 static int deleteKey(redisDb *db, robj *key) {
2417 int retval;
2418
2419 /* We need to protect key from destruction: after the first dictDelete()
2420 * it may happen that 'key' is no longer valid if we don't increment
2421 * it's count. This may happen when we get the object reference directly
2422 * from the hash table with dictRandomKey() or dict iterators */
2423 incrRefCount(key);
2424 if (dictSize(db->expires)) dictDelete(db->expires,key);
2425 retval = dictDelete(db->dict,key);
2426 decrRefCount(key);
2427
2428 return retval == DICT_OK;
2429 }
2430
2431 /* Try to share an object against the shared objects pool */
2432 static robj *tryObjectSharing(robj *o) {
2433 struct dictEntry *de;
2434 unsigned long c;
2435
2436 if (o == NULL || server.shareobjects == 0) return o;
2437
2438 redisAssert(o->type == REDIS_STRING);
2439 de = dictFind(server.sharingpool,o);
2440 if (de) {
2441 robj *shared = dictGetEntryKey(de);
2442
2443 c = ((unsigned long) dictGetEntryVal(de))+1;
2444 dictGetEntryVal(de) = (void*) c;
2445 incrRefCount(shared);
2446 decrRefCount(o);
2447 return shared;
2448 } else {
2449 /* Here we are using a stream algorihtm: Every time an object is
2450 * shared we increment its count, everytime there is a miss we
2451 * recrement the counter of a random object. If this object reaches
2452 * zero we remove the object and put the current object instead. */
2453 if (dictSize(server.sharingpool) >=
2454 server.sharingpoolsize) {
2455 de = dictGetRandomKey(server.sharingpool);
2456 redisAssert(de != NULL);
2457 c = ((unsigned long) dictGetEntryVal(de))-1;
2458 dictGetEntryVal(de) = (void*) c;
2459 if (c == 0) {
2460 dictDelete(server.sharingpool,de->key);
2461 }
2462 } else {
2463 c = 0; /* If the pool is empty we want to add this object */
2464 }
2465 if (c == 0) {
2466 int retval;
2467
2468 retval = dictAdd(server.sharingpool,o,(void*)1);
2469 redisAssert(retval == DICT_OK);
2470 incrRefCount(o);
2471 }
2472 return o;
2473 }
2474 }
2475
2476 /* Check if the nul-terminated string 's' can be represented by a long
2477 * (that is, is a number that fits into long without any other space or
2478 * character before or after the digits).
2479 *
2480 * If so, the function returns REDIS_OK and *longval is set to the value
2481 * of the number. Otherwise REDIS_ERR is returned */
2482 static int isStringRepresentableAsLong(sds s, long *longval) {
2483 char buf[32], *endptr;
2484 long value;
2485 int slen;
2486
2487 value = strtol(s, &endptr, 10);
2488 if (endptr[0] != '\0') return REDIS_ERR;
2489 slen = snprintf(buf,32,"%ld",value);
2490
2491 /* If the number converted back into a string is not identical
2492 * then it's not possible to encode the string as integer */
2493 if (sdslen(s) != (unsigned)slen || memcmp(buf,s,slen)) return REDIS_ERR;
2494 if (longval) *longval = value;
2495 return REDIS_OK;
2496 }
2497
2498 /* Try to encode a string object in order to save space */
2499 static int tryObjectEncoding(robj *o) {
2500 long value;
2501 sds s = o->ptr;
2502
2503 if (o->encoding != REDIS_ENCODING_RAW)
2504 return REDIS_ERR; /* Already encoded */
2505
2506 /* It's not save to encode shared objects: shared objects can be shared
2507 * everywhere in the "object space" of Redis. Encoded objects can only
2508 * appear as "values" (and not, for instance, as keys) */
2509 if (o->refcount > 1) return REDIS_ERR;
2510
2511 /* Currently we try to encode only strings */
2512 redisAssert(o->type == REDIS_STRING);
2513
2514 /* Check if we can represent this string as a long integer */
2515 if (isStringRepresentableAsLong(s,&value) == REDIS_ERR) return REDIS_ERR;
2516
2517 /* Ok, this object can be encoded */
2518 o->encoding = REDIS_ENCODING_INT;
2519 sdsfree(o->ptr);
2520 o->ptr = (void*) value;
2521 return REDIS_OK;
2522 }
2523
2524 /* Get a decoded version of an encoded object (returned as a new object).
2525 * If the object is already raw-encoded just increment the ref count. */
2526 static robj *getDecodedObject(robj *o) {
2527 robj *dec;
2528
2529 if (o->encoding == REDIS_ENCODING_RAW) {
2530 incrRefCount(o);
2531 return o;
2532 }
2533 if (o->type == REDIS_STRING && o->encoding == REDIS_ENCODING_INT) {
2534 char buf[32];
2535
2536 snprintf(buf,32,"%ld",(long)o->ptr);
2537 dec = createStringObject(buf,strlen(buf));
2538 return dec;
2539 } else {
2540 redisAssert(1 != 1);
2541 }
2542 }
2543
2544 /* Compare two string objects via strcmp() or alike.
2545 * Note that the objects may be integer-encoded. In such a case we
2546 * use snprintf() to get a string representation of the numbers on the stack
2547 * and compare the strings, it's much faster than calling getDecodedObject().
2548 *
2549 * Important note: if objects are not integer encoded, but binary-safe strings,
2550 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
2551 * binary safe. */
2552 static int compareStringObjects(robj *a, robj *b) {
2553 redisAssert(a->type == REDIS_STRING && b->type == REDIS_STRING);
2554 char bufa[128], bufb[128], *astr, *bstr;
2555 int bothsds = 1;
2556
2557 if (a == b) return 0;
2558 if (a->encoding != REDIS_ENCODING_RAW) {
2559 snprintf(bufa,sizeof(bufa),"%ld",(long) a->ptr);
2560 astr = bufa;
2561 bothsds = 0;
2562 } else {
2563 astr = a->ptr;
2564 }
2565 if (b->encoding != REDIS_ENCODING_RAW) {
2566 snprintf(bufb,sizeof(bufb),"%ld",(long) b->ptr);
2567 bstr = bufb;
2568 bothsds = 0;
2569 } else {
2570 bstr = b->ptr;
2571 }
2572 return bothsds ? sdscmp(astr,bstr) : strcmp(astr,bstr);
2573 }
2574
2575 static size_t stringObjectLen(robj *o) {
2576 redisAssert(o->type == REDIS_STRING);
2577 if (o->encoding == REDIS_ENCODING_RAW) {
2578 return sdslen(o->ptr);
2579 } else {
2580 char buf[32];
2581
2582 return snprintf(buf,32,"%ld",(long)o->ptr);
2583 }
2584 }
2585
2586 /*============================ RDB saving/loading =========================== */
2587
2588 static int rdbSaveType(FILE *fp, unsigned char type) {
2589 if (fwrite(&type,1,1,fp) == 0) return -1;
2590 return 0;
2591 }
2592
2593 static int rdbSaveTime(FILE *fp, time_t t) {
2594 int32_t t32 = (int32_t) t;
2595 if (fwrite(&t32,4,1,fp) == 0) return -1;
2596 return 0;
2597 }
2598
2599 /* check rdbLoadLen() comments for more info */
2600 static int rdbSaveLen(FILE *fp, uint32_t len) {
2601 unsigned char buf[2];
2602
2603 if (len < (1<<6)) {
2604 /* Save a 6 bit len */
2605 buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
2606 if (fwrite(buf,1,1,fp) == 0) return -1;
2607 } else if (len < (1<<14)) {
2608 /* Save a 14 bit len */
2609 buf[0] = ((len>>8)&0xFF)|(REDIS_RDB_14BITLEN<<6);
2610 buf[1] = len&0xFF;
2611 if (fwrite(buf,2,1,fp) == 0) return -1;
2612 } else {
2613 /* Save a 32 bit len */
2614 buf[0] = (REDIS_RDB_32BITLEN<<6);
2615 if (fwrite(buf,1,1,fp) == 0) return -1;
2616 len = htonl(len);
2617 if (fwrite(&len,4,1,fp) == 0) return -1;
2618 }
2619 return 0;
2620 }
2621
2622 /* String objects in the form "2391" "-100" without any space and with a
2623 * range of values that can fit in an 8, 16 or 32 bit signed value can be
2624 * encoded as integers to save space */
2625 static int rdbTryIntegerEncoding(sds s, unsigned char *enc) {
2626 long long value;
2627 char *endptr, buf[32];
2628
2629 /* Check if it's possible to encode this value as a number */
2630 value = strtoll(s, &endptr, 10);
2631 if (endptr[0] != '\0') return 0;
2632 snprintf(buf,32,"%lld",value);
2633
2634 /* If the number converted back into a string is not identical
2635 * then it's not possible to encode the string as integer */
2636 if (strlen(buf) != sdslen(s) || memcmp(buf,s,sdslen(s))) return 0;
2637
2638 /* Finally check if it fits in our ranges */
2639 if (value >= -(1<<7) && value <= (1<<7)-1) {
2640 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT8;
2641 enc[1] = value&0xFF;
2642 return 2;
2643 } else if (value >= -(1<<15) && value <= (1<<15)-1) {
2644 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT16;
2645 enc[1] = value&0xFF;
2646 enc[2] = (value>>8)&0xFF;
2647 return 3;
2648 } else if (value >= -((long long)1<<31) && value <= ((long long)1<<31)-1) {
2649 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT32;
2650 enc[1] = value&0xFF;
2651 enc[2] = (value>>8)&0xFF;
2652 enc[3] = (value>>16)&0xFF;
2653 enc[4] = (value>>24)&0xFF;
2654 return 5;
2655 } else {
2656 return 0;
2657 }
2658 }
2659
2660 static int rdbSaveLzfStringObject(FILE *fp, robj *obj) {
2661 unsigned int comprlen, outlen;
2662 unsigned char byte;
2663 void *out;
2664
2665 /* We require at least four bytes compression for this to be worth it */
2666 outlen = sdslen(obj->ptr)-4;
2667 if (outlen <= 0) return 0;
2668 if ((out = zmalloc(outlen+1)) == NULL) return 0;
2669 comprlen = lzf_compress(obj->ptr, sdslen(obj->ptr), out, outlen);
2670 if (comprlen == 0) {
2671 zfree(out);
2672 return 0;
2673 }
2674 /* Data compressed! Let's save it on disk */
2675 byte = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_LZF;
2676 if (fwrite(&byte,1,1,fp) == 0) goto writeerr;
2677 if (rdbSaveLen(fp,comprlen) == -1) goto writeerr;
2678 if (rdbSaveLen(fp,sdslen(obj->ptr)) == -1) goto writeerr;
2679 if (fwrite(out,comprlen,1,fp) == 0) goto writeerr;
2680 zfree(out);
2681 return comprlen;
2682
2683 writeerr:
2684 zfree(out);
2685 return -1;
2686 }
2687
2688 /* Save a string objet as [len][data] on disk. If the object is a string
2689 * representation of an integer value we try to safe it in a special form */
2690 static int rdbSaveStringObjectRaw(FILE *fp, robj *obj) {
2691 size_t len;
2692 int enclen;
2693
2694 len = sdslen(obj->ptr);
2695
2696 /* Try integer encoding */
2697 if (len <= 11) {
2698 unsigned char buf[5];
2699 if ((enclen = rdbTryIntegerEncoding(obj->ptr,buf)) > 0) {
2700 if (fwrite(buf,enclen,1,fp) == 0) return -1;
2701 return 0;
2702 }
2703 }
2704
2705 /* Try LZF compression - under 20 bytes it's unable to compress even
2706 * aaaaaaaaaaaaaaaaaa so skip it */
2707 if (server.rdbcompression && len > 20) {
2708 int retval;
2709
2710 retval = rdbSaveLzfStringObject(fp,obj);
2711 if (retval == -1) return -1;
2712 if (retval > 0) return 0;
2713 /* retval == 0 means data can't be compressed, save the old way */
2714 }
2715
2716 /* Store verbatim */
2717 if (rdbSaveLen(fp,len) == -1) return -1;
2718 if (len && fwrite(obj->ptr,len,1,fp) == 0) return -1;
2719 return 0;
2720 }
2721
2722 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
2723 static int rdbSaveStringObject(FILE *fp, robj *obj) {
2724 int retval;
2725
2726 obj = getDecodedObject(obj);
2727 retval = rdbSaveStringObjectRaw(fp,obj);
2728 decrRefCount(obj);
2729 return retval;
2730 }
2731
2732 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
2733 * 8 bit integer specifing the length of the representation.
2734 * This 8 bit integer has special values in order to specify the following
2735 * conditions:
2736 * 253: not a number
2737 * 254: + inf
2738 * 255: - inf
2739 */
2740 static int rdbSaveDoubleValue(FILE *fp, double val) {
2741 unsigned char buf[128];
2742 int len;
2743
2744 if (isnan(val)) {
2745 buf[0] = 253;
2746 len = 1;
2747 } else if (!isfinite(val)) {
2748 len = 1;
2749 buf[0] = (val < 0) ? 255 : 254;
2750 } else {
2751 snprintf((char*)buf+1,sizeof(buf)-1,"%.17g",val);
2752 buf[0] = strlen((char*)buf+1);
2753 len = buf[0]+1;
2754 }
2755 if (fwrite(buf,len,1,fp) == 0) return -1;
2756 return 0;
2757 }
2758
2759 /* Save a Redis object. */
2760 static int rdbSaveObject(FILE *fp, robj *o) {
2761 if (o->type == REDIS_STRING) {
2762 /* Save a string value */
2763 if (rdbSaveStringObject(fp,o) == -1) return -1;
2764 } else if (o->type == REDIS_LIST) {
2765 /* Save a list value */
2766 list *list = o->ptr;
2767 listNode *ln;
2768
2769 listRewind(list);
2770 if (rdbSaveLen(fp,listLength(list)) == -1) return -1;
2771 while((ln = listYield(list))) {
2772 robj *eleobj = listNodeValue(ln);
2773
2774 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
2775 }
2776 } else if (o->type == REDIS_SET) {
2777 /* Save a set value */
2778 dict *set = o->ptr;
2779 dictIterator *di = dictGetIterator(set);
2780 dictEntry *de;
2781
2782 if (rdbSaveLen(fp,dictSize(set)) == -1) return -1;
2783 while((de = dictNext(di)) != NULL) {
2784 robj *eleobj = dictGetEntryKey(de);
2785
2786 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
2787 }
2788 dictReleaseIterator(di);
2789 } else if (o->type == REDIS_ZSET) {
2790 /* Save a set value */
2791 zset *zs = o->ptr;
2792 dictIterator *di = dictGetIterator(zs->dict);
2793 dictEntry *de;
2794
2795 if (rdbSaveLen(fp,dictSize(zs->dict)) == -1) return -1;
2796 while((de = dictNext(di)) != NULL) {
2797 robj *eleobj = dictGetEntryKey(de);
2798 double *score = dictGetEntryVal(de);
2799
2800 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
2801 if (rdbSaveDoubleValue(fp,*score) == -1) return -1;
2802 }
2803 dictReleaseIterator(di);
2804 } else {
2805 redisAssert(0 != 0);
2806 }
2807 return 0;
2808 }
2809
2810 /* Return the length the object will have on disk if saved with
2811 * the rdbSaveObject() function. Currently we use a trick to get
2812 * this length with very little changes to the code. In the future
2813 * we could switch to a faster solution. */
2814 static off_t rdbSavedObjectLen(robj *o) {
2815 static FILE *fp = NULL;
2816
2817 if (fp == NULL) fp = fopen("/dev/null","w");
2818 assert(fp != NULL);
2819
2820 rewind(fp);
2821 assert(rdbSaveObject(fp,o) != 1);
2822 return ftello(fp);
2823 }
2824
2825 /* Return the number of pages required to save this object in the swap file */
2826 static off_t rdbSavedObjectPages(robj *o) {
2827 off_t bytes = rdbSavedObjectLen(o);
2828
2829 return (bytes+(server.vm_page_size-1))/server.vm_page_size;
2830 }
2831
2832 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
2833 static int rdbSave(char *filename) {
2834 dictIterator *di = NULL;
2835 dictEntry *de;
2836 FILE *fp;
2837 char tmpfile[256];
2838 int j;
2839 time_t now = time(NULL);
2840
2841 snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
2842 fp = fopen(tmpfile,"w");
2843 if (!fp) {
2844 redisLog(REDIS_WARNING, "Failed saving the DB: %s", strerror(errno));
2845 return REDIS_ERR;
2846 }
2847 if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
2848 for (j = 0; j < server.dbnum; j++) {
2849 redisDb *db = server.db+j;
2850 dict *d = db->dict;
2851 if (dictSize(d) == 0) continue;
2852 di = dictGetIterator(d);
2853 if (!di) {
2854 fclose(fp);
2855 return REDIS_ERR;
2856 }
2857
2858 /* Write the SELECT DB opcode */
2859 if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
2860 if (rdbSaveLen(fp,j) == -1) goto werr;
2861
2862 /* Iterate this DB writing every entry */
2863 while((de = dictNext(di)) != NULL) {
2864 robj *key = dictGetEntryKey(de);
2865 robj *o = dictGetEntryVal(de);
2866 time_t expiretime = getExpire(db,key);
2867
2868 /* Save the expire time */
2869 if (expiretime != -1) {
2870 /* If this key is already expired skip it */
2871 if (expiretime < now) continue;
2872 if (rdbSaveType(fp,REDIS_EXPIRETIME) == -1) goto werr;
2873 if (rdbSaveTime(fp,expiretime) == -1) goto werr;
2874 }
2875 /* Save the key and associated value */
2876 if (rdbSaveType(fp,o->type) == -1) goto werr;
2877 if (rdbSaveStringObject(fp,key) == -1) goto werr;
2878 /* Save the actual value */
2879 if (rdbSaveObject(fp,o) == -1) goto werr;
2880 }
2881 dictReleaseIterator(di);
2882 }
2883 /* EOF opcode */
2884 if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;
2885
2886 /* Make sure data will not remain on the OS's output buffers */
2887 fflush(fp);
2888 fsync(fileno(fp));
2889 fclose(fp);
2890
2891 /* Use RENAME to make sure the DB file is changed atomically only
2892 * if the generate DB file is ok. */
2893 if (rename(tmpfile,filename) == -1) {
2894 redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
2895 unlink(tmpfile);
2896 return REDIS_ERR;
2897 }
2898 redisLog(REDIS_NOTICE,"DB saved on disk");
2899 server.dirty = 0;
2900 server.lastsave = time(NULL);
2901 return REDIS_OK;
2902
2903 werr:
2904 fclose(fp);
2905 unlink(tmpfile);
2906 redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
2907 if (di) dictReleaseIterator(di);
2908 return REDIS_ERR;
2909 }
2910
2911 static int rdbSaveBackground(char *filename) {
2912 pid_t childpid;
2913
2914 if (server.bgsavechildpid != -1) return REDIS_ERR;
2915 if ((childpid = fork()) == 0) {
2916 /* Child */
2917 close(server.fd);
2918 if (rdbSave(filename) == REDIS_OK) {
2919 exit(0);
2920 } else {
2921 exit(1);
2922 }
2923 } else {
2924 /* Parent */
2925 if (childpid == -1) {
2926 redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
2927 strerror(errno));
2928 return REDIS_ERR;
2929 }
2930 redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
2931 server.bgsavechildpid = childpid;
2932 return REDIS_OK;
2933 }
2934 return REDIS_OK; /* unreached */
2935 }
2936
2937 static void rdbRemoveTempFile(pid_t childpid) {
2938 char tmpfile[256];
2939
2940 snprintf(tmpfile,256,"temp-%d.rdb", (int) childpid);
2941 unlink(tmpfile);
2942 }
2943
2944 static int rdbLoadType(FILE *fp) {
2945 unsigned char type;
2946 if (fread(&type,1,1,fp) == 0) return -1;
2947 return type;
2948 }
2949
2950 static time_t rdbLoadTime(FILE *fp) {
2951 int32_t t32;
2952 if (fread(&t32,4,1,fp) == 0) return -1;
2953 return (time_t) t32;
2954 }
2955
2956 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
2957 * of this file for a description of how this are stored on disk.
2958 *
2959 * isencoded is set to 1 if the readed length is not actually a length but
2960 * an "encoding type", check the above comments for more info */
2961 static uint32_t rdbLoadLen(FILE *fp, int *isencoded) {
2962 unsigned char buf[2];
2963 uint32_t len;
2964 int type;
2965
2966 if (isencoded) *isencoded = 0;
2967 if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
2968 type = (buf[0]&0xC0)>>6;
2969 if (type == REDIS_RDB_6BITLEN) {
2970 /* Read a 6 bit len */
2971 return buf[0]&0x3F;
2972 } else if (type == REDIS_RDB_ENCVAL) {
2973 /* Read a 6 bit len encoding type */
2974 if (isencoded) *isencoded = 1;
2975 return buf[0]&0x3F;
2976 } else if (type == REDIS_RDB_14BITLEN) {
2977 /* Read a 14 bit len */
2978 if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
2979 return ((buf[0]&0x3F)<<8)|buf[1];
2980 } else {
2981 /* Read a 32 bit len */
2982 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
2983 return ntohl(len);
2984 }
2985 }
2986
2987 static robj *rdbLoadIntegerObject(FILE *fp, int enctype) {
2988 unsigned char enc[4];
2989 long long val;
2990
2991 if (enctype == REDIS_RDB_ENC_INT8) {
2992 if (fread(enc,1,1,fp) == 0) return NULL;
2993 val = (signed char)enc[0];
2994 } else if (enctype == REDIS_RDB_ENC_INT16) {
2995 uint16_t v;
2996 if (fread(enc,2,1,fp) == 0) return NULL;
2997 v = enc[0]|(enc[1]<<8);
2998 val = (int16_t)v;
2999 } else if (enctype == REDIS_RDB_ENC_INT32) {
3000 uint32_t v;
3001 if (fread(enc,4,1,fp) == 0) return NULL;
3002 v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
3003 val = (int32_t)v;
3004 } else {
3005 val = 0; /* anti-warning */
3006 redisAssert(0!=0);
3007 }
3008 return createObject(REDIS_STRING,sdscatprintf(sdsempty(),"%lld",val));
3009 }
3010
3011 static robj *rdbLoadLzfStringObject(FILE*fp) {
3012 unsigned int len, clen;
3013 unsigned char *c = NULL;
3014 sds val = NULL;
3015
3016 if ((clen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3017 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3018 if ((c = zmalloc(clen)) == NULL) goto err;
3019 if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
3020 if (fread(c,clen,1,fp) == 0) goto err;
3021 if (lzf_decompress(c,clen,val,len) == 0) goto err;
3022 zfree(c);
3023 return createObject(REDIS_STRING,val);
3024 err:
3025 zfree(c);
3026 sdsfree(val);
3027 return NULL;
3028 }
3029
3030 static robj *rdbLoadStringObject(FILE*fp) {
3031 int isencoded;
3032 uint32_t len;
3033 sds val;
3034
3035 len = rdbLoadLen(fp,&isencoded);
3036 if (isencoded) {
3037 switch(len) {
3038 case REDIS_RDB_ENC_INT8:
3039 case REDIS_RDB_ENC_INT16:
3040 case REDIS_RDB_ENC_INT32:
3041 return tryObjectSharing(rdbLoadIntegerObject(fp,len));
3042 case REDIS_RDB_ENC_LZF:
3043 return tryObjectSharing(rdbLoadLzfStringObject(fp));
3044 default:
3045 redisAssert(0!=0);
3046 }
3047 }
3048
3049 if (len == REDIS_RDB_LENERR) return NULL;
3050 val = sdsnewlen(NULL,len);
3051 if (len && fread(val,len,1,fp) == 0) {
3052 sdsfree(val);
3053 return NULL;
3054 }
3055 return tryObjectSharing(createObject(REDIS_STRING,val));
3056 }
3057
3058 /* For information about double serialization check rdbSaveDoubleValue() */
3059 static int rdbLoadDoubleValue(FILE *fp, double *val) {
3060 char buf[128];
3061 unsigned char len;
3062
3063 if (fread(&len,1,1,fp) == 0) return -1;
3064 switch(len) {
3065 case 255: *val = R_NegInf; return 0;
3066 case 254: *val = R_PosInf; return 0;
3067 case 253: *val = R_Nan; return 0;
3068 default:
3069 if (fread(buf,len,1,fp) == 0) return -1;
3070 buf[len] = '\0';
3071 sscanf(buf, "%lg", val);
3072 return 0;
3073 }
3074 }
3075
3076 /* Load a Redis object of the specified type from the specified file.
3077 * On success a newly allocated object is returned, otherwise NULL. */
3078 static robj *rdbLoadObject(int type, FILE *fp) {
3079 robj *o;
3080
3081 if (type == REDIS_STRING) {
3082 /* Read string value */
3083 if ((o = rdbLoadStringObject(fp)) == NULL) return NULL;
3084 tryObjectEncoding(o);
3085 } else if (type == REDIS_LIST || type == REDIS_SET) {
3086 /* Read list/set value */
3087 uint32_t listlen;
3088
3089 if ((listlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3090 o = (type == REDIS_LIST) ? createListObject() : createSetObject();
3091 /* Load every single element of the list/set */
3092 while(listlen--) {
3093 robj *ele;
3094
3095 if ((ele = rdbLoadStringObject(fp)) == NULL) return NULL;
3096 tryObjectEncoding(ele);
3097 if (type == REDIS_LIST) {
3098 listAddNodeTail((list*)o->ptr,ele);
3099 } else {
3100 dictAdd((dict*)o->ptr,ele,NULL);
3101 }
3102 }
3103 } else if (type == REDIS_ZSET) {
3104 /* Read list/set value */
3105 uint32_t zsetlen;
3106 zset *zs;
3107
3108 if ((zsetlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3109 o = createZsetObject();
3110 zs = o->ptr;
3111 /* Load every single element of the list/set */
3112 while(zsetlen--) {
3113 robj *ele;
3114 double *score = zmalloc(sizeof(double));
3115
3116 if ((ele = rdbLoadStringObject(fp)) == NULL) return NULL;
3117 tryObjectEncoding(ele);
3118 if (rdbLoadDoubleValue(fp,score) == -1) return NULL;
3119 dictAdd(zs->dict,ele,score);
3120 zslInsert(zs->zsl,*score,ele);
3121 incrRefCount(ele); /* added to skiplist */
3122 }
3123 } else {
3124 redisAssert(0 != 0);
3125 }
3126 return o;
3127 }
3128
3129 static int rdbLoad(char *filename) {
3130 FILE *fp;
3131 robj *keyobj = NULL;
3132 uint32_t dbid;
3133 int type, retval, rdbver;
3134 dict *d = server.db[0].dict;
3135 redisDb *db = server.db+0;
3136 char buf[1024];
3137 time_t expiretime = -1, now = time(NULL);
3138
3139 fp = fopen(filename,"r");
3140 if (!fp) return REDIS_ERR;
3141 if (fread(buf,9,1,fp) == 0) goto eoferr;
3142 buf[9] = '\0';
3143 if (memcmp(buf,"REDIS",5) != 0) {
3144 fclose(fp);
3145 redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
3146 return REDIS_ERR;
3147 }
3148 rdbver = atoi(buf+5);
3149 if (rdbver != 1) {
3150 fclose(fp);
3151 redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
3152 return REDIS_ERR;
3153 }
3154 while(1) {
3155 robj *o;
3156
3157 /* Read type. */
3158 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
3159 if (type == REDIS_EXPIRETIME) {
3160 if ((expiretime = rdbLoadTime(fp)) == -1) goto eoferr;
3161 /* We read the time so we need to read the object type again */
3162 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
3163 }
3164 if (type == REDIS_EOF) break;
3165 /* Handle SELECT DB opcode as a special case */
3166 if (type == REDIS_SELECTDB) {
3167 if ((dbid = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR)
3168 goto eoferr;
3169 if (dbid >= (unsigned)server.dbnum) {
3170 redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
3171 exit(1);
3172 }
3173 db = server.db+dbid;
3174 d = db->dict;
3175 continue;
3176 }
3177 /* Read key */
3178 if ((keyobj = rdbLoadStringObject(fp)) == NULL) goto eoferr;
3179 /* Read value */
3180 if ((o = rdbLoadObject(type,fp)) == NULL) goto eoferr;
3181 /* Add the new object in the hash table */
3182 retval = dictAdd(d,keyobj,o);
3183 if (retval == DICT_ERR) {
3184 redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj->ptr);
3185 exit(1);
3186 }
3187 /* Set the expire time if needed */
3188 if (expiretime != -1) {
3189 setExpire(db,keyobj,expiretime);
3190 /* Delete this key if already expired */
3191 if (expiretime < now) deleteKey(db,keyobj);
3192 expiretime = -1;
3193 }
3194 keyobj = o = NULL;
3195 }
3196 fclose(fp);
3197 return REDIS_OK;
3198
3199 eoferr: /* unexpected end of file is handled here with a fatal exit */
3200 if (keyobj) decrRefCount(keyobj);
3201 redisLog(REDIS_WARNING,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
3202 exit(1);
3203 return REDIS_ERR; /* Just to avoid warning */
3204 }
3205
3206 /*================================== Commands =============================== */
3207
3208 static void authCommand(redisClient *c) {
3209 if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) {
3210 c->authenticated = 1;
3211 addReply(c,shared.ok);
3212 } else {
3213 c->authenticated = 0;
3214 addReplySds(c,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
3215 }
3216 }
3217
3218 static void pingCommand(redisClient *c) {
3219 addReply(c,shared.pong);
3220 }
3221
3222 static void echoCommand(redisClient *c) {
3223 addReplyBulkLen(c,c->argv[1]);
3224 addReply(c,c->argv[1]);
3225 addReply(c,shared.crlf);
3226 }
3227
3228 /*=================================== Strings =============================== */
3229
3230 static void setGenericCommand(redisClient *c, int nx) {
3231 int retval;
3232
3233 if (nx) deleteIfVolatile(c->db,c->argv[1]);
3234 retval = dictAdd(c->db->dict,c->argv[1],c->argv[2]);
3235 if (retval == DICT_ERR) {
3236 if (!nx) {
3237 dictReplace(c->db->dict,c->argv[1],c->argv[2]);
3238 incrRefCount(c->argv[2]);
3239 } else {
3240 addReply(c,shared.czero);
3241 return;
3242 }
3243 } else {
3244 incrRefCount(c->argv[1]);
3245 incrRefCount(c->argv[2]);
3246 }
3247 server.dirty++;
3248 removeExpire(c->db,c->argv[1]);
3249 addReply(c, nx ? shared.cone : shared.ok);
3250 }
3251
3252 static void setCommand(redisClient *c) {
3253 setGenericCommand(c,0);
3254 }
3255
3256 static void setnxCommand(redisClient *c) {
3257 setGenericCommand(c,1);
3258 }
3259
3260 static int getGenericCommand(redisClient *c) {
3261 robj *o = lookupKeyRead(c->db,c->argv[1]);
3262
3263 if (o == NULL) {
3264 addReply(c,shared.nullbulk);
3265 return REDIS_OK;
3266 } else {
3267 if (o->type != REDIS_STRING) {
3268 addReply(c,shared.wrongtypeerr);
3269 return REDIS_ERR;
3270 } else {
3271 addReplyBulkLen(c,o);
3272 addReply(c,o);
3273 addReply(c,shared.crlf);
3274 return REDIS_OK;
3275 }
3276 }
3277 }
3278
3279 static void getCommand(redisClient *c) {
3280 getGenericCommand(c);
3281 }
3282
3283 static void getsetCommand(redisClient *c) {
3284 if (getGenericCommand(c) == REDIS_ERR) return;
3285 if (dictAdd(c->db->dict,c->argv[1],c->argv[2]) == DICT_ERR) {
3286 dictReplace(c->db->dict,c->argv[1],c->argv[2]);
3287 } else {
3288 incrRefCount(c->argv[1]);
3289 }
3290 incrRefCount(c->argv[2]);
3291 server.dirty++;
3292 removeExpire(c->db,c->argv[1]);
3293 }
3294
3295 static void mgetCommand(redisClient *c) {
3296 int j;
3297
3298 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-1));
3299 for (j = 1; j < c->argc; j++) {
3300 robj *o = lookupKeyRead(c->db,c->argv[j]);
3301 if (o == NULL) {
3302 addReply(c,shared.nullbulk);
3303 } else {
3304 if (o->type != REDIS_STRING) {
3305 addReply(c,shared.nullbulk);
3306 } else {
3307 addReplyBulkLen(c,o);
3308 addReply(c,o);
3309 addReply(c,shared.crlf);
3310 }
3311 }
3312 }
3313 }
3314
3315 static void msetGenericCommand(redisClient *c, int nx) {
3316 int j, busykeys = 0;
3317
3318 if ((c->argc % 2) == 0) {
3319 addReplySds(c,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
3320 return;
3321 }
3322 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
3323 * set nothing at all if at least one already key exists. */
3324 if (nx) {
3325 for (j = 1; j < c->argc; j += 2) {
3326 if (lookupKeyWrite(c->db,c->argv[j]) != NULL) {
3327 busykeys++;
3328 }
3329 }
3330 }
3331 if (busykeys) {
3332 addReply(c, shared.czero);
3333 return;
3334 }
3335
3336 for (j = 1; j < c->argc; j += 2) {
3337 int retval;
3338
3339 tryObjectEncoding(c->argv[j+1]);
3340 retval = dictAdd(c->db->dict,c->argv[j],c->argv[j+1]);
3341 if (retval == DICT_ERR) {
3342 dictReplace(c->db->dict,c->argv[j],c->argv[j+1]);
3343 incrRefCount(c->argv[j+1]);
3344 } else {
3345 incrRefCount(c->argv[j]);
3346 incrRefCount(c->argv[j+1]);
3347 }
3348 removeExpire(c->db,c->argv[j]);
3349 }
3350 server.dirty += (c->argc-1)/2;
3351 addReply(c, nx ? shared.cone : shared.ok);
3352 }
3353
3354 static void msetCommand(redisClient *c) {
3355 msetGenericCommand(c,0);
3356 }
3357
3358 static void msetnxCommand(redisClient *c) {
3359 msetGenericCommand(c,1);
3360 }
3361
3362 static void incrDecrCommand(redisClient *c, long long incr) {
3363 long long value;
3364 int retval;
3365 robj *o;
3366
3367 o = lookupKeyWrite(c->db,c->argv[1]);
3368 if (o == NULL) {
3369 value = 0;
3370 } else {
3371 if (o->type != REDIS_STRING) {
3372 value = 0;
3373 } else {
3374 char *eptr;
3375
3376 if (o->encoding == REDIS_ENCODING_RAW)
3377 value = strtoll(o->ptr, &eptr, 10);
3378 else if (o->encoding == REDIS_ENCODING_INT)
3379 value = (long)o->ptr;
3380 else
3381 redisAssert(1 != 1);
3382 }
3383 }
3384
3385 value += incr;
3386 o = createObject(REDIS_STRING,sdscatprintf(sdsempty(),"%lld",value));
3387 tryObjectEncoding(o);
3388 retval = dictAdd(c->db->dict,c->argv[1],o);
3389 if (retval == DICT_ERR) {
3390 dictReplace(c->db->dict,c->argv[1],o);
3391 removeExpire(c->db,c->argv[1]);
3392 } else {
3393 incrRefCount(c->argv[1]);
3394 }
3395 server.dirty++;
3396 addReply(c,shared.colon);
3397 addReply(c,o);
3398 addReply(c,shared.crlf);
3399 }
3400
3401 static void incrCommand(redisClient *c) {
3402 incrDecrCommand(c,1);
3403 }
3404
3405 static void decrCommand(redisClient *c) {
3406 incrDecrCommand(c,-1);
3407 }
3408
3409 static void incrbyCommand(redisClient *c) {
3410 long long incr = strtoll(c->argv[2]->ptr, NULL, 10);
3411 incrDecrCommand(c,incr);
3412 }
3413
3414 static void decrbyCommand(redisClient *c) {
3415 long long incr = strtoll(c->argv[2]->ptr, NULL, 10);
3416 incrDecrCommand(c,-incr);
3417 }
3418
3419 /* ========================= Type agnostic commands ========================= */
3420
3421 static void delCommand(redisClient *c) {
3422 int deleted = 0, j;
3423
3424 for (j = 1; j < c->argc; j++) {
3425 if (deleteKey(c->db,c->argv[j])) {
3426 server.dirty++;
3427 deleted++;
3428 }
3429 }
3430 switch(deleted) {
3431 case 0:
3432 addReply(c,shared.czero);
3433 break;
3434 case 1:
3435 addReply(c,shared.cone);
3436 break;
3437 default:
3438 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",deleted));
3439 break;
3440 }
3441 }
3442
3443 static void existsCommand(redisClient *c) {
3444 addReply(c,lookupKeyRead(c->db,c->argv[1]) ? shared.cone : shared.czero);
3445 }
3446
3447 static void selectCommand(redisClient *c) {
3448 int id = atoi(c->argv[1]->ptr);
3449
3450 if (selectDb(c,id) == REDIS_ERR) {
3451 addReplySds(c,sdsnew("-ERR invalid DB index\r\n"));
3452 } else {
3453 addReply(c,shared.ok);
3454 }
3455 }
3456
3457 static void randomkeyCommand(redisClient *c) {
3458 dictEntry *de;
3459
3460 while(1) {
3461 de = dictGetRandomKey(c->db->dict);
3462 if (!de || expireIfNeeded(c->db,dictGetEntryKey(de)) == 0) break;
3463 }
3464 if (de == NULL) {
3465 addReply(c,shared.plus);
3466 addReply(c,shared.crlf);
3467 } else {
3468 addReply(c,shared.plus);
3469 addReply(c,dictGetEntryKey(de));
3470 addReply(c,shared.crlf);
3471 }
3472 }
3473
3474 static void keysCommand(redisClient *c) {
3475 dictIterator *di;
3476 dictEntry *de;
3477 sds pattern = c->argv[1]->ptr;
3478 int plen = sdslen(pattern);
3479 unsigned long numkeys = 0, keyslen = 0;
3480 robj *lenobj = createObject(REDIS_STRING,NULL);
3481
3482 di = dictGetIterator(c->db->dict);
3483 addReply(c,lenobj);
3484 decrRefCount(lenobj);
3485 while((de = dictNext(di)) != NULL) {
3486 robj *keyobj = dictGetEntryKey(de);
3487
3488 sds key = keyobj->ptr;
3489 if ((pattern[0] == '*' && pattern[1] == '\0') ||
3490 stringmatchlen(pattern,plen,key,sdslen(key),0)) {
3491 if (expireIfNeeded(c->db,keyobj) == 0) {
3492 if (numkeys != 0)
3493 addReply(c,shared.space);
3494 addReply(c,keyobj);
3495 numkeys++;
3496 keyslen += sdslen(key);
3497 }
3498 }
3499 }
3500 dictReleaseIterator(di);
3501 lenobj->ptr = sdscatprintf(sdsempty(),"$%lu\r\n",keyslen+(numkeys ? (numkeys-1) : 0));
3502 addReply(c,shared.crlf);
3503 }
3504
3505 static void dbsizeCommand(redisClient *c) {
3506 addReplySds(c,
3507 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c->db->dict)));
3508 }
3509
3510 static void lastsaveCommand(redisClient *c) {
3511 addReplySds(c,
3512 sdscatprintf(sdsempty(),":%lu\r\n",server.lastsave));
3513 }
3514
3515 static void typeCommand(redisClient *c) {
3516 robj *o;
3517 char *type;
3518
3519 o = lookupKeyRead(c->db,c->argv[1]);
3520 if (o == NULL) {
3521 type = "+none";
3522 } else {
3523 switch(o->type) {
3524 case REDIS_STRING: type = "+string"; break;
3525 case REDIS_LIST: type = "+list"; break;
3526 case REDIS_SET: type = "+set"; break;
3527 case REDIS_ZSET: type = "+zset"; break;
3528 default: type = "unknown"; break;
3529 }
3530 }
3531 addReplySds(c,sdsnew(type));
3532 addReply(c,shared.crlf);
3533 }
3534
3535 static void saveCommand(redisClient *c) {
3536 if (server.bgsavechildpid != -1) {
3537 addReplySds(c,sdsnew("-ERR background save in progress\r\n"));
3538 return;
3539 }
3540 if (rdbSave(server.dbfilename) == REDIS_OK) {
3541 addReply(c,shared.ok);
3542 } else {
3543 addReply(c,shared.err);
3544 }
3545 }
3546
3547 static void bgsaveCommand(redisClient *c) {
3548 if (server.bgsavechildpid != -1) {
3549 addReplySds(c,sdsnew("-ERR background save already in progress\r\n"));
3550 return;
3551 }
3552 if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
3553 char *status = "+Background saving started\r\n";
3554 addReplySds(c,sdsnew(status));
3555 } else {
3556 addReply(c,shared.err);
3557 }
3558 }
3559
3560 static void shutdownCommand(redisClient *c) {
3561 redisLog(REDIS_WARNING,"User requested shutdown, saving DB...");
3562 /* Kill the saving child if there is a background saving in progress.
3563 We want to avoid race conditions, for instance our saving child may
3564 overwrite the synchronous saving did by SHUTDOWN. */
3565 if (server.bgsavechildpid != -1) {
3566 redisLog(REDIS_WARNING,"There is a live saving child. Killing it!");
3567 kill(server.bgsavechildpid,SIGKILL);
3568 rdbRemoveTempFile(server.bgsavechildpid);
3569 }
3570 if (server.appendonly) {
3571 /* Append only file: fsync() the AOF and exit */
3572 fsync(server.appendfd);
3573 exit(0);
3574 } else {
3575 /* Snapshotting. Perform a SYNC SAVE and exit */
3576 if (rdbSave(server.dbfilename) == REDIS_OK) {
3577 if (server.daemonize)
3578 unlink(server.pidfile);
3579 redisLog(REDIS_WARNING,"%zu bytes used at exit",zmalloc_used_memory());
3580 redisLog(REDIS_WARNING,"Server exit now, bye bye...");
3581 exit(0);
3582 } else {
3583 /* Ooops.. error saving! The best we can do is to continue operating.
3584 * Note that if there was a background saving process, in the next
3585 * cron() Redis will be notified that the background saving aborted,
3586 * handling special stuff like slaves pending for synchronization... */
3587 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit");
3588 addReplySds(c,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
3589 }
3590 }
3591 }
3592
3593 static void renameGenericCommand(redisClient *c, int nx) {
3594 robj *o;
3595
3596 /* To use the same key as src and dst is probably an error */
3597 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
3598 addReply(c,shared.sameobjecterr);
3599 return;
3600 }
3601
3602 o = lookupKeyWrite(c->db,c->argv[1]);
3603 if (o == NULL) {
3604 addReply(c,shared.nokeyerr);
3605 return;
3606 }
3607 incrRefCount(o);
3608 deleteIfVolatile(c->db,c->argv[2]);
3609 if (dictAdd(c->db->dict,c->argv[2],o) == DICT_ERR) {
3610 if (nx) {
3611 decrRefCount(o);
3612 addReply(c,shared.czero);
3613 return;
3614 }
3615 dictReplace(c->db->dict,c->argv[2],o);
3616 } else {
3617 incrRefCount(c->argv[2]);
3618 }
3619 deleteKey(c->db,c->argv[1]);
3620 server.dirty++;
3621 addReply(c,nx ? shared.cone : shared.ok);
3622 }
3623
3624 static void renameCommand(redisClient *c) {
3625 renameGenericCommand(c,0);
3626 }
3627
3628 static void renamenxCommand(redisClient *c) {
3629 renameGenericCommand(c,1);
3630 }
3631
3632 static void moveCommand(redisClient *c) {
3633 robj *o;
3634 redisDb *src, *dst;
3635 int srcid;
3636
3637 /* Obtain source and target DB pointers */
3638 src = c->db;
3639 srcid = c->db->id;
3640 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
3641 addReply(c,shared.outofrangeerr);
3642 return;
3643 }
3644 dst = c->db;
3645 selectDb(c,srcid); /* Back to the source DB */
3646
3647 /* If the user is moving using as target the same
3648 * DB as the source DB it is probably an error. */
3649 if (src == dst) {
3650 addReply(c,shared.sameobjecterr);
3651 return;
3652 }
3653
3654 /* Check if the element exists and get a reference */
3655 o = lookupKeyWrite(c->db,c->argv[1]);
3656 if (!o) {
3657 addReply(c,shared.czero);
3658 return;
3659 }
3660
3661 /* Try to add the element to the target DB */
3662 deleteIfVolatile(dst,c->argv[1]);
3663 if (dictAdd(dst->dict,c->argv[1],o) == DICT_ERR) {
3664 addReply(c,shared.czero);
3665 return;
3666 }
3667 incrRefCount(c->argv[1]);
3668 incrRefCount(o);
3669
3670 /* OK! key moved, free the entry in the source DB */
3671 deleteKey(src,c->argv[1]);
3672 server.dirty++;
3673 addReply(c,shared.cone);
3674 }
3675
3676 /* =================================== Lists ================================ */
3677 static void pushGenericCommand(redisClient *c, int where) {
3678 robj *lobj;
3679 list *list;
3680
3681 lobj = lookupKeyWrite(c->db,c->argv[1]);
3682 if (lobj == NULL) {
3683 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
3684 addReply(c,shared.ok);
3685 return;
3686 }
3687 lobj = createListObject();
3688 list = lobj->ptr;
3689 if (where == REDIS_HEAD) {
3690 listAddNodeHead(list,c->argv[2]);
3691 } else {
3692 listAddNodeTail(list,c->argv[2]);
3693 }
3694 dictAdd(c->db->dict,c->argv[1],lobj);
3695 incrRefCount(c->argv[1]);
3696 incrRefCount(c->argv[2]);
3697 } else {
3698 if (lobj->type != REDIS_LIST) {
3699 addReply(c,shared.wrongtypeerr);
3700 return;
3701 }
3702 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
3703 addReply(c,shared.ok);
3704 return;
3705 }
3706 list = lobj->ptr;
3707 if (where == REDIS_HEAD) {
3708 listAddNodeHead(list,c->argv[2]);
3709 } else {
3710 listAddNodeTail(list,c->argv[2]);
3711 }
3712 incrRefCount(c->argv[2]);
3713 }
3714 server.dirty++;
3715 addReply(c,shared.ok);
3716 }
3717
3718 static void lpushCommand(redisClient *c) {
3719 pushGenericCommand(c,REDIS_HEAD);
3720 }
3721
3722 static void rpushCommand(redisClient *c) {
3723 pushGenericCommand(c,REDIS_TAIL);
3724 }
3725
3726 static void llenCommand(redisClient *c) {
3727 robj *o;
3728 list *l;
3729
3730 o = lookupKeyRead(c->db,c->argv[1]);
3731 if (o == NULL) {
3732 addReply(c,shared.czero);
3733 return;
3734 } else {
3735 if (o->type != REDIS_LIST) {
3736 addReply(c,shared.wrongtypeerr);
3737 } else {
3738 l = o->ptr;
3739 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",listLength(l)));
3740 }
3741 }
3742 }
3743
3744 static void lindexCommand(redisClient *c) {
3745 robj *o;
3746 int index = atoi(c->argv[2]->ptr);
3747
3748 o = lookupKeyRead(c->db,c->argv[1]);
3749 if (o == NULL) {
3750 addReply(c,shared.nullbulk);
3751 } else {
3752 if (o->type != REDIS_LIST) {
3753 addReply(c,shared.wrongtypeerr);
3754 } else {
3755 list *list = o->ptr;
3756 listNode *ln;
3757
3758 ln = listIndex(list, index);
3759 if (ln == NULL) {
3760 addReply(c,shared.nullbulk);
3761 } else {
3762 robj *ele = listNodeValue(ln);
3763 addReplyBulkLen(c,ele);
3764 addReply(c,ele);
3765 addReply(c,shared.crlf);
3766 }
3767 }
3768 }
3769 }
3770
3771 static void lsetCommand(redisClient *c) {
3772 robj *o;
3773 int index = atoi(c->argv[2]->ptr);
3774
3775 o = lookupKeyWrite(c->db,c->argv[1]);
3776 if (o == NULL) {
3777 addReply(c,shared.nokeyerr);
3778 } else {
3779 if (o->type != REDIS_LIST) {
3780 addReply(c,shared.wrongtypeerr);
3781 } else {
3782 list *list = o->ptr;
3783 listNode *ln;
3784
3785 ln = listIndex(list, index);
3786 if (ln == NULL) {
3787 addReply(c,shared.outofrangeerr);
3788 } else {
3789 robj *ele = listNodeValue(ln);
3790
3791 decrRefCount(ele);
3792 listNodeValue(ln) = c->argv[3];
3793 incrRefCount(c->argv[3]);
3794 addReply(c,shared.ok);
3795 server.dirty++;
3796 }
3797 }
3798 }
3799 }
3800
3801 static void popGenericCommand(redisClient *c, int where) {
3802 robj *o;
3803
3804 o = lookupKeyWrite(c->db,c->argv[1]);
3805 if (o == NULL) {
3806 addReply(c,shared.nullbulk);
3807 } else {
3808 if (o->type != REDIS_LIST) {
3809 addReply(c,shared.wrongtypeerr);
3810 } else {
3811 list *list = o->ptr;
3812 listNode *ln;
3813
3814 if (where == REDIS_HEAD)
3815 ln = listFirst(list);
3816 else
3817 ln = listLast(list);
3818
3819 if (ln == NULL) {
3820 addReply(c,shared.nullbulk);
3821 } else {
3822 robj *ele = listNodeValue(ln);
3823 addReplyBulkLen(c,ele);
3824 addReply(c,ele);
3825 addReply(c,shared.crlf);
3826 listDelNode(list,ln);
3827 server.dirty++;
3828 }
3829 }
3830 }
3831 }
3832
3833 static void lpopCommand(redisClient *c) {
3834 popGenericCommand(c,REDIS_HEAD);
3835 }
3836
3837 static void rpopCommand(redisClient *c) {
3838 popGenericCommand(c,REDIS_TAIL);
3839 }
3840
3841 static void lrangeCommand(redisClient *c) {
3842 robj *o;
3843 int start = atoi(c->argv[2]->ptr);
3844 int end = atoi(c->argv[3]->ptr);
3845
3846 o = lookupKeyRead(c->db,c->argv[1]);
3847 if (o == NULL) {
3848 addReply(c,shared.nullmultibulk);
3849 } else {
3850 if (o->type != REDIS_LIST) {
3851 addReply(c,shared.wrongtypeerr);
3852 } else {
3853 list *list = o->ptr;
3854 listNode *ln;
3855 int llen = listLength(list);
3856 int rangelen, j;
3857 robj *ele;
3858
3859 /* convert negative indexes */
3860 if (start < 0) start = llen+start;
3861 if (end < 0) end = llen+end;
3862 if (start < 0) start = 0;
3863 if (end < 0) end = 0;
3864
3865 /* indexes sanity checks */
3866 if (start > end || start >= llen) {
3867 /* Out of range start or start > end result in empty list */
3868 addReply(c,shared.emptymultibulk);
3869 return;
3870 }
3871 if (end >= llen) end = llen-1;
3872 rangelen = (end-start)+1;
3873
3874 /* Return the result in form of a multi-bulk reply */
3875 ln = listIndex(list, start);
3876 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",rangelen));
3877 for (j = 0; j < rangelen; j++) {
3878 ele = listNodeValue(ln);
3879 addReplyBulkLen(c,ele);
3880 addReply(c,ele);
3881 addReply(c,shared.crlf);
3882 ln = ln->next;
3883 }
3884 }
3885 }
3886 }
3887
3888 static void ltrimCommand(redisClient *c) {
3889 robj *o;
3890 int start = atoi(c->argv[2]->ptr);
3891 int end = atoi(c->argv[3]->ptr);
3892
3893 o = lookupKeyWrite(c->db,c->argv[1]);
3894 if (o == NULL) {
3895 addReply(c,shared.ok);
3896 } else {
3897 if (o->type != REDIS_LIST) {
3898 addReply(c,shared.wrongtypeerr);
3899 } else {
3900 list *list = o->ptr;
3901 listNode *ln;
3902 int llen = listLength(list);
3903 int j, ltrim, rtrim;
3904
3905 /* convert negative indexes */
3906 if (start < 0) start = llen+start;
3907 if (end < 0) end = llen+end;
3908 if (start < 0) start = 0;
3909 if (end < 0) end = 0;
3910
3911 /* indexes sanity checks */
3912 if (start > end || start >= llen) {
3913 /* Out of range start or start > end result in empty list */
3914 ltrim = llen;
3915 rtrim = 0;
3916 } else {
3917 if (end >= llen) end = llen-1;
3918 ltrim = start;
3919 rtrim = llen-end-1;
3920 }
3921
3922 /* Remove list elements to perform the trim */
3923 for (j = 0; j < ltrim; j++) {
3924 ln = listFirst(list);
3925 listDelNode(list,ln);
3926 }
3927 for (j = 0; j < rtrim; j++) {
3928 ln = listLast(list);
3929 listDelNode(list,ln);
3930 }
3931 server.dirty++;
3932 addReply(c,shared.ok);
3933 }
3934 }
3935 }
3936
3937 static void lremCommand(redisClient *c) {
3938 robj *o;
3939
3940 o = lookupKeyWrite(c->db,c->argv[1]);
3941 if (o == NULL) {
3942 addReply(c,shared.czero);
3943 } else {
3944 if (o->type != REDIS_LIST) {
3945 addReply(c,shared.wrongtypeerr);
3946 } else {
3947 list *list = o->ptr;
3948 listNode *ln, *next;
3949 int toremove = atoi(c->argv[2]->ptr);
3950 int removed = 0;
3951 int fromtail = 0;
3952
3953 if (toremove < 0) {
3954 toremove = -toremove;
3955 fromtail = 1;
3956 }
3957 ln = fromtail ? list->tail : list->head;
3958 while (ln) {
3959 robj *ele = listNodeValue(ln);
3960
3961 next = fromtail ? ln->prev : ln->next;
3962 if (compareStringObjects(ele,c->argv[3]) == 0) {
3963 listDelNode(list,ln);
3964 server.dirty++;
3965 removed++;
3966 if (toremove && removed == toremove) break;
3967 }
3968 ln = next;
3969 }
3970 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",removed));
3971 }
3972 }
3973 }
3974
3975 /* This is the semantic of this command:
3976 * RPOPLPUSH srclist dstlist:
3977 * IF LLEN(srclist) > 0
3978 * element = RPOP srclist
3979 * LPUSH dstlist element
3980 * RETURN element
3981 * ELSE
3982 * RETURN nil
3983 * END
3984 * END
3985 *
3986 * The idea is to be able to get an element from a list in a reliable way
3987 * since the element is not just returned but pushed against another list
3988 * as well. This command was originally proposed by Ezra Zygmuntowicz.
3989 */
3990 static void rpoplpushcommand(redisClient *c) {
3991 robj *sobj;
3992
3993 sobj = lookupKeyWrite(c->db,c->argv[1]);
3994 if (sobj == NULL) {
3995 addReply(c,shared.nullbulk);
3996 } else {
3997 if (sobj->type != REDIS_LIST) {
3998 addReply(c,shared.wrongtypeerr);
3999 } else {
4000 list *srclist = sobj->ptr;
4001 listNode *ln = listLast(srclist);
4002
4003 if (ln == NULL) {
4004 addReply(c,shared.nullbulk);
4005 } else {
4006 robj *dobj = lookupKeyWrite(c->db,c->argv[2]);
4007 robj *ele = listNodeValue(ln);
4008 list *dstlist;
4009
4010 if (dobj && dobj->type != REDIS_LIST) {
4011 addReply(c,shared.wrongtypeerr);
4012 return;
4013 }
4014
4015 /* Add the element to the target list (unless it's directly
4016 * passed to some BLPOP-ing client */
4017 if (!handleClientsWaitingListPush(c,c->argv[2],ele)) {
4018 if (dobj == NULL) {
4019 /* Create the list if the key does not exist */
4020 dobj = createListObject();
4021 dictAdd(c->db->dict,c->argv[2],dobj);
4022 incrRefCount(c->argv[2]);
4023 }
4024 dstlist = dobj->ptr;
4025 listAddNodeHead(dstlist,ele);
4026 incrRefCount(ele);
4027 }
4028
4029 /* Send the element to the client as reply as well */
4030 addReplyBulkLen(c,ele);
4031 addReply(c,ele);
4032 addReply(c,shared.crlf);
4033
4034 /* Finally remove the element from the source list */
4035 listDelNode(srclist,ln);
4036 server.dirty++;
4037 }
4038 }
4039 }
4040 }
4041
4042
4043 /* ==================================== Sets ================================ */
4044
4045 static void saddCommand(redisClient *c) {
4046 robj *set;
4047
4048 set = lookupKeyWrite(c->db,c->argv[1]);
4049 if (set == NULL) {
4050 set = createSetObject();
4051 dictAdd(c->db->dict,c->argv[1],set);
4052 incrRefCount(c->argv[1]);
4053 } else {
4054 if (set->type != REDIS_SET) {
4055 addReply(c,shared.wrongtypeerr);
4056 return;
4057 }
4058 }
4059 if (dictAdd(set->ptr,c->argv[2],NULL) == DICT_OK) {
4060 incrRefCount(c->argv[2]);
4061 server.dirty++;
4062 addReply(c,shared.cone);
4063 } else {
4064 addReply(c,shared.czero);
4065 }
4066 }
4067
4068 static void sremCommand(redisClient *c) {
4069 robj *set;
4070
4071 set = lookupKeyWrite(c->db,c->argv[1]);
4072 if (set == NULL) {
4073 addReply(c,shared.czero);
4074 } else {
4075 if (set->type != REDIS_SET) {
4076 addReply(c,shared.wrongtypeerr);
4077 return;
4078 }
4079 if (dictDelete(set->ptr,c->argv[2]) == DICT_OK) {
4080 server.dirty++;
4081 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
4082 addReply(c,shared.cone);
4083 } else {
4084 addReply(c,shared.czero);
4085 }
4086 }
4087 }
4088
4089 static void smoveCommand(redisClient *c) {
4090 robj *srcset, *dstset;
4091
4092 srcset = lookupKeyWrite(c->db,c->argv[1]);
4093 dstset = lookupKeyWrite(c->db,c->argv[2]);
4094
4095 /* If the source key does not exist return 0, if it's of the wrong type
4096 * raise an error */
4097 if (srcset == NULL || srcset->type != REDIS_SET) {
4098 addReply(c, srcset ? shared.wrongtypeerr : shared.czero);
4099 return;
4100 }
4101 /* Error if the destination key is not a set as well */
4102 if (dstset && dstset->type != REDIS_SET) {
4103 addReply(c,shared.wrongtypeerr);
4104 return;
4105 }
4106 /* Remove the element from the source set */
4107 if (dictDelete(srcset->ptr,c->argv[3]) == DICT_ERR) {
4108 /* Key not found in the src set! return zero */
4109 addReply(c,shared.czero);
4110 return;
4111 }
4112 server.dirty++;
4113 /* Add the element to the destination set */
4114 if (!dstset) {
4115 dstset = createSetObject();
4116 dictAdd(c->db->dict,c->argv[2],dstset);
4117 incrRefCount(c->argv[2]);
4118 }
4119 if (dictAdd(dstset->ptr,c->argv[3],NULL) == DICT_OK)
4120 incrRefCount(c->argv[3]);
4121 addReply(c,shared.cone);
4122 }
4123
4124 static void sismemberCommand(redisClient *c) {
4125 robj *set;
4126
4127 set = lookupKeyRead(c->db,c->argv[1]);
4128 if (set == NULL) {
4129 addReply(c,shared.czero);
4130 } else {
4131 if (set->type != REDIS_SET) {
4132 addReply(c,shared.wrongtypeerr);
4133 return;
4134 }
4135 if (dictFind(set->ptr,c->argv[2]))
4136 addReply(c,shared.cone);
4137 else
4138 addReply(c,shared.czero);
4139 }
4140 }
4141
4142 static void scardCommand(redisClient *c) {
4143 robj *o;
4144 dict *s;
4145
4146 o = lookupKeyRead(c->db,c->argv[1]);
4147 if (o == NULL) {
4148 addReply(c,shared.czero);
4149 return;
4150 } else {
4151 if (o->type != REDIS_SET) {
4152 addReply(c,shared.wrongtypeerr);
4153 } else {
4154 s = o->ptr;
4155 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",
4156 dictSize(s)));
4157 }
4158 }
4159 }
4160
4161 static void spopCommand(redisClient *c) {
4162 robj *set;
4163 dictEntry *de;
4164
4165 set = lookupKeyWrite(c->db,c->argv[1]);
4166 if (set == NULL) {
4167 addReply(c,shared.nullbulk);
4168 } else {
4169 if (set->type != REDIS_SET) {
4170 addReply(c,shared.wrongtypeerr);
4171 return;
4172 }
4173 de = dictGetRandomKey(set->ptr);
4174 if (de == NULL) {
4175 addReply(c,shared.nullbulk);
4176 } else {
4177 robj *ele = dictGetEntryKey(de);
4178
4179 addReplyBulkLen(c,ele);
4180 addReply(c,ele);
4181 addReply(c,shared.crlf);
4182 dictDelete(set->ptr,ele);
4183 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
4184 server.dirty++;
4185 }
4186 }
4187 }
4188
4189 static void srandmemberCommand(redisClient *c) {
4190 robj *set;
4191 dictEntry *de;
4192
4193 set = lookupKeyRead(c->db,c->argv[1]);
4194 if (set == NULL) {
4195 addReply(c,shared.nullbulk);
4196 } else {
4197 if (set->type != REDIS_SET) {
4198 addReply(c,shared.wrongtypeerr);
4199 return;
4200 }
4201 de = dictGetRandomKey(set->ptr);
4202 if (de == NULL) {
4203 addReply(c,shared.nullbulk);
4204 } else {
4205 robj *ele = dictGetEntryKey(de);
4206
4207 addReplyBulkLen(c,ele);
4208 addReply(c,ele);
4209 addReply(c,shared.crlf);
4210 }
4211 }
4212 }
4213
4214 static int qsortCompareSetsByCardinality(const void *s1, const void *s2) {
4215 dict **d1 = (void*) s1, **d2 = (void*) s2;
4216
4217 return dictSize(*d1)-dictSize(*d2);
4218 }
4219
4220 static void sinterGenericCommand(redisClient *c, robj **setskeys, unsigned long setsnum, robj *dstkey) {
4221 dict **dv = zmalloc(sizeof(dict*)*setsnum);
4222 dictIterator *di;
4223 dictEntry *de;
4224 robj *lenobj = NULL, *dstset = NULL;
4225 unsigned long j, cardinality = 0;
4226
4227 for (j = 0; j < setsnum; j++) {
4228 robj *setobj;
4229
4230 setobj = dstkey ?
4231 lookupKeyWrite(c->db,setskeys[j]) :
4232 lookupKeyRead(c->db,setskeys[j]);
4233 if (!setobj) {
4234 zfree(dv);
4235 if (dstkey) {
4236 if (deleteKey(c->db,dstkey))
4237 server.dirty++;
4238 addReply(c,shared.czero);
4239 } else {
4240 addReply(c,shared.nullmultibulk);
4241 }
4242 return;
4243 }
4244 if (setobj->type != REDIS_SET) {
4245 zfree(dv);
4246 addReply(c,shared.wrongtypeerr);
4247 return;
4248 }
4249 dv[j] = setobj->ptr;
4250 }
4251 /* Sort sets from the smallest to largest, this will improve our
4252 * algorithm's performace */
4253 qsort(dv,setsnum,sizeof(dict*),qsortCompareSetsByCardinality);
4254
4255 /* The first thing we should output is the total number of elements...
4256 * since this is a multi-bulk write, but at this stage we don't know
4257 * the intersection set size, so we use a trick, append an empty object
4258 * to the output list and save the pointer to later modify it with the
4259 * right length */
4260 if (!dstkey) {
4261 lenobj = createObject(REDIS_STRING,NULL);
4262 addReply(c,lenobj);
4263 decrRefCount(lenobj);
4264 } else {
4265 /* If we have a target key where to store the resulting set
4266 * create this key with an empty set inside */
4267 dstset = createSetObject();
4268 }
4269
4270 /* Iterate all the elements of the first (smallest) set, and test
4271 * the element against all the other sets, if at least one set does
4272 * not include the element it is discarded */
4273 di = dictGetIterator(dv[0]);
4274
4275 while((de = dictNext(di)) != NULL) {
4276 robj *ele;
4277
4278 for (j = 1; j < setsnum; j++)
4279 if (dictFind(dv[j],dictGetEntryKey(de)) == NULL) break;
4280 if (j != setsnum)
4281 continue; /* at least one set does not contain the member */
4282 ele = dictGetEntryKey(de);
4283 if (!dstkey) {
4284 addReplyBulkLen(c,ele);
4285 addReply(c,ele);
4286 addReply(c,shared.crlf);
4287 cardinality++;
4288 } else {
4289 dictAdd(dstset->ptr,ele,NULL);
4290 incrRefCount(ele);
4291 }
4292 }
4293 dictReleaseIterator(di);
4294
4295 if (dstkey) {
4296 /* Store the resulting set into the target */
4297 deleteKey(c->db,dstkey);
4298 dictAdd(c->db->dict,dstkey,dstset);
4299 incrRefCount(dstkey);
4300 }
4301
4302 if (!dstkey) {
4303 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",cardinality);
4304 } else {
4305 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",
4306 dictSize((dict*)dstset->ptr)));
4307 server.dirty++;
4308 }
4309 zfree(dv);
4310 }
4311
4312 static void sinterCommand(redisClient *c) {
4313 sinterGenericCommand(c,c->argv+1,c->argc-1,NULL);
4314 }
4315
4316 static void sinterstoreCommand(redisClient *c) {
4317 sinterGenericCommand(c,c->argv+2,c->argc-2,c->argv[1]);
4318 }
4319
4320 #define REDIS_OP_UNION 0
4321 #define REDIS_OP_DIFF 1
4322
4323 static void sunionDiffGenericCommand(redisClient *c, robj **setskeys, int setsnum, robj *dstkey, int op) {
4324 dict **dv = zmalloc(sizeof(dict*)*setsnum);
4325 dictIterator *di;
4326 dictEntry *de;
4327 robj *dstset = NULL;
4328 int j, cardinality = 0;
4329
4330 for (j = 0; j < setsnum; j++) {
4331 robj *setobj;
4332
4333 setobj = dstkey ?
4334 lookupKeyWrite(c->db,setskeys[j]) :
4335 lookupKeyRead(c->db,setskeys[j]);
4336 if (!setobj) {
4337 dv[j] = NULL;
4338 continue;
4339 }
4340 if (setobj->type != REDIS_SET) {
4341 zfree(dv);
4342 addReply(c,shared.wrongtypeerr);
4343 return;
4344 }
4345 dv[j] = setobj->ptr;
4346 }
4347
4348 /* We need a temp set object to store our union. If the dstkey
4349 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
4350 * this set object will be the resulting object to set into the target key*/
4351 dstset = createSetObject();
4352
4353 /* Iterate all the elements of all the sets, add every element a single
4354 * time to the result set */
4355 for (j = 0; j < setsnum; j++) {
4356 if (op == REDIS_OP_DIFF && j == 0 && !dv[j]) break; /* result set is empty */
4357 if (!dv[j]) continue; /* non existing keys are like empty sets */
4358
4359 di = dictGetIterator(dv[j]);
4360
4361 while((de = dictNext(di)) != NULL) {
4362 robj *ele;
4363
4364 /* dictAdd will not add the same element multiple times */
4365 ele = dictGetEntryKey(de);
4366 if (op == REDIS_OP_UNION || j == 0) {
4367 if (dictAdd(dstset->ptr,ele,NULL) == DICT_OK) {
4368 incrRefCount(ele);
4369 cardinality++;
4370 }
4371 } else if (op == REDIS_OP_DIFF) {
4372 if (dictDelete(dstset->ptr,ele) == DICT_OK) {
4373 cardinality--;
4374 }
4375 }
4376 }
4377 dictReleaseIterator(di);
4378
4379 if (op == REDIS_OP_DIFF && cardinality == 0) break; /* result set is empty */
4380 }
4381
4382 /* Output the content of the resulting set, if not in STORE mode */
4383 if (!dstkey) {
4384 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",cardinality));
4385 di = dictGetIterator(dstset->ptr);
4386 while((de = dictNext(di)) != NULL) {
4387 robj *ele;
4388
4389 ele = dictGetEntryKey(de);
4390 addReplyBulkLen(c,ele);
4391 addReply(c,ele);
4392 addReply(c,shared.crlf);
4393 }
4394 dictReleaseIterator(di);
4395 } else {
4396 /* If we have a target key where to store the resulting set
4397 * create this key with the result set inside */
4398 deleteKey(c->db,dstkey);
4399 dictAdd(c->db->dict,dstkey,dstset);
4400 incrRefCount(dstkey);
4401 }
4402
4403 /* Cleanup */
4404 if (!dstkey) {
4405 decrRefCount(dstset);
4406 } else {
4407 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",
4408 dictSize((dict*)dstset->ptr)));
4409 server.dirty++;
4410 }
4411 zfree(dv);
4412 }
4413
4414 static void sunionCommand(redisClient *c) {
4415 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_UNION);
4416 }
4417
4418 static void sunionstoreCommand(redisClient *c) {
4419 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_UNION);
4420 }
4421
4422 static void sdiffCommand(redisClient *c) {
4423 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_DIFF);
4424 }
4425
4426 static void sdiffstoreCommand(redisClient *c) {
4427 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_DIFF);
4428 }
4429
4430 /* ==================================== ZSets =============================== */
4431
4432 /* ZSETs are ordered sets using two data structures to hold the same elements
4433 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
4434 * data structure.
4435 *
4436 * The elements are added to an hash table mapping Redis objects to scores.
4437 * At the same time the elements are added to a skip list mapping scores
4438 * to Redis objects (so objects are sorted by scores in this "view"). */
4439
4440 /* This skiplist implementation is almost a C translation of the original
4441 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
4442 * Alternative to Balanced Trees", modified in three ways:
4443 * a) this implementation allows for repeated values.
4444 * b) the comparison is not just by key (our 'score') but by satellite data.
4445 * c) there is a back pointer, so it's a doubly linked list with the back
4446 * pointers being only at "level 1". This allows to traverse the list
4447 * from tail to head, useful for ZREVRANGE. */
4448
4449 static zskiplistNode *zslCreateNode(int level, double score, robj *obj) {
4450 zskiplistNode *zn = zmalloc(sizeof(*zn));
4451
4452 zn->forward = zmalloc(sizeof(zskiplistNode*) * level);
4453 zn->score = score;
4454 zn->obj = obj;
4455 return zn;
4456 }
4457
4458 static zskiplist *zslCreate(void) {
4459 int j;
4460 zskiplist *zsl;
4461
4462 zsl = zmalloc(sizeof(*zsl));
4463 zsl->level = 1;
4464 zsl->length = 0;
4465 zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);
4466 for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++)
4467 zsl->header->forward[j] = NULL;
4468 zsl->header->backward = NULL;
4469 zsl->tail = NULL;
4470 return zsl;
4471 }
4472
4473 static void zslFreeNode(zskiplistNode *node) {
4474 decrRefCount(node->obj);
4475 zfree(node->forward);
4476 zfree(node);
4477 }
4478
4479 static void zslFree(zskiplist *zsl) {
4480 zskiplistNode *node = zsl->header->forward[0], *next;
4481
4482 zfree(zsl->header->forward);
4483 zfree(zsl->header);
4484 while(node) {
4485 next = node->forward[0];
4486 zslFreeNode(node);
4487 node = next;
4488 }
4489 zfree(zsl);
4490 }
4491
4492 static int zslRandomLevel(void) {
4493 int level = 1;
4494 while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
4495 level += 1;
4496 return level;
4497 }
4498
4499 static void zslInsert(zskiplist *zsl, double score, robj *obj) {
4500 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
4501 int i, level;
4502
4503 x = zsl->header;
4504 for (i = zsl->level-1; i >= 0; i--) {
4505 while (x->forward[i] &&
4506 (x->forward[i]->score < score ||
4507 (x->forward[i]->score == score &&
4508 compareStringObjects(x->forward[i]->obj,obj) < 0)))
4509 x = x->forward[i];
4510 update[i] = x;
4511 }
4512 /* we assume the key is not already inside, since we allow duplicated
4513 * scores, and the re-insertion of score and redis object should never
4514 * happpen since the caller of zslInsert() should test in the hash table
4515 * if the element is already inside or not. */
4516 level = zslRandomLevel();
4517 if (level > zsl->level) {
4518 for (i = zsl->level; i < level; i++)
4519 update[i] = zsl->header;
4520 zsl->level = level;
4521 }
4522 x = zslCreateNode(level,score,obj);
4523 for (i = 0; i < level; i++) {
4524 x->forward[i] = update[i]->forward[i];
4525 update[i]->forward[i] = x;
4526 }
4527 x->backward = (update[0] == zsl->header) ? NULL : update[0];
4528 if (x->forward[0])
4529 x->forward[0]->backward = x;
4530 else
4531 zsl->tail = x;
4532 zsl->length++;
4533 }
4534
4535 /* Delete an element with matching score/object from the skiplist. */
4536 static int zslDelete(zskiplist *zsl, double score, robj *obj) {
4537 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
4538 int i;
4539
4540 x = zsl->header;
4541 for (i = zsl->level-1; i >= 0; i--) {
4542 while (x->forward[i] &&
4543 (x->forward[i]->score < score ||
4544 (x->forward[i]->score == score &&
4545 compareStringObjects(x->forward[i]->obj,obj) < 0)))
4546 x = x->forward[i];
4547 update[i] = x;
4548 }
4549 /* We may have multiple elements with the same score, what we need
4550 * is to find the element with both the right score and object. */
4551 x = x->forward[0];
4552 if (x && score == x->score && compareStringObjects(x->obj,obj) == 0) {
4553 for (i = 0; i < zsl->level; i++) {
4554 if (update[i]->forward[i] != x) break;
4555 update[i]->forward[i] = x->forward[i];
4556 }
4557 if (x->forward[0]) {
4558 x->forward[0]->backward = (x->backward == zsl->header) ?
4559 NULL : x->backward;
4560 } else {
4561 zsl->tail = x->backward;
4562 }
4563 zslFreeNode(x);
4564 while(zsl->level > 1 && zsl->header->forward[zsl->level-1] == NULL)
4565 zsl->level--;
4566 zsl->length--;
4567 return 1;
4568 } else {
4569 return 0; /* not found */
4570 }
4571 return 0; /* not found */
4572 }
4573
4574 /* Delete all the elements with score between min and max from the skiplist.
4575 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
4576 * Note that this function takes the reference to the hash table view of the
4577 * sorted set, in order to remove the elements from the hash table too. */
4578 static unsigned long zslDeleteRange(zskiplist *zsl, double min, double max, dict *dict) {
4579 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
4580 unsigned long removed = 0;
4581 int i;
4582
4583 x = zsl->header;
4584 for (i = zsl->level-1; i >= 0; i--) {
4585 while (x->forward[i] && x->forward[i]->score < min)
4586 x = x->forward[i];
4587 update[i] = x;
4588 }
4589 /* We may have multiple elements with the same score, what we need
4590 * is to find the element with both the right score and object. */
4591 x = x->forward[0];
4592 while (x && x->score <= max) {
4593 zskiplistNode *next;
4594
4595 for (i = 0; i < zsl->level; i++) {
4596 if (update[i]->forward[i] != x) break;
4597 update[i]->forward[i] = x->forward[i];
4598 }
4599 if (x->forward[0]) {
4600 x->forward[0]->backward = (x->backward == zsl->header) ?
4601 NULL : x->backward;
4602 } else {
4603 zsl->tail = x->backward;
4604 }
4605 next = x->forward[0];
4606 dictDelete(dict,x->obj);
4607 zslFreeNode(x);
4608 while(zsl->level > 1 && zsl->header->forward[zsl->level-1] == NULL)
4609 zsl->level--;
4610 zsl->length--;
4611 removed++;
4612 x = next;
4613 }
4614 return removed; /* not found */
4615 }
4616
4617 /* Find the first node having a score equal or greater than the specified one.
4618 * Returns NULL if there is no match. */
4619 static zskiplistNode *zslFirstWithScore(zskiplist *zsl, double score) {
4620 zskiplistNode *x;
4621 int i;
4622
4623 x = zsl->header;
4624 for (i = zsl->level-1; i >= 0; i--) {
4625 while (x->forward[i] && x->forward[i]->score < score)
4626 x = x->forward[i];
4627 }
4628 /* We may have multiple elements with the same score, what we need
4629 * is to find the element with both the right score and object. */
4630 return x->forward[0];
4631 }
4632
4633 /* The actual Z-commands implementations */
4634
4635 /* This generic command implements both ZADD and ZINCRBY.
4636 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
4637 * the increment if the operation is a ZINCRBY (doincrement == 1). */
4638 static void zaddGenericCommand(redisClient *c, robj *key, robj *ele, double scoreval, int doincrement) {
4639 robj *zsetobj;
4640 zset *zs;
4641 double *score;
4642
4643 zsetobj = lookupKeyWrite(c->db,key);
4644 if (zsetobj == NULL) {
4645 zsetobj = createZsetObject();
4646 dictAdd(c->db->dict,key,zsetobj);
4647 incrRefCount(key);
4648 } else {
4649 if (zsetobj->type != REDIS_ZSET) {
4650 addReply(c,shared.wrongtypeerr);
4651 return;
4652 }
4653 }
4654 zs = zsetobj->ptr;
4655
4656 /* Ok now since we implement both ZADD and ZINCRBY here the code
4657 * needs to handle the two different conditions. It's all about setting
4658 * '*score', that is, the new score to set, to the right value. */
4659 score = zmalloc(sizeof(double));
4660 if (doincrement) {
4661 dictEntry *de;
4662
4663 /* Read the old score. If the element was not present starts from 0 */
4664 de = dictFind(zs->dict,ele);
4665 if (de) {
4666 double *oldscore = dictGetEntryVal(de);
4667 *score = *oldscore + scoreval;
4668 } else {
4669 *score = scoreval;
4670 }
4671 } else {
4672 *score = scoreval;
4673 }
4674
4675 /* What follows is a simple remove and re-insert operation that is common
4676 * to both ZADD and ZINCRBY... */
4677 if (dictAdd(zs->dict,ele,score) == DICT_OK) {
4678 /* case 1: New element */
4679 incrRefCount(ele); /* added to hash */
4680 zslInsert(zs->zsl,*score,ele);
4681 incrRefCount(ele); /* added to skiplist */
4682 server.dirty++;
4683 if (doincrement)
4684 addReplyDouble(c,*score);
4685 else
4686 addReply(c,shared.cone);
4687 } else {
4688 dictEntry *de;
4689 double *oldscore;
4690
4691 /* case 2: Score update operation */
4692 de = dictFind(zs->dict,ele);
4693 redisAssert(de != NULL);
4694 oldscore = dictGetEntryVal(de);
4695 if (*score != *oldscore) {
4696 int deleted;
4697
4698 /* Remove and insert the element in the skip list with new score */
4699 deleted = zslDelete(zs->zsl,*oldscore,ele);
4700 redisAssert(deleted != 0);
4701 zslInsert(zs->zsl,*score,ele);
4702 incrRefCount(ele);
4703 /* Update the score in the hash table */
4704 dictReplace(zs->dict,ele,score);
4705 server.dirty++;
4706 } else {
4707 zfree(score);
4708 }
4709 if (doincrement)
4710 addReplyDouble(c,*score);
4711 else
4712 addReply(c,shared.czero);
4713 }
4714 }
4715
4716 static void zaddCommand(redisClient *c) {
4717 double scoreval;
4718
4719 scoreval = strtod(c->argv[2]->ptr,NULL);
4720 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,0);
4721 }
4722
4723 static void zincrbyCommand(redisClient *c) {
4724 double scoreval;
4725
4726 scoreval = strtod(c->argv[2]->ptr,NULL);
4727 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,1);
4728 }
4729
4730 static void zremCommand(redisClient *c) {
4731 robj *zsetobj;
4732 zset *zs;
4733
4734 zsetobj = lookupKeyWrite(c->db,c->argv[1]);
4735 if (zsetobj == NULL) {
4736 addReply(c,shared.czero);
4737 } else {
4738 dictEntry *de;
4739 double *oldscore;
4740 int deleted;
4741
4742 if (zsetobj->type != REDIS_ZSET) {
4743 addReply(c,shared.wrongtypeerr);
4744 return;
4745 }
4746 zs = zsetobj->ptr;
4747 de = dictFind(zs->dict,c->argv[2]);
4748 if (de == NULL) {
4749 addReply(c,shared.czero);
4750 return;
4751 }
4752 /* Delete from the skiplist */
4753 oldscore = dictGetEntryVal(de);
4754 deleted = zslDelete(zs->zsl,*oldscore,c->argv[2]);
4755 redisAssert(deleted != 0);
4756
4757 /* Delete from the hash table */
4758 dictDelete(zs->dict,c->argv[2]);
4759 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
4760 server.dirty++;
4761 addReply(c,shared.cone);
4762 }
4763 }
4764
4765 static void zremrangebyscoreCommand(redisClient *c) {
4766 double min = strtod(c->argv[2]->ptr,NULL);
4767 double max = strtod(c->argv[3]->ptr,NULL);
4768 robj *zsetobj;
4769 zset *zs;
4770
4771 zsetobj = lookupKeyWrite(c->db,c->argv[1]);
4772 if (zsetobj == NULL) {
4773 addReply(c,shared.czero);
4774 } else {
4775 long deleted;
4776
4777 if (zsetobj->type != REDIS_ZSET) {
4778 addReply(c,shared.wrongtypeerr);
4779 return;
4780 }
4781 zs = zsetobj->ptr;
4782 deleted = zslDeleteRange(zs->zsl,min,max,zs->dict);
4783 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
4784 server.dirty += deleted;
4785 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",deleted));
4786 }
4787 }
4788
4789 static void zrangeGenericCommand(redisClient *c, int reverse) {
4790 robj *o;
4791 int start = atoi(c->argv[2]->ptr);
4792 int end = atoi(c->argv[3]->ptr);
4793 int withscores = 0;
4794
4795 if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) {
4796 withscores = 1;
4797 } else if (c->argc >= 5) {
4798 addReply(c,shared.syntaxerr);
4799 return;
4800 }
4801
4802 o = lookupKeyRead(c->db,c->argv[1]);
4803 if (o == NULL) {
4804 addReply(c,shared.nullmultibulk);
4805 } else {
4806 if (o->type != REDIS_ZSET) {
4807 addReply(c,shared.wrongtypeerr);
4808 } else {
4809 zset *zsetobj = o->ptr;
4810 zskiplist *zsl = zsetobj->zsl;
4811 zskiplistNode *ln;
4812
4813 int llen = zsl->length;
4814 int rangelen, j;
4815 robj *ele;
4816
4817 /* convert negative indexes */
4818 if (start < 0) start = llen+start;
4819 if (end < 0) end = llen+end;
4820 if (start < 0) start = 0;
4821 if (end < 0) end = 0;
4822
4823 /* indexes sanity checks */
4824 if (start > end || start >= llen) {
4825 /* Out of range start or start > end result in empty list */
4826 addReply(c,shared.emptymultibulk);
4827 return;
4828 }
4829 if (end >= llen) end = llen-1;
4830 rangelen = (end-start)+1;
4831
4832 /* Return the result in form of a multi-bulk reply */
4833 if (reverse) {
4834 ln = zsl->tail;
4835 while (start--)
4836 ln = ln->backward;
4837 } else {
4838 ln = zsl->header->forward[0];
4839 while (start--)
4840 ln = ln->forward[0];
4841 }
4842
4843 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",
4844 withscores ? (rangelen*2) : rangelen));
4845 for (j = 0; j < rangelen; j++) {
4846 ele = ln->obj;
4847 addReplyBulkLen(c,ele);
4848 addReply(c,ele);
4849 addReply(c,shared.crlf);
4850 if (withscores)
4851 addReplyDouble(c,ln->score);
4852 ln = reverse ? ln->backward : ln->forward[0];
4853 }
4854 }
4855 }
4856 }
4857
4858 static void zrangeCommand(redisClient *c) {
4859 zrangeGenericCommand(c,0);
4860 }
4861
4862 static void zrevrangeCommand(redisClient *c) {
4863 zrangeGenericCommand(c,1);
4864 }
4865
4866 static void zrangebyscoreCommand(redisClient *c) {
4867 robj *o;
4868 double min = strtod(c->argv[2]->ptr,NULL);
4869 double max = strtod(c->argv[3]->ptr,NULL);
4870 int offset = 0, limit = -1;
4871
4872 if (c->argc != 4 && c->argc != 7) {
4873 addReplySds(c,
4874 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
4875 return;
4876 } else if (c->argc == 7 && strcasecmp(c->argv[4]->ptr,"limit")) {
4877 addReply(c,shared.syntaxerr);
4878 return;
4879 } else if (c->argc == 7) {
4880 offset = atoi(c->argv[5]->ptr);
4881 limit = atoi(c->argv[6]->ptr);
4882 if (offset < 0) offset = 0;
4883 }
4884
4885 o = lookupKeyRead(c->db,c->argv[1]);
4886 if (o == NULL) {
4887 addReply(c,shared.nullmultibulk);
4888 } else {
4889 if (o->type != REDIS_ZSET) {
4890 addReply(c,shared.wrongtypeerr);
4891 } else {
4892 zset *zsetobj = o->ptr;
4893 zskiplist *zsl = zsetobj->zsl;
4894 zskiplistNode *ln;
4895 robj *ele, *lenobj;
4896 unsigned int rangelen = 0;
4897
4898 /* Get the first node with the score >= min */
4899 ln = zslFirstWithScore(zsl,min);
4900 if (ln == NULL) {
4901 /* No element matching the speciifed interval */
4902 addReply(c,shared.emptymultibulk);
4903 return;
4904 }
4905
4906 /* We don't know in advance how many matching elements there
4907 * are in the list, so we push this object that will represent
4908 * the multi-bulk length in the output buffer, and will "fix"
4909 * it later */
4910 lenobj = createObject(REDIS_STRING,NULL);
4911 addReply(c,lenobj);
4912 decrRefCount(lenobj);
4913
4914 while(ln && ln->score <= max) {
4915 if (offset) {
4916 offset--;
4917 ln = ln->forward[0];
4918 continue;
4919 }
4920 if (limit == 0) break;
4921 ele = ln->obj;
4922 addReplyBulkLen(c,ele);
4923 addReply(c,ele);
4924 addReply(c,shared.crlf);
4925 ln = ln->forward[0];
4926 rangelen++;
4927 if (limit > 0) limit--;
4928 }
4929 lenobj->ptr = sdscatprintf(sdsempty(),"*%d\r\n",rangelen);
4930 }
4931 }
4932 }
4933
4934 static void zcardCommand(redisClient *c) {
4935 robj *o;
4936 zset *zs;
4937
4938 o = lookupKeyRead(c->db,c->argv[1]);
4939 if (o == NULL) {
4940 addReply(c,shared.czero);
4941 return;
4942 } else {
4943 if (o->type != REDIS_ZSET) {
4944 addReply(c,shared.wrongtypeerr);
4945 } else {
4946 zs = o->ptr;
4947 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",zs->zsl->length));
4948 }
4949 }
4950 }
4951
4952 static void zscoreCommand(redisClient *c) {
4953 robj *o;
4954 zset *zs;
4955
4956 o = lookupKeyRead(c->db,c->argv[1]);
4957 if (o == NULL) {
4958 addReply(c,shared.nullbulk);
4959 return;
4960 } else {
4961 if (o->type != REDIS_ZSET) {
4962 addReply(c,shared.wrongtypeerr);
4963 } else {
4964 dictEntry *de;
4965
4966 zs = o->ptr;
4967 de = dictFind(zs->dict,c->argv[2]);
4968 if (!de) {
4969 addReply(c,shared.nullbulk);
4970 } else {
4971 double *score = dictGetEntryVal(de);
4972
4973 addReplyDouble(c,*score);
4974 }
4975 }
4976 }
4977 }
4978
4979 /* ========================= Non type-specific commands ==================== */
4980
4981 static void flushdbCommand(redisClient *c) {
4982 server.dirty += dictSize(c->db->dict);
4983 dictEmpty(c->db->dict);
4984 dictEmpty(c->db->expires);
4985 addReply(c,shared.ok);
4986 }
4987
4988 static void flushallCommand(redisClient *c) {
4989 server.dirty += emptyDb();
4990 addReply(c,shared.ok);
4991 rdbSave(server.dbfilename);
4992 server.dirty++;
4993 }
4994
4995 static redisSortOperation *createSortOperation(int type, robj *pattern) {
4996 redisSortOperation *so = zmalloc(sizeof(*so));
4997 so->type = type;
4998 so->pattern = pattern;
4999 return so;
5000 }
5001
5002 /* Return the value associated to the key with a name obtained
5003 * substituting the first occurence of '*' in 'pattern' with 'subst' */
5004 static robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst) {
5005 char *p;
5006 sds spat, ssub;
5007 robj keyobj;
5008 int prefixlen, sublen, postfixlen;
5009 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
5010 struct {
5011 long len;
5012 long free;
5013 char buf[REDIS_SORTKEY_MAX+1];
5014 } keyname;
5015
5016 /* If the pattern is "#" return the substitution object itself in order
5017 * to implement the "SORT ... GET #" feature. */
5018 spat = pattern->ptr;
5019 if (spat[0] == '#' && spat[1] == '\0') {
5020 return subst;
5021 }
5022
5023 /* The substitution object may be specially encoded. If so we create
5024 * a decoded object on the fly. Otherwise getDecodedObject will just
5025 * increment the ref count, that we'll decrement later. */
5026 subst = getDecodedObject(subst);
5027
5028 ssub = subst->ptr;
5029 if (sdslen(spat)+sdslen(ssub)-1 > REDIS_SORTKEY_MAX) return NULL;
5030 p = strchr(spat,'*');
5031 if (!p) {
5032 decrRefCount(subst);
5033 return NULL;
5034 }
5035
5036 prefixlen = p-spat;
5037 sublen = sdslen(ssub);
5038 postfixlen = sdslen(spat)-(prefixlen+1);
5039 memcpy(keyname.buf,spat,prefixlen);
5040 memcpy(keyname.buf+prefixlen,ssub,sublen);
5041 memcpy(keyname.buf+prefixlen+sublen,p+1,postfixlen);
5042 keyname.buf[prefixlen+sublen+postfixlen] = '\0';
5043 keyname.len = prefixlen+sublen+postfixlen;
5044
5045 initStaticStringObject(keyobj,((char*)&keyname)+(sizeof(long)*2))
5046 decrRefCount(subst);
5047
5048 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
5049 return lookupKeyRead(db,&keyobj);
5050 }
5051
5052 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
5053 * the additional parameter is not standard but a BSD-specific we have to
5054 * pass sorting parameters via the global 'server' structure */
5055 static int sortCompare(const void *s1, const void *s2) {
5056 const redisSortObject *so1 = s1, *so2 = s2;
5057 int cmp;
5058
5059 if (!server.sort_alpha) {
5060 /* Numeric sorting. Here it's trivial as we precomputed scores */
5061 if (so1->u.score > so2->u.score) {
5062 cmp = 1;
5063 } else if (so1->u.score < so2->u.score) {
5064 cmp = -1;
5065 } else {
5066 cmp = 0;
5067 }
5068 } else {
5069 /* Alphanumeric sorting */
5070 if (server.sort_bypattern) {
5071 if (!so1->u.cmpobj || !so2->u.cmpobj) {
5072 /* At least one compare object is NULL */
5073 if (so1->u.cmpobj == so2->u.cmpobj)
5074 cmp = 0;
5075 else if (so1->u.cmpobj == NULL)
5076 cmp = -1;
5077 else
5078 cmp = 1;
5079 } else {
5080 /* We have both the objects, use strcoll */
5081 cmp = strcoll(so1->u.cmpobj->ptr,so2->u.cmpobj->ptr);
5082 }
5083 } else {
5084 /* Compare elements directly */
5085 robj *dec1, *dec2;
5086
5087 dec1 = getDecodedObject(so1->obj);
5088 dec2 = getDecodedObject(so2->obj);
5089 cmp = strcoll(dec1->ptr,dec2->ptr);
5090 decrRefCount(dec1);
5091 decrRefCount(dec2);
5092 }
5093 }
5094 return server.sort_desc ? -cmp : cmp;
5095 }
5096
5097 /* The SORT command is the most complex command in Redis. Warning: this code
5098 * is optimized for speed and a bit less for readability */
5099 static void sortCommand(redisClient *c) {
5100 list *operations;
5101 int outputlen = 0;
5102 int desc = 0, alpha = 0;
5103 int limit_start = 0, limit_count = -1, start, end;
5104 int j, dontsort = 0, vectorlen;
5105 int getop = 0; /* GET operation counter */
5106 robj *sortval, *sortby = NULL, *storekey = NULL;
5107 redisSortObject *vector; /* Resulting vector to sort */
5108
5109 /* Lookup the key to sort. It must be of the right types */
5110 sortval = lookupKeyRead(c->db,c->argv[1]);
5111 if (sortval == NULL) {
5112 addReply(c,shared.nullmultibulk);
5113 return;
5114 }
5115 if (sortval->type != REDIS_SET && sortval->type != REDIS_LIST &&
5116 sortval->type != REDIS_ZSET)
5117 {
5118 addReply(c,shared.wrongtypeerr);
5119 return;
5120 }
5121
5122 /* Create a list of operations to perform for every sorted element.
5123 * Operations can be GET/DEL/INCR/DECR */
5124 operations = listCreate();
5125 listSetFreeMethod(operations,zfree);
5126 j = 2;
5127
5128 /* Now we need to protect sortval incrementing its count, in the future
5129 * SORT may have options able to overwrite/delete keys during the sorting
5130 * and the sorted key itself may get destroied */
5131 incrRefCount(sortval);
5132
5133 /* The SORT command has an SQL-alike syntax, parse it */
5134 while(j < c->argc) {
5135 int leftargs = c->argc-j-1;
5136 if (!strcasecmp(c->argv[j]->ptr,"asc")) {
5137 desc = 0;
5138 } else if (!strcasecmp(c->argv[j]->ptr,"desc")) {
5139 desc = 1;
5140 } else if (!strcasecmp(c->argv[j]->ptr,"alpha")) {
5141 alpha = 1;
5142 } else if (!strcasecmp(c->argv[j]->ptr,"limit") && leftargs >= 2) {
5143 limit_start = atoi(c->argv[j+1]->ptr);
5144 limit_count = atoi(c->argv[j+2]->ptr);
5145 j+=2;
5146 } else if (!strcasecmp(c->argv[j]->ptr,"store") && leftargs >= 1) {
5147 storekey = c->argv[j+1];
5148 j++;
5149 } else if (!strcasecmp(c->argv[j]->ptr,"by") && leftargs >= 1) {
5150 sortby = c->argv[j+1];
5151 /* If the BY pattern does not contain '*', i.e. it is constant,
5152 * we don't need to sort nor to lookup the weight keys. */
5153 if (strchr(c->argv[j+1]->ptr,'*') == NULL) dontsort = 1;
5154 j++;
5155 } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {
5156 listAddNodeTail(operations,createSortOperation(
5157 REDIS_SORT_GET,c->argv[j+1]));
5158 getop++;
5159 j++;
5160 } else {
5161 decrRefCount(sortval);
5162 listRelease(operations);
5163 addReply(c,shared.syntaxerr);
5164 return;
5165 }
5166 j++;
5167 }
5168
5169 /* Load the sorting vector with all the objects to sort */
5170 switch(sortval->type) {
5171 case REDIS_LIST: vectorlen = listLength((list*)sortval->ptr); break;
5172 case REDIS_SET: vectorlen = dictSize((dict*)sortval->ptr); break;
5173 case REDIS_ZSET: vectorlen = dictSize(((zset*)sortval->ptr)->dict); break;
5174 default: vectorlen = 0; redisAssert(0); /* Avoid GCC warning */
5175 }
5176 vector = zmalloc(sizeof(redisSortObject)*vectorlen);
5177 j = 0;
5178
5179 if (sortval->type == REDIS_LIST) {
5180 list *list = sortval->ptr;
5181 listNode *ln;
5182
5183 listRewind(list);
5184 while((ln = listYield(list))) {
5185 robj *ele = ln->value;
5186 vector[j].obj = ele;
5187 vector[j].u.score = 0;
5188 vector[j].u.cmpobj = NULL;
5189 j++;
5190 }
5191 } else {
5192 dict *set;
5193 dictIterator *di;
5194 dictEntry *setele;
5195
5196 if (sortval->type == REDIS_SET) {
5197 set = sortval->ptr;
5198 } else {
5199 zset *zs = sortval->ptr;
5200 set = zs->dict;
5201 }
5202
5203 di = dictGetIterator(set);
5204 while((setele = dictNext(di)) != NULL) {
5205 vector[j].obj = dictGetEntryKey(setele);
5206 vector[j].u.score = 0;
5207 vector[j].u.cmpobj = NULL;
5208 j++;
5209 }
5210 dictReleaseIterator(di);
5211 }
5212 redisAssert(j == vectorlen);
5213
5214 /* Now it's time to load the right scores in the sorting vector */
5215 if (dontsort == 0) {
5216 for (j = 0; j < vectorlen; j++) {
5217 if (sortby) {
5218 robj *byval;
5219
5220 byval = lookupKeyByPattern(c->db,sortby,vector[j].obj);
5221 if (!byval || byval->type != REDIS_STRING) continue;
5222 if (alpha) {
5223 vector[j].u.cmpobj = getDecodedObject(byval);
5224 } else {
5225 if (byval->encoding == REDIS_ENCODING_RAW) {
5226 vector[j].u.score = strtod(byval->ptr,NULL);
5227 } else {
5228 /* Don't need to decode the object if it's
5229 * integer-encoded (the only encoding supported) so
5230 * far. We can just cast it */
5231 if (byval->encoding == REDIS_ENCODING_INT) {
5232 vector[j].u.score = (long)byval->ptr;
5233 } else
5234 redisAssert(1 != 1);
5235 }
5236 }
5237 } else {
5238 if (!alpha) {
5239 if (vector[j].obj->encoding == REDIS_ENCODING_RAW)
5240 vector[j].u.score = strtod(vector[j].obj->ptr,NULL);
5241 else {
5242 if (vector[j].obj->encoding == REDIS_ENCODING_INT)
5243 vector[j].u.score = (long) vector[j].obj->ptr;
5244 else
5245 redisAssert(1 != 1);
5246 }
5247 }
5248 }
5249 }
5250 }
5251
5252 /* We are ready to sort the vector... perform a bit of sanity check
5253 * on the LIMIT option too. We'll use a partial version of quicksort. */
5254 start = (limit_start < 0) ? 0 : limit_start;
5255 end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1;
5256 if (start >= vectorlen) {
5257 start = vectorlen-1;
5258 end = vectorlen-2;
5259 }
5260 if (end >= vectorlen) end = vectorlen-1;
5261
5262 if (dontsort == 0) {
5263 server.sort_desc = desc;
5264 server.sort_alpha = alpha;
5265 server.sort_bypattern = sortby ? 1 : 0;
5266 if (sortby && (start != 0 || end != vectorlen-1))
5267 pqsort(vector,vectorlen,sizeof(redisSortObject),sortCompare, start,end);
5268 else
5269 qsort(vector,vectorlen,sizeof(redisSortObject),sortCompare);
5270 }
5271
5272 /* Send command output to the output buffer, performing the specified
5273 * GET/DEL/INCR/DECR operations if any. */
5274 outputlen = getop ? getop*(end-start+1) : end-start+1;
5275 if (storekey == NULL) {
5276 /* STORE option not specified, sent the sorting result to client */
5277 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",outputlen));
5278 for (j = start; j <= end; j++) {
5279 listNode *ln;
5280 if (!getop) {
5281 addReplyBulkLen(c,vector[j].obj);
5282 addReply(c,vector[j].obj);
5283 addReply(c,shared.crlf);
5284 }
5285 listRewind(operations);
5286 while((ln = listYield(operations))) {
5287 redisSortOperation *sop = ln->value;
5288 robj *val = lookupKeyByPattern(c->db,sop->pattern,
5289 vector[j].obj);
5290
5291 if (sop->type == REDIS_SORT_GET) {
5292 if (!val || val->type != REDIS_STRING) {
5293 addReply(c,shared.nullbulk);
5294 } else {
5295 addReplyBulkLen(c,val);
5296 addReply(c,val);
5297 addReply(c,shared.crlf);
5298 }
5299 } else {
5300 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
5301 }
5302 }
5303 }
5304 } else {
5305 robj *listObject = createListObject();
5306 list *listPtr = (list*) listObject->ptr;
5307
5308 /* STORE option specified, set the sorting result as a List object */
5309 for (j = start; j <= end; j++) {
5310 listNode *ln;
5311 if (!getop) {
5312 listAddNodeTail(listPtr,vector[j].obj);
5313 incrRefCount(vector[j].obj);
5314 }
5315 listRewind(operations);
5316 while((ln = listYield(operations))) {
5317 redisSortOperation *sop = ln->value;
5318 robj *val = lookupKeyByPattern(c->db,sop->pattern,
5319 vector[j].obj);
5320
5321 if (sop->type == REDIS_SORT_GET) {
5322 if (!val || val->type != REDIS_STRING) {
5323 listAddNodeTail(listPtr,createStringObject("",0));
5324 } else {
5325 listAddNodeTail(listPtr,val);
5326 incrRefCount(val);
5327 }
5328 } else {
5329 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
5330 }
5331 }
5332 }
5333 if (dictReplace(c->db->dict,storekey,listObject)) {
5334 incrRefCount(storekey);
5335 }
5336 /* Note: we add 1 because the DB is dirty anyway since even if the
5337 * SORT result is empty a new key is set and maybe the old content
5338 * replaced. */
5339 server.dirty += 1+outputlen;
5340 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",outputlen));
5341 }
5342
5343 /* Cleanup */
5344 decrRefCount(sortval);
5345 listRelease(operations);
5346 for (j = 0; j < vectorlen; j++) {
5347 if (sortby && alpha && vector[j].u.cmpobj)
5348 decrRefCount(vector[j].u.cmpobj);
5349 }
5350 zfree(vector);
5351 }
5352
5353 /* Create the string returned by the INFO command. This is decoupled
5354 * by the INFO command itself as we need to report the same information
5355 * on memory corruption problems. */
5356 static sds genRedisInfoString(void) {
5357 sds info;
5358 time_t uptime = time(NULL)-server.stat_starttime;
5359 int j;
5360
5361 info = sdscatprintf(sdsempty(),
5362 "redis_version:%s\r\n"
5363 "arch_bits:%s\r\n"
5364 "multiplexing_api:%s\r\n"
5365 "uptime_in_seconds:%ld\r\n"
5366 "uptime_in_days:%ld\r\n"
5367 "connected_clients:%d\r\n"
5368 "connected_slaves:%d\r\n"
5369 "blocked_clients:%d\r\n"
5370 "used_memory:%zu\r\n"
5371 "changes_since_last_save:%lld\r\n"
5372 "bgsave_in_progress:%d\r\n"
5373 "last_save_time:%ld\r\n"
5374 "bgrewriteaof_in_progress:%d\r\n"
5375 "total_connections_received:%lld\r\n"
5376 "total_commands_processed:%lld\r\n"
5377 "role:%s\r\n"
5378 ,REDIS_VERSION,
5379 (sizeof(long) == 8) ? "64" : "32",
5380 aeGetApiName(),
5381 uptime,
5382 uptime/(3600*24),
5383 listLength(server.clients)-listLength(server.slaves),
5384 listLength(server.slaves),
5385 server.blockedclients,
5386 server.usedmemory,
5387 server.dirty,
5388 server.bgsavechildpid != -1,
5389 server.lastsave,
5390 server.bgrewritechildpid != -1,
5391 server.stat_numconnections,
5392 server.stat_numcommands,
5393 server.masterhost == NULL ? "master" : "slave"
5394 );
5395 if (server.masterhost) {
5396 info = sdscatprintf(info,
5397 "master_host:%s\r\n"
5398 "master_port:%d\r\n"
5399 "master_link_status:%s\r\n"
5400 "master_last_io_seconds_ago:%d\r\n"
5401 ,server.masterhost,
5402 server.masterport,
5403 (server.replstate == REDIS_REPL_CONNECTED) ?
5404 "up" : "down",
5405 server.master ? ((int)(time(NULL)-server.master->lastinteraction)) : -1
5406 );
5407 }
5408 for (j = 0; j < server.dbnum; j++) {
5409 long long keys, vkeys;
5410
5411 keys = dictSize(server.db[j].dict);
5412 vkeys = dictSize(server.db[j].expires);
5413 if (keys || vkeys) {
5414 info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
5415 j, keys, vkeys);
5416 }
5417 }
5418 return info;
5419 }
5420
5421 static void infoCommand(redisClient *c) {
5422 sds info = genRedisInfoString();
5423 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
5424 (unsigned long)sdslen(info)));
5425 addReplySds(c,info);
5426 addReply(c,shared.crlf);
5427 }
5428
5429 static void monitorCommand(redisClient *c) {
5430 /* ignore MONITOR if aleady slave or in monitor mode */
5431 if (c->flags & REDIS_SLAVE) return;
5432
5433 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
5434 c->slaveseldb = 0;
5435 listAddNodeTail(server.monitors,c);
5436 addReply(c,shared.ok);
5437 }
5438
5439 /* ================================= Expire ================================= */
5440 static int removeExpire(redisDb *db, robj *key) {
5441 if (dictDelete(db->expires,key) == DICT_OK) {
5442 return 1;
5443 } else {
5444 return 0;
5445 }
5446 }
5447
5448 static int setExpire(redisDb *db, robj *key, time_t when) {
5449 if (dictAdd(db->expires,key,(void*)when) == DICT_ERR) {
5450 return 0;
5451 } else {
5452 incrRefCount(key);
5453 return 1;
5454 }
5455 }
5456
5457 /* Return the expire time of the specified key, or -1 if no expire
5458 * is associated with this key (i.e. the key is non volatile) */
5459 static time_t getExpire(redisDb *db, robj *key) {
5460 dictEntry *de;
5461
5462 /* No expire? return ASAP */
5463 if (dictSize(db->expires) == 0 ||
5464 (de = dictFind(db->expires,key)) == NULL) return -1;
5465
5466 return (time_t) dictGetEntryVal(de);
5467 }
5468
5469 static int expireIfNeeded(redisDb *db, robj *key) {
5470 time_t when;
5471 dictEntry *de;
5472
5473 /* No expire? return ASAP */
5474 if (dictSize(db->expires) == 0 ||
5475 (de = dictFind(db->expires,key)) == NULL) return 0;
5476
5477 /* Lookup the expire */
5478 when = (time_t) dictGetEntryVal(de);
5479 if (time(NULL) <= when) return 0;
5480
5481 /* Delete the key */
5482 dictDelete(db->expires,key);
5483 return dictDelete(db->dict,key) == DICT_OK;
5484 }
5485
5486 static int deleteIfVolatile(redisDb *db, robj *key) {
5487 dictEntry *de;
5488
5489 /* No expire? return ASAP */
5490 if (dictSize(db->expires) == 0 ||
5491 (de = dictFind(db->expires,key)) == NULL) return 0;
5492
5493 /* Delete the key */
5494 server.dirty++;
5495 dictDelete(db->expires,key);
5496 return dictDelete(db->dict,key) == DICT_OK;
5497 }
5498
5499 static void expireGenericCommand(redisClient *c, robj *key, time_t seconds) {
5500 dictEntry *de;
5501
5502 de = dictFind(c->db->dict,key);
5503 if (de == NULL) {
5504 addReply(c,shared.czero);
5505 return;
5506 }
5507 if (seconds < 0) {
5508 if (deleteKey(c->db,key)) server.dirty++;
5509 addReply(c, shared.cone);
5510 return;
5511 } else {
5512 time_t when = time(NULL)+seconds;
5513 if (setExpire(c->db,key,when)) {
5514 addReply(c,shared.cone);
5515 server.dirty++;
5516 } else {
5517 addReply(c,shared.czero);
5518 }
5519 return;
5520 }
5521 }
5522
5523 static void expireCommand(redisClient *c) {
5524 expireGenericCommand(c,c->argv[1],strtol(c->argv[2]->ptr,NULL,10));
5525 }
5526
5527 static void expireatCommand(redisClient *c) {
5528 expireGenericCommand(c,c->argv[1],strtol(c->argv[2]->ptr,NULL,10)-time(NULL));
5529 }
5530
5531 static void ttlCommand(redisClient *c) {
5532 time_t expire;
5533 int ttl = -1;
5534
5535 expire = getExpire(c->db,c->argv[1]);
5536 if (expire != -1) {
5537 ttl = (int) (expire-time(NULL));
5538 if (ttl < 0) ttl = -1;
5539 }
5540 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",ttl));
5541 }
5542
5543 /* ================================ MULTI/EXEC ============================== */
5544
5545 /* Client state initialization for MULTI/EXEC */
5546 static void initClientMultiState(redisClient *c) {
5547 c->mstate.commands = NULL;
5548 c->mstate.count = 0;
5549 }
5550
5551 /* Release all the resources associated with MULTI/EXEC state */
5552 static void freeClientMultiState(redisClient *c) {
5553 int j;
5554
5555 for (j = 0; j < c->mstate.count; j++) {
5556 int i;
5557 multiCmd *mc = c->mstate.commands+j;
5558
5559 for (i = 0; i < mc->argc; i++)
5560 decrRefCount(mc->argv[i]);
5561 zfree(mc->argv);
5562 }
5563 zfree(c->mstate.commands);
5564 }
5565
5566 /* Add a new command into the MULTI commands queue */
5567 static void queueMultiCommand(redisClient *c, struct redisCommand *cmd) {
5568 multiCmd *mc;
5569 int j;
5570
5571 c->mstate.commands = zrealloc(c->mstate.commands,
5572 sizeof(multiCmd)*(c->mstate.count+1));
5573 mc = c->mstate.commands+c->mstate.count;
5574 mc->cmd = cmd;
5575 mc->argc = c->argc;
5576 mc->argv = zmalloc(sizeof(robj*)*c->argc);
5577 memcpy(mc->argv,c->argv,sizeof(robj*)*c->argc);
5578 for (j = 0; j < c->argc; j++)
5579 incrRefCount(mc->argv[j]);
5580 c->mstate.count++;
5581 }
5582
5583 static void multiCommand(redisClient *c) {
5584 c->flags |= REDIS_MULTI;
5585 addReply(c,shared.ok);
5586 }
5587
5588 static void execCommand(redisClient *c) {
5589 int j;
5590 robj **orig_argv;
5591 int orig_argc;
5592
5593 if (!(c->flags & REDIS_MULTI)) {
5594 addReplySds(c,sdsnew("-ERR EXEC without MULTI\r\n"));
5595 return;
5596 }
5597
5598 orig_argv = c->argv;
5599 orig_argc = c->argc;
5600 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->mstate.count));
5601 for (j = 0; j < c->mstate.count; j++) {
5602 c->argc = c->mstate.commands[j].argc;
5603 c->argv = c->mstate.commands[j].argv;
5604 call(c,c->mstate.commands[j].cmd);
5605 }
5606 c->argv = orig_argv;
5607 c->argc = orig_argc;
5608 freeClientMultiState(c);
5609 initClientMultiState(c);
5610 c->flags &= (~REDIS_MULTI);
5611 }
5612
5613 /* =========================== Blocking Operations ========================= */
5614
5615 /* Currently Redis blocking operations support is limited to list POP ops,
5616 * so the current implementation is not fully generic, but it is also not
5617 * completely specific so it will not require a rewrite to support new
5618 * kind of blocking operations in the future.
5619 *
5620 * Still it's important to note that list blocking operations can be already
5621 * used as a notification mechanism in order to implement other blocking
5622 * operations at application level, so there must be a very strong evidence
5623 * of usefulness and generality before new blocking operations are implemented.
5624 *
5625 * This is how the current blocking POP works, we use BLPOP as example:
5626 * - If the user calls BLPOP and the key exists and contains a non empty list
5627 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
5628 * if there is not to block.
5629 * - If instead BLPOP is called and the key does not exists or the list is
5630 * empty we need to block. In order to do so we remove the notification for
5631 * new data to read in the client socket (so that we'll not serve new
5632 * requests if the blocking request is not served). Also we put the client
5633 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
5634 * blocking for this keys.
5635 * - If a PUSH operation against a key with blocked clients waiting is
5636 * performed, we serve the first in the list: basically instead to push
5637 * the new element inside the list we return it to the (first / oldest)
5638 * blocking client, unblock the client, and remove it form the list.
5639 *
5640 * The above comment and the source code should be enough in order to understand
5641 * the implementation and modify / fix it later.
5642 */
5643
5644 /* Set a client in blocking mode for the specified key, with the specified
5645 * timeout */
5646 static void blockForKeys(redisClient *c, robj **keys, int numkeys, time_t timeout) {
5647 dictEntry *de;
5648 list *l;
5649 int j;
5650
5651 c->blockingkeys = zmalloc(sizeof(robj*)*numkeys);
5652 c->blockingkeysnum = numkeys;
5653 c->blockingto = timeout;
5654 for (j = 0; j < numkeys; j++) {
5655 /* Add the key in the client structure, to map clients -> keys */
5656 c->blockingkeys[j] = keys[j];
5657 incrRefCount(keys[j]);
5658
5659 /* And in the other "side", to map keys -> clients */
5660 de = dictFind(c->db->blockingkeys,keys[j]);
5661 if (de == NULL) {
5662 int retval;
5663
5664 /* For every key we take a list of clients blocked for it */
5665 l = listCreate();
5666 retval = dictAdd(c->db->blockingkeys,keys[j],l);
5667 incrRefCount(keys[j]);
5668 assert(retval == DICT_OK);
5669 } else {
5670 l = dictGetEntryVal(de);
5671 }
5672 listAddNodeTail(l,c);
5673 }
5674 /* Mark the client as a blocked client */
5675 c->flags |= REDIS_BLOCKED;
5676 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
5677 server.blockedclients++;
5678 }
5679
5680 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
5681 static void unblockClient(redisClient *c) {
5682 dictEntry *de;
5683 list *l;
5684 int j;
5685
5686 assert(c->blockingkeys != NULL);
5687 /* The client may wait for multiple keys, so unblock it for every key. */
5688 for (j = 0; j < c->blockingkeysnum; j++) {
5689 /* Remove this client from the list of clients waiting for this key. */
5690 de = dictFind(c->db->blockingkeys,c->blockingkeys[j]);
5691 assert(de != NULL);
5692 l = dictGetEntryVal(de);
5693 listDelNode(l,listSearchKey(l,c));
5694 /* If the list is empty we need to remove it to avoid wasting memory */
5695 if (listLength(l) == 0)
5696 dictDelete(c->db->blockingkeys,c->blockingkeys[j]);
5697 decrRefCount(c->blockingkeys[j]);
5698 }
5699 /* Cleanup the client structure */
5700 zfree(c->blockingkeys);
5701 c->blockingkeys = NULL;
5702 c->flags &= (~REDIS_BLOCKED);
5703 server.blockedclients--;
5704 /* Ok now we are ready to get read events from socket, note that we
5705 * can't trap errors here as it's possible that unblockClients() is
5706 * called from freeClient() itself, and the only thing we can do
5707 * if we failed to register the READABLE event is to kill the client.
5708 * Still the following function should never fail in the real world as
5709 * we are sure the file descriptor is sane, and we exit on out of mem. */
5710 aeCreateFileEvent(server.el, c->fd, AE_READABLE, readQueryFromClient, c);
5711 /* As a final step we want to process data if there is some command waiting
5712 * in the input buffer. Note that this is safe even if unblockClient()
5713 * gets called from freeClient() because freeClient() will be smart
5714 * enough to call this function *after* c->querybuf was set to NULL. */
5715 if (c->querybuf && sdslen(c->querybuf) > 0) processInputBuffer(c);
5716 }
5717
5718 /* This should be called from any function PUSHing into lists.
5719 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
5720 * 'ele' is the element pushed.
5721 *
5722 * If the function returns 0 there was no client waiting for a list push
5723 * against this key.
5724 *
5725 * If the function returns 1 there was a client waiting for a list push
5726 * against this key, the element was passed to this client thus it's not
5727 * needed to actually add it to the list and the caller should return asap. */
5728 static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele) {
5729 struct dictEntry *de;
5730 redisClient *receiver;
5731 list *l;
5732 listNode *ln;
5733
5734 de = dictFind(c->db->blockingkeys,key);
5735 if (de == NULL) return 0;
5736 l = dictGetEntryVal(de);
5737 ln = listFirst(l);
5738 assert(ln != NULL);
5739 receiver = ln->value;
5740
5741 addReplySds(receiver,sdsnew("*2\r\n"));
5742 addReplyBulkLen(receiver,key);
5743 addReply(receiver,key);
5744 addReply(receiver,shared.crlf);
5745 addReplyBulkLen(receiver,ele);
5746 addReply(receiver,ele);
5747 addReply(receiver,shared.crlf);
5748 unblockClient(receiver);
5749 return 1;
5750 }
5751
5752 /* Blocking RPOP/LPOP */
5753 static void blockingPopGenericCommand(redisClient *c, int where) {
5754 robj *o;
5755 time_t timeout;
5756 int j;
5757
5758 for (j = 1; j < c->argc-1; j++) {
5759 o = lookupKeyWrite(c->db,c->argv[j]);
5760 if (o != NULL) {
5761 if (o->type != REDIS_LIST) {
5762 addReply(c,shared.wrongtypeerr);
5763 return;
5764 } else {
5765 list *list = o->ptr;
5766 if (listLength(list) != 0) {
5767 /* If the list contains elements fall back to the usual
5768 * non-blocking POP operation */
5769 robj *argv[2], **orig_argv;
5770 int orig_argc;
5771
5772 /* We need to alter the command arguments before to call
5773 * popGenericCommand() as the command takes a single key. */
5774 orig_argv = c->argv;
5775 orig_argc = c->argc;
5776 argv[1] = c->argv[j];
5777 c->argv = argv;
5778 c->argc = 2;
5779
5780 /* Also the return value is different, we need to output
5781 * the multi bulk reply header and the key name. The
5782 * "real" command will add the last element (the value)
5783 * for us. If this souds like an hack to you it's just
5784 * because it is... */
5785 addReplySds(c,sdsnew("*2\r\n"));
5786 addReplyBulkLen(c,argv[1]);
5787 addReply(c,argv[1]);
5788 addReply(c,shared.crlf);
5789 popGenericCommand(c,where);
5790
5791 /* Fix the client structure with the original stuff */
5792 c->argv = orig_argv;
5793 c->argc = orig_argc;
5794 return;
5795 }
5796 }
5797 }
5798 }
5799 /* If the list is empty or the key does not exists we must block */
5800 timeout = strtol(c->argv[c->argc-1]->ptr,NULL,10);
5801 if (timeout > 0) timeout += time(NULL);
5802 blockForKeys(c,c->argv+1,c->argc-2,timeout);
5803 }
5804
5805 static void blpopCommand(redisClient *c) {
5806 blockingPopGenericCommand(c,REDIS_HEAD);
5807 }
5808
5809 static void brpopCommand(redisClient *c) {
5810 blockingPopGenericCommand(c,REDIS_TAIL);
5811 }
5812
5813 /* =============================== Replication ============================= */
5814
5815 static int syncWrite(int fd, char *ptr, ssize_t size, int timeout) {
5816 ssize_t nwritten, ret = size;
5817 time_t start = time(NULL);
5818
5819 timeout++;
5820 while(size) {
5821 if (aeWait(fd,AE_WRITABLE,1000) & AE_WRITABLE) {
5822 nwritten = write(fd,ptr,size);
5823 if (nwritten == -1) return -1;
5824 ptr += nwritten;
5825 size -= nwritten;
5826 }
5827 if ((time(NULL)-start) > timeout) {
5828 errno = ETIMEDOUT;
5829 return -1;
5830 }
5831 }
5832 return ret;
5833 }
5834
5835 static int syncRead(int fd, char *ptr, ssize_t size, int timeout) {
5836 ssize_t nread, totread = 0;
5837 time_t start = time(NULL);
5838
5839 timeout++;
5840 while(size) {
5841 if (aeWait(fd,AE_READABLE,1000) & AE_READABLE) {
5842 nread = read(fd,ptr,size);
5843 if (nread == -1) return -1;
5844 ptr += nread;
5845 size -= nread;
5846 totread += nread;
5847 }
5848 if ((time(NULL)-start) > timeout) {
5849 errno = ETIMEDOUT;
5850 return -1;
5851 }
5852 }
5853 return totread;
5854 }
5855
5856 static int syncReadLine(int fd, char *ptr, ssize_t size, int timeout) {
5857 ssize_t nread = 0;
5858
5859 size--;
5860 while(size) {
5861 char c;
5862
5863 if (syncRead(fd,&c,1,timeout) == -1) return -1;
5864 if (c == '\n') {
5865 *ptr = '\0';
5866 if (nread && *(ptr-1) == '\r') *(ptr-1) = '\0';
5867 return nread;
5868 } else {
5869 *ptr++ = c;
5870 *ptr = '\0';
5871 nread++;
5872 }
5873 }
5874 return nread;
5875 }
5876
5877 static void syncCommand(redisClient *c) {
5878 /* ignore SYNC if aleady slave or in monitor mode */
5879 if (c->flags & REDIS_SLAVE) return;
5880
5881 /* SYNC can't be issued when the server has pending data to send to
5882 * the client about already issued commands. We need a fresh reply
5883 * buffer registering the differences between the BGSAVE and the current
5884 * dataset, so that we can copy to other slaves if needed. */
5885 if (listLength(c->reply) != 0) {
5886 addReplySds(c,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
5887 return;
5888 }
5889
5890 redisLog(REDIS_NOTICE,"Slave ask for synchronization");
5891 /* Here we need to check if there is a background saving operation
5892 * in progress, or if it is required to start one */
5893 if (server.bgsavechildpid != -1) {
5894 /* Ok a background save is in progress. Let's check if it is a good
5895 * one for replication, i.e. if there is another slave that is
5896 * registering differences since the server forked to save */
5897 redisClient *slave;
5898 listNode *ln;
5899
5900 listRewind(server.slaves);
5901 while((ln = listYield(server.slaves))) {
5902 slave = ln->value;
5903 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) break;
5904 }
5905 if (ln) {
5906 /* Perfect, the server is already registering differences for
5907 * another slave. Set the right state, and copy the buffer. */
5908 listRelease(c->reply);
5909 c->reply = listDup(slave->reply);
5910 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
5911 redisLog(REDIS_NOTICE,"Waiting for end of BGSAVE for SYNC");
5912 } else {
5913 /* No way, we need to wait for the next BGSAVE in order to
5914 * register differences */
5915 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
5916 redisLog(REDIS_NOTICE,"Waiting for next BGSAVE for SYNC");
5917 }
5918 } else {
5919 /* Ok we don't have a BGSAVE in progress, let's start one */
5920 redisLog(REDIS_NOTICE,"Starting BGSAVE for SYNC");
5921 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
5922 redisLog(REDIS_NOTICE,"Replication failed, can't BGSAVE");
5923 addReplySds(c,sdsnew("-ERR Unalbe to perform background save\r\n"));
5924 return;
5925 }
5926 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
5927 }
5928 c->repldbfd = -1;
5929 c->flags |= REDIS_SLAVE;
5930 c->slaveseldb = 0;
5931 listAddNodeTail(server.slaves,c);
5932 return;
5933 }
5934
5935 static void sendBulkToSlave(aeEventLoop *el, int fd, void *privdata, int mask) {
5936 redisClient *slave = privdata;
5937 REDIS_NOTUSED(el);
5938 REDIS_NOTUSED(mask);
5939 char buf[REDIS_IOBUF_LEN];
5940 ssize_t nwritten, buflen;
5941
5942 if (slave->repldboff == 0) {
5943 /* Write the bulk write count before to transfer the DB. In theory here
5944 * we don't know how much room there is in the output buffer of the
5945 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
5946 * operations) will never be smaller than the few bytes we need. */
5947 sds bulkcount;
5948
5949 bulkcount = sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
5950 slave->repldbsize);
5951 if (write(fd,bulkcount,sdslen(bulkcount)) != (signed)sdslen(bulkcount))
5952 {
5953 sdsfree(bulkcount);
5954 freeClient(slave);
5955 return;
5956 }
5957 sdsfree(bulkcount);
5958 }
5959 lseek(slave->repldbfd,slave->repldboff,SEEK_SET);
5960 buflen = read(slave->repldbfd,buf,REDIS_IOBUF_LEN);
5961 if (buflen <= 0) {
5962 redisLog(REDIS_WARNING,"Read error sending DB to slave: %s",
5963 (buflen == 0) ? "premature EOF" : strerror(errno));
5964 freeClient(slave);
5965 return;
5966 }
5967 if ((nwritten = write(fd,buf,buflen)) == -1) {
5968 redisLog(REDIS_DEBUG,"Write error sending DB to slave: %s",
5969 strerror(errno));
5970 freeClient(slave);
5971 return;
5972 }
5973 slave->repldboff += nwritten;
5974 if (slave->repldboff == slave->repldbsize) {
5975 close(slave->repldbfd);
5976 slave->repldbfd = -1;
5977 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
5978 slave->replstate = REDIS_REPL_ONLINE;
5979 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE,
5980 sendReplyToClient, slave) == AE_ERR) {
5981 freeClient(slave);
5982 return;
5983 }
5984 addReplySds(slave,sdsempty());
5985 redisLog(REDIS_NOTICE,"Synchronization with slave succeeded");
5986 }
5987 }
5988
5989 /* This function is called at the end of every backgrond saving.
5990 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
5991 * otherwise REDIS_ERR is passed to the function.
5992 *
5993 * The goal of this function is to handle slaves waiting for a successful
5994 * background saving in order to perform non-blocking synchronization. */
5995 static void updateSlavesWaitingBgsave(int bgsaveerr) {
5996 listNode *ln;
5997 int startbgsave = 0;
5998
5999 listRewind(server.slaves);
6000 while((ln = listYield(server.slaves))) {
6001 redisClient *slave = ln->value;
6002
6003 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) {
6004 startbgsave = 1;
6005 slave->replstate = REDIS_REPL_WAIT_BGSAVE_END;
6006 } else if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) {
6007 struct redis_stat buf;
6008
6009 if (bgsaveerr != REDIS_OK) {
6010 freeClient(slave);
6011 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE child returned an error");
6012 continue;
6013 }
6014 if ((slave->repldbfd = open(server.dbfilename,O_RDONLY)) == -1 ||
6015 redis_fstat(slave->repldbfd,&buf) == -1) {
6016 freeClient(slave);
6017 redisLog(REDIS_WARNING,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno));
6018 continue;
6019 }
6020 slave->repldboff = 0;
6021 slave->repldbsize = buf.st_size;
6022 slave->replstate = REDIS_REPL_SEND_BULK;
6023 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
6024 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE, sendBulkToSlave, slave) == AE_ERR) {
6025 freeClient(slave);
6026 continue;
6027 }
6028 }
6029 }
6030 if (startbgsave) {
6031 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
6032 listRewind(server.slaves);
6033 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE failed");
6034 while((ln = listYield(server.slaves))) {
6035 redisClient *slave = ln->value;
6036
6037 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START)
6038 freeClient(slave);
6039 }
6040 }
6041 }
6042 }
6043
6044 static int syncWithMaster(void) {
6045 char buf[1024], tmpfile[256], authcmd[1024];
6046 int dumpsize;
6047 int fd = anetTcpConnect(NULL,server.masterhost,server.masterport);
6048 int dfd;
6049
6050 if (fd == -1) {
6051 redisLog(REDIS_WARNING,"Unable to connect to MASTER: %s",
6052 strerror(errno));
6053 return REDIS_ERR;
6054 }
6055
6056 /* AUTH with the master if required. */
6057 if(server.masterauth) {
6058 snprintf(authcmd, 1024, "AUTH %s\r\n", server.masterauth);
6059 if (syncWrite(fd, authcmd, strlen(server.masterauth)+7, 5) == -1) {
6060 close(fd);
6061 redisLog(REDIS_WARNING,"Unable to AUTH to MASTER: %s",
6062 strerror(errno));
6063 return REDIS_ERR;
6064 }
6065 /* Read the AUTH result. */
6066 if (syncReadLine(fd,buf,1024,3600) == -1) {
6067 close(fd);
6068 redisLog(REDIS_WARNING,"I/O error reading auth result from MASTER: %s",
6069 strerror(errno));
6070 return REDIS_ERR;
6071 }
6072 if (buf[0] != '+') {
6073 close(fd);
6074 redisLog(REDIS_WARNING,"Cannot AUTH to MASTER, is the masterauth password correct?");
6075 return REDIS_ERR;
6076 }
6077 }
6078
6079 /* Issue the SYNC command */
6080 if (syncWrite(fd,"SYNC \r\n",7,5) == -1) {
6081 close(fd);
6082 redisLog(REDIS_WARNING,"I/O error writing to MASTER: %s",
6083 strerror(errno));
6084 return REDIS_ERR;
6085 }
6086 /* Read the bulk write count */
6087 if (syncReadLine(fd,buf,1024,3600) == -1) {
6088 close(fd);
6089 redisLog(REDIS_WARNING,"I/O error reading bulk count from MASTER: %s",
6090 strerror(errno));
6091 return REDIS_ERR;
6092 }
6093 if (buf[0] != '$') {
6094 close(fd);
6095 redisLog(REDIS_WARNING,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
6096 return REDIS_ERR;
6097 }
6098 dumpsize = atoi(buf+1);
6099 redisLog(REDIS_NOTICE,"Receiving %d bytes data dump from MASTER",dumpsize);
6100 /* Read the bulk write data on a temp file */
6101 snprintf(tmpfile,256,"temp-%d.%ld.rdb",(int)time(NULL),(long int)random());
6102 dfd = open(tmpfile,O_CREAT|O_WRONLY,0644);
6103 if (dfd == -1) {
6104 close(fd);
6105 redisLog(REDIS_WARNING,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno));
6106 return REDIS_ERR;
6107 }
6108 while(dumpsize) {
6109 int nread, nwritten;
6110
6111 nread = read(fd,buf,(dumpsize < 1024)?dumpsize:1024);
6112 if (nread == -1) {
6113 redisLog(REDIS_WARNING,"I/O error trying to sync with MASTER: %s",
6114 strerror(errno));
6115 close(fd);
6116 close(dfd);
6117 return REDIS_ERR;
6118 }
6119 nwritten = write(dfd,buf,nread);
6120 if (nwritten == -1) {
6121 redisLog(REDIS_WARNING,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno));
6122 close(fd);
6123 close(dfd);
6124 return REDIS_ERR;
6125 }
6126 dumpsize -= nread;
6127 }
6128 close(dfd);
6129 if (rename(tmpfile,server.dbfilename) == -1) {
6130 redisLog(REDIS_WARNING,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno));
6131 unlink(tmpfile);
6132 close(fd);
6133 return REDIS_ERR;
6134 }
6135 emptyDb();
6136 if (rdbLoad(server.dbfilename) != REDIS_OK) {
6137 redisLog(REDIS_WARNING,"Failed trying to load the MASTER synchronization DB from disk");
6138 close(fd);
6139 return REDIS_ERR;
6140 }
6141 server.master = createClient(fd);
6142 server.master->flags |= REDIS_MASTER;
6143 server.master->authenticated = 1;
6144 server.replstate = REDIS_REPL_CONNECTED;
6145 return REDIS_OK;
6146 }
6147
6148 static void slaveofCommand(redisClient *c) {
6149 if (!strcasecmp(c->argv[1]->ptr,"no") &&
6150 !strcasecmp(c->argv[2]->ptr,"one")) {
6151 if (server.masterhost) {
6152 sdsfree(server.masterhost);
6153 server.masterhost = NULL;
6154 if (server.master) freeClient(server.master);
6155 server.replstate = REDIS_REPL_NONE;
6156 redisLog(REDIS_NOTICE,"MASTER MODE enabled (user request)");
6157 }
6158 } else {
6159 sdsfree(server.masterhost);
6160 server.masterhost = sdsdup(c->argv[1]->ptr);
6161 server.masterport = atoi(c->argv[2]->ptr);
6162 if (server.master) freeClient(server.master);
6163 server.replstate = REDIS_REPL_CONNECT;
6164 redisLog(REDIS_NOTICE,"SLAVE OF %s:%d enabled (user request)",
6165 server.masterhost, server.masterport);
6166 }
6167 addReply(c,shared.ok);
6168 }
6169
6170 /* ============================ Maxmemory directive ======================== */
6171
6172 /* This function gets called when 'maxmemory' is set on the config file to limit
6173 * the max memory used by the server, and we are out of memory.
6174 * This function will try to, in order:
6175 *
6176 * - Free objects from the free list
6177 * - Try to remove keys with an EXPIRE set
6178 *
6179 * It is not possible to free enough memory to reach used-memory < maxmemory
6180 * the server will start refusing commands that will enlarge even more the
6181 * memory usage.
6182 */
6183 static void freeMemoryIfNeeded(void) {
6184 while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
6185 if (listLength(server.objfreelist)) {
6186 robj *o;
6187
6188 listNode *head = listFirst(server.objfreelist);
6189 o = listNodeValue(head);
6190 listDelNode(server.objfreelist,head);
6191 zfree(o);
6192 } else {
6193 int j, k, freed = 0;
6194
6195 for (j = 0; j < server.dbnum; j++) {
6196 int minttl = -1;
6197 robj *minkey = NULL;
6198 struct dictEntry *de;
6199
6200 if (dictSize(server.db[j].expires)) {
6201 freed = 1;
6202 /* From a sample of three keys drop the one nearest to
6203 * the natural expire */
6204 for (k = 0; k < 3; k++) {
6205 time_t t;
6206
6207 de = dictGetRandomKey(server.db[j].expires);
6208 t = (time_t) dictGetEntryVal(de);
6209 if (minttl == -1 || t < minttl) {
6210 minkey = dictGetEntryKey(de);
6211 minttl = t;
6212 }
6213 }
6214 deleteKey(server.db+j,minkey);
6215 }
6216 }
6217 if (!freed) return; /* nothing to free... */
6218 }
6219 }
6220 }
6221
6222 /* ============================== Append Only file ========================== */
6223
6224 static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
6225 sds buf = sdsempty();
6226 int j;
6227 ssize_t nwritten;
6228 time_t now;
6229 robj *tmpargv[3];
6230
6231 /* The DB this command was targetting is not the same as the last command
6232 * we appendend. To issue a SELECT command is needed. */
6233 if (dictid != server.appendseldb) {
6234 char seldb[64];
6235
6236 snprintf(seldb,sizeof(seldb),"%d",dictid);
6237 buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
6238 (unsigned long)strlen(seldb),seldb);
6239 server.appendseldb = dictid;
6240 }
6241
6242 /* "Fix" the argv vector if the command is EXPIRE. We want to translate
6243 * EXPIREs into EXPIREATs calls */
6244 if (cmd->proc == expireCommand) {
6245 long when;
6246
6247 tmpargv[0] = createStringObject("EXPIREAT",8);
6248 tmpargv[1] = argv[1];
6249 incrRefCount(argv[1]);
6250 when = time(NULL)+strtol(argv[2]->ptr,NULL,10);
6251 tmpargv[2] = createObject(REDIS_STRING,
6252 sdscatprintf(sdsempty(),"%ld",when));
6253 argv = tmpargv;
6254 }
6255
6256 /* Append the actual command */
6257 buf = sdscatprintf(buf,"*%d\r\n",argc);
6258 for (j = 0; j < argc; j++) {
6259 robj *o = argv[j];
6260
6261 o = getDecodedObject(o);
6262 buf = sdscatprintf(buf,"$%lu\r\n",(unsigned long)sdslen(o->ptr));
6263 buf = sdscatlen(buf,o->ptr,sdslen(o->ptr));
6264 buf = sdscatlen(buf,"\r\n",2);
6265 decrRefCount(o);
6266 }
6267
6268 /* Free the objects from the modified argv for EXPIREAT */
6269 if (cmd->proc == expireCommand) {
6270 for (j = 0; j < 3; j++)
6271 decrRefCount(argv[j]);
6272 }
6273
6274 /* We want to perform a single write. This should be guaranteed atomic
6275 * at least if the filesystem we are writing is a real physical one.
6276 * While this will save us against the server being killed I don't think
6277 * there is much to do about the whole server stopping for power problems
6278 * or alike */
6279 nwritten = write(server.appendfd,buf,sdslen(buf));
6280 if (nwritten != (signed)sdslen(buf)) {
6281 /* Ooops, we are in troubles. The best thing to do for now is
6282 * to simply exit instead to give the illusion that everything is
6283 * working as expected. */
6284 if (nwritten == -1) {
6285 redisLog(REDIS_WARNING,"Exiting on error writing to the append-only file: %s",strerror(errno));
6286 } else {
6287 redisLog(REDIS_WARNING,"Exiting on short write while writing to the append-only file: %s",strerror(errno));
6288 }
6289 exit(1);
6290 }
6291 /* If a background append only file rewriting is in progress we want to
6292 * accumulate the differences between the child DB and the current one
6293 * in a buffer, so that when the child process will do its work we
6294 * can append the differences to the new append only file. */
6295 if (server.bgrewritechildpid != -1)
6296 server.bgrewritebuf = sdscatlen(server.bgrewritebuf,buf,sdslen(buf));
6297
6298 sdsfree(buf);
6299 now = time(NULL);
6300 if (server.appendfsync == APPENDFSYNC_ALWAYS ||
6301 (server.appendfsync == APPENDFSYNC_EVERYSEC &&
6302 now-server.lastfsync > 1))
6303 {
6304 fsync(server.appendfd); /* Let's try to get this data on the disk */
6305 server.lastfsync = now;
6306 }
6307 }
6308
6309 /* In Redis commands are always executed in the context of a client, so in
6310 * order to load the append only file we need to create a fake client. */
6311 static struct redisClient *createFakeClient(void) {
6312 struct redisClient *c = zmalloc(sizeof(*c));
6313
6314 selectDb(c,0);
6315 c->fd = -1;
6316 c->querybuf = sdsempty();
6317 c->argc = 0;
6318 c->argv = NULL;
6319 c->flags = 0;
6320 /* We set the fake client as a slave waiting for the synchronization
6321 * so that Redis will not try to send replies to this client. */
6322 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
6323 c->reply = listCreate();
6324 listSetFreeMethod(c->reply,decrRefCount);
6325 listSetDupMethod(c->reply,dupClientReplyValue);
6326 return c;
6327 }
6328
6329 static void freeFakeClient(struct redisClient *c) {
6330 sdsfree(c->querybuf);
6331 listRelease(c->reply);
6332 zfree(c);
6333 }
6334
6335 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
6336 * error (the append only file is zero-length) REDIS_ERR is returned. On
6337 * fatal error an error message is logged and the program exists. */
6338 int loadAppendOnlyFile(char *filename) {
6339 struct redisClient *fakeClient;
6340 FILE *fp = fopen(filename,"r");
6341 struct redis_stat sb;
6342
6343 if (redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0)
6344 return REDIS_ERR;
6345
6346 if (fp == NULL) {
6347 redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno));
6348 exit(1);
6349 }
6350
6351 fakeClient = createFakeClient();
6352 while(1) {
6353 int argc, j;
6354 unsigned long len;
6355 robj **argv;
6356 char buf[128];
6357 sds argsds;
6358 struct redisCommand *cmd;
6359
6360 if (fgets(buf,sizeof(buf),fp) == NULL) {
6361 if (feof(fp))
6362 break;
6363 else
6364 goto readerr;
6365 }
6366 if (buf[0] != '*') goto fmterr;
6367 argc = atoi(buf+1);
6368 argv = zmalloc(sizeof(robj*)*argc);
6369 for (j = 0; j < argc; j++) {
6370 if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
6371 if (buf[0] != '$') goto fmterr;
6372 len = strtol(buf+1,NULL,10);
6373 argsds = sdsnewlen(NULL,len);
6374 if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
6375 argv[j] = createObject(REDIS_STRING,argsds);
6376 if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
6377 }
6378
6379 /* Command lookup */
6380 cmd = lookupCommand(argv[0]->ptr);
6381 if (!cmd) {
6382 redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", argv[0]->ptr);
6383 exit(1);
6384 }
6385 /* Try object sharing and encoding */
6386 if (server.shareobjects) {
6387 int j;
6388 for(j = 1; j < argc; j++)
6389 argv[j] = tryObjectSharing(argv[j]);
6390 }
6391 if (cmd->flags & REDIS_CMD_BULK)
6392 tryObjectEncoding(argv[argc-1]);
6393 /* Run the command in the context of a fake client */
6394 fakeClient->argc = argc;
6395 fakeClient->argv = argv;
6396 cmd->proc(fakeClient);
6397 /* Discard the reply objects list from the fake client */
6398 while(listLength(fakeClient->reply))
6399 listDelNode(fakeClient->reply,listFirst(fakeClient->reply));
6400 /* Clean up, ready for the next command */
6401 for (j = 0; j < argc; j++) decrRefCount(argv[j]);
6402 zfree(argv);
6403 }
6404 fclose(fp);
6405 freeFakeClient(fakeClient);
6406 return REDIS_OK;
6407
6408 readerr:
6409 if (feof(fp)) {
6410 redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file");
6411 } else {
6412 redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
6413 }
6414 exit(1);
6415 fmterr:
6416 redisLog(REDIS_WARNING,"Bad file format reading the append only file");
6417 exit(1);
6418 }
6419
6420 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
6421 static int fwriteBulk(FILE *fp, robj *obj) {
6422 char buf[128];
6423 obj = getDecodedObject(obj);
6424 snprintf(buf,sizeof(buf),"$%ld\r\n",(long)sdslen(obj->ptr));
6425 if (fwrite(buf,strlen(buf),1,fp) == 0) goto err;
6426 if (sdslen(obj->ptr) && fwrite(obj->ptr,sdslen(obj->ptr),1,fp) == 0)
6427 goto err;
6428 if (fwrite("\r\n",2,1,fp) == 0) goto err;
6429 decrRefCount(obj);
6430 return 1;
6431 err:
6432 decrRefCount(obj);
6433 return 0;
6434 }
6435
6436 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
6437 static int fwriteBulkDouble(FILE *fp, double d) {
6438 char buf[128], dbuf[128];
6439
6440 snprintf(dbuf,sizeof(dbuf),"%.17g\r\n",d);
6441 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(dbuf)-2);
6442 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
6443 if (fwrite(dbuf,strlen(dbuf),1,fp) == 0) return 0;
6444 return 1;
6445 }
6446
6447 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
6448 static int fwriteBulkLong(FILE *fp, long l) {
6449 char buf[128], lbuf[128];
6450
6451 snprintf(lbuf,sizeof(lbuf),"%ld\r\n",l);
6452 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(lbuf)-2);
6453 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
6454 if (fwrite(lbuf,strlen(lbuf),1,fp) == 0) return 0;
6455 return 1;
6456 }
6457
6458 /* Write a sequence of commands able to fully rebuild the dataset into
6459 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
6460 static int rewriteAppendOnlyFile(char *filename) {
6461 dictIterator *di = NULL;
6462 dictEntry *de;
6463 FILE *fp;
6464 char tmpfile[256];
6465 int j;
6466 time_t now = time(NULL);
6467
6468 /* Note that we have to use a different temp name here compared to the
6469 * one used by rewriteAppendOnlyFileBackground() function. */
6470 snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
6471 fp = fopen(tmpfile,"w");
6472 if (!fp) {
6473 redisLog(REDIS_WARNING, "Failed rewriting the append only file: %s", strerror(errno));
6474 return REDIS_ERR;
6475 }
6476 for (j = 0; j < server.dbnum; j++) {
6477 char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
6478 redisDb *db = server.db+j;
6479 dict *d = db->dict;
6480 if (dictSize(d) == 0) continue;
6481 di = dictGetIterator(d);
6482 if (!di) {
6483 fclose(fp);
6484 return REDIS_ERR;
6485 }
6486
6487 /* SELECT the new DB */
6488 if (fwrite(selectcmd,sizeof(selectcmd)-1,1,fp) == 0) goto werr;
6489 if (fwriteBulkLong(fp,j) == 0) goto werr;
6490
6491 /* Iterate this DB writing every entry */
6492 while((de = dictNext(di)) != NULL) {
6493 robj *key = dictGetEntryKey(de);
6494 robj *o = dictGetEntryVal(de);
6495 time_t expiretime = getExpire(db,key);
6496
6497 /* Save the key and associated value */
6498 if (o->type == REDIS_STRING) {
6499 /* Emit a SET command */
6500 char cmd[]="*3\r\n$3\r\nSET\r\n";
6501 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
6502 /* Key and value */
6503 if (fwriteBulk(fp,key) == 0) goto werr;
6504 if (fwriteBulk(fp,o) == 0) goto werr;
6505 } else if (o->type == REDIS_LIST) {
6506 /* Emit the RPUSHes needed to rebuild the list */
6507 list *list = o->ptr;
6508 listNode *ln;
6509
6510 listRewind(list);
6511 while((ln = listYield(list))) {
6512 char cmd[]="*3\r\n$5\r\nRPUSH\r\n";
6513 robj *eleobj = listNodeValue(ln);
6514
6515 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
6516 if (fwriteBulk(fp,key) == 0) goto werr;
6517 if (fwriteBulk(fp,eleobj) == 0) goto werr;
6518 }
6519 } else if (o->type == REDIS_SET) {
6520 /* Emit the SADDs needed to rebuild the set */
6521 dict *set = o->ptr;
6522 dictIterator *di = dictGetIterator(set);
6523 dictEntry *de;
6524
6525 while((de = dictNext(di)) != NULL) {
6526 char cmd[]="*3\r\n$4\r\nSADD\r\n";
6527 robj *eleobj = dictGetEntryKey(de);
6528
6529 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
6530 if (fwriteBulk(fp,key) == 0) goto werr;
6531 if (fwriteBulk(fp,eleobj) == 0) goto werr;
6532 }
6533 dictReleaseIterator(di);
6534 } else if (o->type == REDIS_ZSET) {
6535 /* Emit the ZADDs needed to rebuild the sorted set */
6536 zset *zs = o->ptr;
6537 dictIterator *di = dictGetIterator(zs->dict);
6538 dictEntry *de;
6539
6540 while((de = dictNext(di)) != NULL) {
6541 char cmd[]="*4\r\n$4\r\nZADD\r\n";
6542 robj *eleobj = dictGetEntryKey(de);
6543 double *score = dictGetEntryVal(de);
6544
6545 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
6546 if (fwriteBulk(fp,key) == 0) goto werr;
6547 if (fwriteBulkDouble(fp,*score) == 0) goto werr;
6548 if (fwriteBulk(fp,eleobj) == 0) goto werr;
6549 }
6550 dictReleaseIterator(di);
6551 } else {
6552 redisAssert(0 != 0);
6553 }
6554 /* Save the expire time */
6555 if (expiretime != -1) {
6556 char cmd[]="*3\r\n$8\r\nEXPIREAT\r\n";
6557 /* If this key is already expired skip it */
6558 if (expiretime < now) continue;
6559 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
6560 if (fwriteBulk(fp,key) == 0) goto werr;
6561 if (fwriteBulkLong(fp,expiretime) == 0) goto werr;
6562 }
6563 }
6564 dictReleaseIterator(di);
6565 }
6566
6567 /* Make sure data will not remain on the OS's output buffers */
6568 fflush(fp);
6569 fsync(fileno(fp));
6570 fclose(fp);
6571
6572 /* Use RENAME to make sure the DB file is changed atomically only
6573 * if the generate DB file is ok. */
6574 if (rename(tmpfile,filename) == -1) {
6575 redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
6576 unlink(tmpfile);
6577 return REDIS_ERR;
6578 }
6579 redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
6580 return REDIS_OK;
6581
6582 werr:
6583 fclose(fp);
6584 unlink(tmpfile);
6585 redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
6586 if (di) dictReleaseIterator(di);
6587 return REDIS_ERR;
6588 }
6589
6590 /* This is how rewriting of the append only file in background works:
6591 *
6592 * 1) The user calls BGREWRITEAOF
6593 * 2) Redis calls this function, that forks():
6594 * 2a) the child rewrite the append only file in a temp file.
6595 * 2b) the parent accumulates differences in server.bgrewritebuf.
6596 * 3) When the child finished '2a' exists.
6597 * 4) The parent will trap the exit code, if it's OK, will append the
6598 * data accumulated into server.bgrewritebuf into the temp file, and
6599 * finally will rename(2) the temp file in the actual file name.
6600 * The the new file is reopened as the new append only file. Profit!
6601 */
6602 static int rewriteAppendOnlyFileBackground(void) {
6603 pid_t childpid;
6604
6605 if (server.bgrewritechildpid != -1) return REDIS_ERR;
6606 if ((childpid = fork()) == 0) {
6607 /* Child */
6608 char tmpfile[256];
6609 close(server.fd);
6610
6611 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
6612 if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
6613 exit(0);
6614 } else {
6615 exit(1);
6616 }
6617 } else {
6618 /* Parent */
6619 if (childpid == -1) {
6620 redisLog(REDIS_WARNING,
6621 "Can't rewrite append only file in background: fork: %s",
6622 strerror(errno));
6623 return REDIS_ERR;
6624 }
6625 redisLog(REDIS_NOTICE,
6626 "Background append only file rewriting started by pid %d",childpid);
6627 server.bgrewritechildpid = childpid;
6628 /* We set appendseldb to -1 in order to force the next call to the
6629 * feedAppendOnlyFile() to issue a SELECT command, so the differences
6630 * accumulated by the parent into server.bgrewritebuf will start
6631 * with a SELECT statement and it will be safe to merge. */
6632 server.appendseldb = -1;
6633 return REDIS_OK;
6634 }
6635 return REDIS_OK; /* unreached */
6636 }
6637
6638 static void bgrewriteaofCommand(redisClient *c) {
6639 if (server.bgrewritechildpid != -1) {
6640 addReplySds(c,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
6641 return;
6642 }
6643 if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
6644 char *status = "+Background append only file rewriting started\r\n";
6645 addReplySds(c,sdsnew(status));
6646 } else {
6647 addReply(c,shared.err);
6648 }
6649 }
6650
6651 static void aofRemoveTempFile(pid_t childpid) {
6652 char tmpfile[256];
6653
6654 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
6655 unlink(tmpfile);
6656 }
6657
6658 /* =============================== Virtual Memory =========================== */
6659 static void vmInit(void) {
6660 off_t totsize;
6661
6662 server.vm_fp = fopen("/tmp/redisvm","w+b");
6663 if (server.vm_fp == NULL) {
6664 redisLog(REDIS_WARNING,"Impossible to open the swap file. Exiting.");
6665 exit(1);
6666 }
6667 server.vm_fd = fileno(server.vm_fp);
6668 server.vm_next_page = 0;
6669 server.vm_near_pages = 0;
6670 totsize = server.vm_pages*server.vm_page_size;
6671 redisLog(REDIS_NOTICE,"Allocating %lld bytes of swap file",totsize);
6672 if (ftruncate(server.vm_fd,totsize) == -1) {
6673 redisLog(REDIS_WARNING,"Can't ftruncate swap file: %s. Exiting.",
6674 strerror(errno));
6675 exit(1);
6676 } else {
6677 redisLog(REDIS_NOTICE,"Swap file allocated with success");
6678 }
6679 server.vm_bitmap = zmalloc((server.vm_pages+7)/8);
6680 redisLog(REDIS_DEBUG,"Allocated %lld bytes page table for %lld pages",
6681 (long long) (server.vm_pages+7)/8, server.vm_pages);
6682 memset(server.vm_bitmap,0,(server.vm_pages+7)/8);
6683 /* Try to remove the swap file, so the OS will really delete it from the
6684 * file system when Redis exists. */
6685 unlink("/tmp/redisvm");
6686 }
6687
6688 /* Mark the page as used */
6689 static void vmMarkPageUsed(off_t page) {
6690 off_t byte = page/8;
6691 int bit = page&7;
6692 server.vm_bitmap[byte] |= 1<<bit;
6693 printf("Mark used: %lld (byte:%lld bit:%d)\n", (long long)page,
6694 (long long)byte, bit);
6695 }
6696
6697 /* Mark N contiguous pages as used, with 'page' being the first. */
6698 static void vmMarkPagesUsed(off_t page, off_t count) {
6699 off_t j;
6700
6701 for (j = 0; j < count; j++)
6702 vmMarkPageUsed(page+j);
6703 }
6704
6705 /* Mark the page as free */
6706 static void vmMarkPageFree(off_t page) {
6707 off_t byte = page/8;
6708 int bit = page&7;
6709 server.vm_bitmap[byte] &= ~(1<<bit);
6710 }
6711
6712 /* Mark N contiguous pages as free, with 'page' being the first. */
6713 static void vmMarkPagesFree(off_t page, off_t count) {
6714 off_t j;
6715
6716 for (j = 0; j < count; j++)
6717 vmMarkPageFree(page+j);
6718 }
6719
6720 /* Test if the page is free */
6721 static int vmFreePage(off_t page) {
6722 off_t byte = page/8;
6723 int bit = page&7;
6724 return (server.vm_bitmap[byte] & (1<<bit)) == 0;
6725 }
6726
6727 /* Find N contiguous free pages storing the first page of the cluster in *first.
6728 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
6729 * REDIS_ERR is returned.
6730 *
6731 * This function uses a simple algorithm: we try to allocate
6732 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
6733 * again from the start of the swap file searching for free spaces.
6734 *
6735 * If it looks pretty clear that there are no free pages near our offset
6736 * we try to find less populated places doing a forward jump of
6737 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
6738 * without hurry, and then we jump again and so forth...
6739 *
6740 * This function can be improved using a free list to avoid to guess
6741 * too much, since we could collect data about freed pages.
6742 *
6743 * note: I implemented this function just after watching an episode of
6744 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
6745 */
6746 static int vmFindContiguousPages(off_t *first, int n) {
6747 off_t base, offset = 0, since_jump = 0, numfree = 0;
6748
6749 if (server.vm_near_pages == REDIS_VM_MAX_NEAR_PAGES) {
6750 server.vm_near_pages = 0;
6751 server.vm_next_page = 0;
6752 }
6753 server.vm_near_pages++; /* Yet another try for pages near to the old ones */
6754 base = server.vm_next_page;
6755
6756 while(offset < server.vm_pages) {
6757 off_t this = base+offset;
6758
6759 printf("THIS: %lld (%c)\n", (long long) this, vmFreePage(this) ? 'F' : 'X');
6760 /* If we overflow, restart from page zero */
6761 if (this >= server.vm_pages) {
6762 this -= server.vm_pages;
6763 if (this == 0) {
6764 /* Just overflowed, what we found on tail is no longer
6765 * interesting, as it's no longer contiguous. */
6766 numfree = 0;
6767 }
6768 }
6769 if (vmFreePage(this)) {
6770 /* This is a free page */
6771 numfree++;
6772 /* Already got N free pages? Return to the caller, with success */
6773 if (numfree == n) {
6774 *first = this-(n-1);
6775 server.vm_next_page = this+1;
6776 return REDIS_OK;
6777 }
6778 } else {
6779 /* The current one is not a free page */
6780 numfree = 0;
6781 }
6782
6783 /* Fast-forward if the current page is not free and we already
6784 * searched enough near this place. */
6785 since_jump++;
6786 if (!numfree && since_jump >= REDIS_VM_MAX_RANDOM_JUMP/4) {
6787 offset += random() % REDIS_VM_MAX_RANDOM_JUMP;
6788 since_jump = 0;
6789 /* Note that even if we rewind after the jump, we are don't need
6790 * to make sure numfree is set to zero as we only jump *if* it
6791 * is set to zero. */
6792 } else {
6793 /* Otherwise just check the next page */
6794 offset++;
6795 }
6796 }
6797 return REDIS_ERR;
6798 }
6799
6800 /* Swap the 'val' object relative to 'key' into disk. Store all the information
6801 * needed to later retrieve the object into the key object.
6802 * If we can't find enough contiguous empty pages to swap the object on disk
6803 * REDIS_ERR is returned. */
6804 static int vmSwapObject(robj *key, robj *val) {
6805 off_t pages = rdbSavedObjectPages(val);
6806 off_t page;
6807
6808 assert(key->storage == REDIS_VM_MEMORY);
6809 assert(key->refcount == 1);
6810 if (vmFindContiguousPages(&page,pages) == REDIS_ERR) return REDIS_ERR;
6811 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
6812 redisLog(REDIS_WARNING,
6813 "Critical VM problem in vmSwapObject(): can't seek: %s",
6814 strerror(errno));
6815 return REDIS_ERR;
6816 }
6817 rdbSaveObject(server.vm_fp,val);
6818 key->vm.page = page;
6819 key->vm.usedpages = pages;
6820 key->storage = REDIS_VM_SWAPPED;
6821 key->vtype = val->type;
6822 decrRefCount(val); /* Deallocate the object from memory. */
6823 vmMarkPagesUsed(page,pages);
6824 redisLog(REDIS_DEBUG,"VM: object %s swapped out at %lld (%lld pages)",
6825 (unsigned char*) key->ptr,
6826 (unsigned long long) page, (unsigned long long) pages);
6827 return REDIS_OK;
6828 }
6829
6830 /* Load the value object relative to the 'key' object from swap to memory.
6831 * The newly allocated object is returned. */
6832 static robj *vmLoadObject(robj *key) {
6833 robj *val;
6834
6835 assert(key->storage == REDIS_VM_SWAPPED);
6836 if (fseeko(server.vm_fp,key->vm.page*server.vm_page_size,SEEK_SET) == -1) {
6837 redisLog(REDIS_WARNING,
6838 "Unrecoverable VM problem in vmLoadObject(): can't seek: %s",
6839 strerror(errno));
6840 exit(1);
6841 }
6842 val = rdbLoadObject(key->vtype,server.vm_fp);
6843 if (val == NULL) {
6844 redisLog(REDIS_WARNING, "Unrecoverable VM problem in vmLoadObject(): can't load object from swap file: %s", strerror(errno));
6845 exit(1);
6846 }
6847 key->storage = REDIS_VM_MEMORY;
6848 key->vm.atime = server.unixtime;
6849 vmMarkPagesFree(key->vm.page,key->vm.usedpages);
6850 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk",
6851 (unsigned char*) key->ptr);
6852 return val;
6853 }
6854
6855 /* How a good candidate is this object for swapping?
6856 * The better candidate it is, the greater the returned value.
6857 *
6858 * Currently we try to perform a fast estimation of the object size in
6859 * memory, and combine it with aging informations.
6860 *
6861 * Basically swappability = idle-time * log(estimated size)
6862 *
6863 * Bigger objects are preferred over smaller objects, but not
6864 * proportionally, this is why we use the logarithm. This algorithm is
6865 * just a first try and will probably be tuned later. */
6866 static double computeObjectSwappability(robj *o) {
6867 time_t age = server.unixtime - o->vm.atime;
6868 long asize = 0;
6869 list *l;
6870 dict *d;
6871 struct dictEntry *de;
6872 int z;
6873
6874 if (age <= 0) return 0;
6875 switch(o->type) {
6876 case REDIS_STRING:
6877 if (o->encoding != REDIS_ENCODING_RAW) {
6878 asize = sizeof(*o);
6879 } else {
6880 asize = sdslen(o->ptr)+sizeof(*o)+sizeof(long)*2;
6881 }
6882 break;
6883 case REDIS_LIST:
6884 l = o->ptr;
6885 listNode *ln = listFirst(l);
6886
6887 asize = sizeof(list);
6888 if (ln) {
6889 robj *ele = ln->value;
6890 long elesize;
6891
6892 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
6893 (sizeof(*o)+sdslen(ele->ptr)) :
6894 sizeof(*o);
6895 asize += (sizeof(listNode)+elesize)*listLength(l);
6896 }
6897 break;
6898 case REDIS_SET:
6899 case REDIS_ZSET:
6900 z = (o->type == REDIS_ZSET);
6901 d = z ? ((zset*)o->ptr)->dict : o->ptr;
6902
6903 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
6904 if (z) asize += sizeof(zset)-sizeof(dict);
6905 if (dictSize(d)) {
6906 long elesize;
6907 robj *ele;
6908
6909 de = dictGetRandomKey(d);
6910 ele = dictGetEntryKey(de);
6911 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
6912 (sizeof(*o)+sdslen(ele->ptr)) :
6913 sizeof(*o);
6914 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
6915 if (z) asize += sizeof(zskiplistNode)*dictSize(d);
6916 }
6917 break;
6918 }
6919 return (double)asize*log(1+asize);
6920 }
6921
6922 /* Try to swap an object that's a good candidate for swapping.
6923 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
6924 * to swap any object at all. */
6925 static int vmSwapOneObject(void) {
6926 int j, i;
6927 struct dictEntry *best = NULL;
6928 double best_swappability = 0;
6929 robj *key, *val;
6930
6931 for (j = 0; j < server.dbnum; j++) {
6932 redisDb *db = server.db+j;
6933
6934 if (dictSize(db->dict) == 0) continue;
6935 for (i = 0; i < 5; i++) {
6936 dictEntry *de;
6937 double swappability;
6938
6939 de = dictGetRandomKey(db->dict);
6940 key = dictGetEntryKey(de);
6941 val = dictGetEntryVal(de);
6942 if (key->storage != REDIS_VM_MEMORY) continue;
6943 swappability = computeObjectSwappability(val);
6944 if (!best || swappability > best_swappability) {
6945 best = de;
6946 best_swappability = swappability;
6947 }
6948 }
6949 }
6950 if (best == NULL) return REDIS_ERR;
6951 key = dictGetEntryKey(best);
6952 val = dictGetEntryVal(best);
6953
6954 redisLog(REDIS_DEBUG,"Key with best swappability: %s, %f\n",
6955 key->ptr, best_swappability);
6956
6957 /* Unshare the key if needed */
6958 if (key->refcount > 1) {
6959 robj *newkey = dupStringObject(key);
6960 decrRefCount(key);
6961 key = dictGetEntryKey(best) = newkey;
6962 }
6963 /* Swap it */
6964 if (vmSwapObject(key,val) == REDIS_OK) {
6965 dictGetEntryVal(best) = NULL;
6966 return REDIS_OK;
6967 } else {
6968 return REDIS_ERR;
6969 }
6970 }
6971
6972 /* ================================= Debugging ============================== */
6973
6974 static void debugCommand(redisClient *c) {
6975 if (!strcasecmp(c->argv[1]->ptr,"segfault")) {
6976 *((char*)-1) = 'x';
6977 } else if (!strcasecmp(c->argv[1]->ptr,"reload")) {
6978 if (rdbSave(server.dbfilename) != REDIS_OK) {
6979 addReply(c,shared.err);
6980 return;
6981 }
6982 emptyDb();
6983 if (rdbLoad(server.dbfilename) != REDIS_OK) {
6984 addReply(c,shared.err);
6985 return;
6986 }
6987 redisLog(REDIS_WARNING,"DB reloaded by DEBUG RELOAD");
6988 addReply(c,shared.ok);
6989 } else if (!strcasecmp(c->argv[1]->ptr,"loadaof")) {
6990 emptyDb();
6991 if (loadAppendOnlyFile(server.appendfilename) != REDIS_OK) {
6992 addReply(c,shared.err);
6993 return;
6994 }
6995 redisLog(REDIS_WARNING,"Append Only File loaded by DEBUG LOADAOF");
6996 addReply(c,shared.ok);
6997 } else if (!strcasecmp(c->argv[1]->ptr,"object") && c->argc == 3) {
6998 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
6999 robj *key, *val;
7000
7001 if (!de) {
7002 addReply(c,shared.nokeyerr);
7003 return;
7004 }
7005 key = dictGetEntryKey(de);
7006 val = dictGetEntryVal(de);
7007 addReplySds(c,sdscatprintf(sdsempty(),
7008 "+Key at:%p refcount:%d, value at:%p refcount:%d encoding:%d serializedlength:%lld\r\n",
7009 (void*)key, key->refcount, (void*)val, val->refcount,
7010 val->encoding, rdbSavedObjectLen(val)));
7011 } else if (!strcasecmp(c->argv[1]->ptr,"swapout") && c->argc == 3) {
7012 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
7013 robj *key, *val;
7014
7015 if (!server.vm_enabled) {
7016 addReplySds(c,sdsnew("-ERR Virtual Memory is disabled\r\n"));
7017 return;
7018 }
7019 if (!de) {
7020 addReply(c,shared.nokeyerr);
7021 return;
7022 }
7023 key = dictGetEntryKey(de);
7024 val = dictGetEntryVal(de);
7025 /* If the key is shared we want to create a copy */
7026 if (key->refcount > 1) {
7027 robj *newkey = dupStringObject(key);
7028 decrRefCount(key);
7029 key = dictGetEntryKey(de) = newkey;
7030 }
7031 /* Swap it */
7032 if (key->storage != REDIS_VM_MEMORY) {
7033 addReplySds(c,sdsnew("-ERR This key is not in memory\r\n"));
7034 } else if (vmSwapObject(key,val) == REDIS_OK) {
7035 dictGetEntryVal(de) = NULL;
7036 addReply(c,shared.ok);
7037 } else {
7038 addReply(c,shared.err);
7039 }
7040 } else {
7041 addReplySds(c,sdsnew(
7042 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPOUT <key>|RELOAD]\r\n"));
7043 }
7044 }
7045
7046 static void _redisAssert(char *estr) {
7047 redisLog(REDIS_WARNING,"=== ASSERTION FAILED ===");
7048 redisLog(REDIS_WARNING,"==> %s\n",estr);
7049 #ifdef HAVE_BACKTRACE
7050 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
7051 *((char*)-1) = 'x';
7052 #endif
7053 }
7054
7055 /* =================================== Main! ================================ */
7056
7057 #ifdef __linux__
7058 int linuxOvercommitMemoryValue(void) {
7059 FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
7060 char buf[64];
7061
7062 if (!fp) return -1;
7063 if (fgets(buf,64,fp) == NULL) {
7064 fclose(fp);
7065 return -1;
7066 }
7067 fclose(fp);
7068
7069 return atoi(buf);
7070 }
7071
7072 void linuxOvercommitMemoryWarning(void) {
7073 if (linuxOvercommitMemoryValue() == 0) {
7074 redisLog(REDIS_WARNING,"WARNING overcommit_memory is set to 0! Background save may fail under low condition memory. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.");
7075 }
7076 }
7077 #endif /* __linux__ */
7078
7079 static void daemonize(void) {
7080 int fd;
7081 FILE *fp;
7082
7083 if (fork() != 0) exit(0); /* parent exits */
7084 printf("New pid: %d\n", getpid());
7085 setsid(); /* create a new session */
7086
7087 /* Every output goes to /dev/null. If Redis is daemonized but
7088 * the 'logfile' is set to 'stdout' in the configuration file
7089 * it will not log at all. */
7090 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
7091 dup2(fd, STDIN_FILENO);
7092 dup2(fd, STDOUT_FILENO);
7093 dup2(fd, STDERR_FILENO);
7094 if (fd > STDERR_FILENO) close(fd);
7095 }
7096 /* Try to write the pid file */
7097 fp = fopen(server.pidfile,"w");
7098 if (fp) {
7099 fprintf(fp,"%d\n",getpid());
7100 fclose(fp);
7101 }
7102 }
7103
7104 int main(int argc, char **argv) {
7105 initServerConfig();
7106 if (argc == 2) {
7107 resetServerSaveParams();
7108 loadServerConfig(argv[1]);
7109 } else if (argc > 2) {
7110 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n");
7111 exit(1);
7112 } else {
7113 redisLog(REDIS_WARNING,"Warning: no config file specified, using the default config. In order to specify a config file use 'redis-server /path/to/redis.conf'");
7114 }
7115 if (server.daemonize) daemonize();
7116 initServer();
7117 redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
7118 #ifdef __linux__
7119 linuxOvercommitMemoryWarning();
7120 #endif
7121 if (server.appendonly) {
7122 if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK)
7123 redisLog(REDIS_NOTICE,"DB loaded from append only file");
7124 } else {
7125 if (rdbLoad(server.dbfilename) == REDIS_OK)
7126 redisLog(REDIS_NOTICE,"DB loaded from disk");
7127 }
7128 if (aeCreateFileEvent(server.el, server.fd, AE_READABLE,
7129 acceptHandler, NULL) == AE_ERR) oom("creating file event");
7130 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
7131 aeMain(server.el);
7132 aeDeleteEventLoop(server.el);
7133 return 0;
7134 }
7135
7136 /* ============================= Backtrace support ========================= */
7137
7138 #ifdef HAVE_BACKTRACE
7139 static char *findFuncName(void *pointer, unsigned long *offset);
7140
7141 static void *getMcontextEip(ucontext_t *uc) {
7142 #if defined(__FreeBSD__)
7143 return (void*) uc->uc_mcontext.mc_eip;
7144 #elif defined(__dietlibc__)
7145 return (void*) uc->uc_mcontext.eip;
7146 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
7147 #if __x86_64__
7148 return (void*) uc->uc_mcontext->__ss.__rip;
7149 #else
7150 return (void*) uc->uc_mcontext->__ss.__eip;
7151 #endif
7152 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
7153 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
7154 return (void*) uc->uc_mcontext->__ss.__rip;
7155 #else
7156 return (void*) uc->uc_mcontext->__ss.__eip;
7157 #endif
7158 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
7159 return (void*) uc->uc_mcontext.gregs[REG_EIP]; /* Linux 32/64 bit */
7160 #elif defined(__ia64__) /* Linux IA64 */
7161 return (void*) uc->uc_mcontext.sc_ip;
7162 #else
7163 return NULL;
7164 #endif
7165 }
7166
7167 static void segvHandler(int sig, siginfo_t *info, void *secret) {
7168 void *trace[100];
7169 char **messages = NULL;
7170 int i, trace_size = 0;
7171 unsigned long offset=0;
7172 ucontext_t *uc = (ucontext_t*) secret;
7173 sds infostring;
7174 REDIS_NOTUSED(info);
7175
7176 redisLog(REDIS_WARNING,
7177 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig);
7178 infostring = genRedisInfoString();
7179 redisLog(REDIS_WARNING, "%s",infostring);
7180 /* It's not safe to sdsfree() the returned string under memory
7181 * corruption conditions. Let it leak as we are going to abort */
7182
7183 trace_size = backtrace(trace, 100);
7184 /* overwrite sigaction with caller's address */
7185 if (getMcontextEip(uc) != NULL) {
7186 trace[1] = getMcontextEip(uc);
7187 }
7188 messages = backtrace_symbols(trace, trace_size);
7189
7190 for (i=1; i<trace_size; ++i) {
7191 char *fn = findFuncName(trace[i], &offset), *p;
7192
7193 p = strchr(messages[i],'+');
7194 if (!fn || (p && ((unsigned long)strtol(p+1,NULL,10)) < offset)) {
7195 redisLog(REDIS_WARNING,"%s", messages[i]);
7196 } else {
7197 redisLog(REDIS_WARNING,"%d redis-server %p %s + %d", i, trace[i], fn, (unsigned int)offset);
7198 }
7199 }
7200 /* free(messages); Don't call free() with possibly corrupted memory. */
7201 exit(0);
7202 }
7203
7204 static void setupSigSegvAction(void) {
7205 struct sigaction act;
7206
7207 sigemptyset (&act.sa_mask);
7208 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
7209 * is used. Otherwise, sa_handler is used */
7210 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
7211 act.sa_sigaction = segvHandler;
7212 sigaction (SIGSEGV, &act, NULL);
7213 sigaction (SIGBUS, &act, NULL);
7214 sigaction (SIGFPE, &act, NULL);
7215 sigaction (SIGILL, &act, NULL);
7216 sigaction (SIGBUS, &act, NULL);
7217 return;
7218 }
7219
7220 #include "staticsymbols.h"
7221 /* This function try to convert a pointer into a function name. It's used in
7222 * oreder to provide a backtrace under segmentation fault that's able to
7223 * display functions declared as static (otherwise the backtrace is useless). */
7224 static char *findFuncName(void *pointer, unsigned long *offset){
7225 int i, ret = -1;
7226 unsigned long off, minoff = 0;
7227
7228 /* Try to match against the Symbol with the smallest offset */
7229 for (i=0; symsTable[i].pointer; i++) {
7230 unsigned long lp = (unsigned long) pointer;
7231
7232 if (lp != (unsigned long)-1 && lp >= symsTable[i].pointer) {
7233 off=lp-symsTable[i].pointer;
7234 if (ret < 0 || off < minoff) {
7235 minoff=off;
7236 ret=i;
7237 }
7238 }
7239 }
7240 if (ret == -1) return NULL;
7241 *offset = minoff;
7242 return symsTable[ret].name;
7243 }
7244 #else /* HAVE_BACKTRACE */
7245 static void setupSigSegvAction(void) {
7246 }
7247 #endif /* HAVE_BACKTRACE */
7248
7249
7250
7251 /* The End */
7252
7253
7254