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