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