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