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