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