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