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