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