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