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