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