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