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