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