2 * Copyright (c) 2006-2009, Salvatore Sanfilippo <antirez at gmail dot com>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
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.
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.
30 #define REDIS_VERSION "1.3.2"
40 #define __USE_POSIX199309
46 #endif /* HAVE_BACKTRACE */
54 #include <arpa/inet.h>
58 #include <sys/resource.h>
64 #include "solarisfixes.h"
68 #include "ae.h" /* Event driven programming library */
69 #include "sds.h" /* Dynamic safe strings */
70 #include "anet.h" /* Networking the easy way */
71 #include "dict.h" /* Hash tables */
72 #include "adlist.h" /* Linked lists */
73 #include "zmalloc.h" /* total memory usage aware version of malloc/free */
74 #include "lzf.h" /* LZF compression library */
75 #include "pqsort.h" /* Partial qsort for SORT+LIMIT */
81 /* Static server configuration */
82 #define REDIS_SERVERPORT 6379 /* TCP port */
83 #define REDIS_MAXIDLETIME (60*5) /* default client timeout */
84 #define REDIS_IOBUF_LEN 1024
85 #define REDIS_LOADBUF_LEN 1024
86 #define REDIS_STATIC_ARGS 4
87 #define REDIS_DEFAULT_DBNUM 16
88 #define REDIS_CONFIGLINE_MAX 1024
89 #define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
90 #define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
91 #define REDIS_EXPIRELOOKUPS_PER_CRON 100 /* try to expire 100 keys/second */
92 #define REDIS_MAX_WRITE_PER_EVENT (1024*64)
93 #define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */
95 /* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */
96 #define REDIS_WRITEV_THRESHOLD 3
97 /* Max number of iovecs used for each writev call */
98 #define REDIS_WRITEV_IOVEC_COUNT 256
100 /* Hash table parameters */
101 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
104 #define REDIS_CMD_BULK 1 /* Bulk write command */
105 #define REDIS_CMD_INLINE 2 /* Inline command */
106 /* REDIS_CMD_DENYOOM reserves a longer comment: all the commands marked with
107 this flags will return an error when the 'maxmemory' option is set in the
108 config file and the server is using more than maxmemory bytes of memory.
109 In short this commands are denied on low memory conditions. */
110 #define REDIS_CMD_DENYOOM 4
113 #define REDIS_STRING 0
119 /* Objects encoding */
120 #define REDIS_ENCODING_RAW 0 /* Raw representation */
121 #define REDIS_ENCODING_INT 1 /* Encoded as integer */
123 /* Object types only used for dumping to disk */
124 #define REDIS_EXPIRETIME 253
125 #define REDIS_SELECTDB 254
126 #define REDIS_EOF 255
128 /* Defines related to the dump file format. To store 32 bits lengths for short
129 * keys requires a lot of space, so we check the most significant 2 bits of
130 * the first byte to interpreter the length:
132 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
133 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
134 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
135 * 11|000000 this means: specially encoded object will follow. The six bits
136 * number specify the kind of object that follows.
137 * See the REDIS_RDB_ENC_* defines.
139 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
140 * values, will fit inside. */
141 #define REDIS_RDB_6BITLEN 0
142 #define REDIS_RDB_14BITLEN 1
143 #define REDIS_RDB_32BITLEN 2
144 #define REDIS_RDB_ENCVAL 3
145 #define REDIS_RDB_LENERR UINT_MAX
147 /* When a length of a string object stored on disk has the first two bits
148 * set, the remaining two bits specify a special encoding for the object
149 * accordingly to the following defines: */
150 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
151 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
152 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
153 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
155 /* Virtual memory object->where field. */
156 #define REDIS_VM_MEMORY 0 /* The object is on memory */
157 #define REDIS_VM_SWAPPED 1 /* The object is on disk */
158 #define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
159 #define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
161 /* Virtual memory static configuration stuff.
162 * Check vmFindContiguousPages() to know more about this magic numbers. */
163 #define REDIS_VM_MAX_NEAR_PAGES 65536
164 #define REDIS_VM_MAX_RANDOM_JUMP 4096
167 #define REDIS_CLOSE 1 /* This client connection should be closed ASAP */
168 #define REDIS_SLAVE 2 /* This client is a slave server */
169 #define REDIS_MASTER 4 /* This client is a master server */
170 #define REDIS_MONITOR 8 /* This client is a slave monitor, see MONITOR */
171 #define REDIS_MULTI 16 /* This client is in a MULTI context */
172 #define REDIS_BLOCKED 32 /* The client is waiting in a blocking operation */
174 /* Slave replication state - slave side */
175 #define REDIS_REPL_NONE 0 /* No active replication */
176 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
177 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
179 /* Slave replication state - from the point of view of master
180 * Note that in SEND_BULK and ONLINE state the slave receives new updates
181 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
182 * to start the next background saving in order to send updates to it. */
183 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
184 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
185 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
186 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
188 /* List related stuff */
192 /* Sort operations */
193 #define REDIS_SORT_GET 0
194 #define REDIS_SORT_ASC 1
195 #define REDIS_SORT_DESC 2
196 #define REDIS_SORTKEY_MAX 1024
199 #define REDIS_DEBUG 0
200 #define REDIS_NOTICE 1
201 #define REDIS_WARNING 2
203 /* Anti-warning macro... */
204 #define REDIS_NOTUSED(V) ((void) V)
206 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
207 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
209 /* Append only defines */
210 #define APPENDFSYNC_NO 0
211 #define APPENDFSYNC_ALWAYS 1
212 #define APPENDFSYNC_EVERYSEC 2
214 /* We can print the stacktrace, so our assert is defined this way: */
215 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e),exit(1)))
216 static void _redisAssert(char *estr
);
218 /*================================= Data types ============================== */
220 /* A redis object, that is a type able to hold a string / list / set */
222 /* The VM object structure */
223 struct redisObjectVM
{
224 off_t page
; /* the page at witch the object is stored on disk */
225 off_t usedpages
; /* number of pages used on disk */
226 time_t atime
; /* Last access time */
229 /* The actual Redis Object */
230 typedef struct redisObject
{
233 unsigned char encoding
;
234 unsigned char storage
; /* If this object is a key, where is the value?
235 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
236 unsigned char vtype
; /* If this object is a key, and value is swapped out,
237 * this is the type of the swapped out object. */
239 /* VM fields, this are only allocated if VM is active, otherwise the
240 * object allocation function will just allocate
241 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
242 * Redis without VM active will not have any overhead. */
243 struct redisObjectVM vm
;
246 /* Macro used to initalize a Redis object allocated on the stack.
247 * Note that this macro is taken near the structure definition to make sure
248 * we'll update it when the structure is changed, to avoid bugs like
249 * bug #85 introduced exactly in this way. */
250 #define initStaticStringObject(_var,_ptr) do { \
252 _var.type = REDIS_STRING; \
253 _var.encoding = REDIS_ENCODING_RAW; \
255 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
258 typedef struct redisDb
{
259 dict
*dict
; /* The keyspace for this DB */
260 dict
*expires
; /* Timeout of keys with a timeout set */
261 dict
*blockingkeys
; /* Keys with clients waiting for data (BLPOP) */
265 /* Client MULTI/EXEC state */
266 typedef struct multiCmd
{
269 struct redisCommand
*cmd
;
272 typedef struct multiState
{
273 multiCmd
*commands
; /* Array of MULTI commands */
274 int count
; /* Total number of MULTI commands */
277 /* With multiplexing we need to take per-clinet state.
278 * Clients are taken in a liked list. */
279 typedef struct redisClient
{
284 robj
**argv
, **mbargv
;
286 int bulklen
; /* bulk read len. -1 if not in bulk read mode */
287 int multibulk
; /* multi bulk command format active */
290 time_t lastinteraction
; /* time of the last interaction, used for timeout */
291 int flags
; /* REDIS_CLOSE | REDIS_SLAVE | REDIS_MONITOR */
293 int slaveseldb
; /* slave selected db, if this client is a slave */
294 int authenticated
; /* when requirepass is non-NULL */
295 int replstate
; /* replication state if this is a slave */
296 int repldbfd
; /* replication DB file descriptor */
297 long repldboff
; /* replication DB file offset */
298 off_t repldbsize
; /* replication DB file size */
299 multiState mstate
; /* MULTI/EXEC state */
300 robj
**blockingkeys
; /* The key we waiting to terminate a blocking
301 * operation such as BLPOP. Otherwise NULL. */
302 int blockingkeysnum
; /* Number of blocking keys */
303 time_t blockingto
; /* Blocking operation timeout. If UNIX current time
304 * is >= blockingto then the operation timed out. */
312 /* Global server state structure */
317 dict
*sharingpool
; /* Poll used for object sharing */
318 unsigned int sharingpoolsize
;
319 long long dirty
; /* changes to DB from the last save */
321 list
*slaves
, *monitors
;
322 char neterr
[ANET_ERR_LEN
];
324 int cronloops
; /* number of times the cron function run */
325 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
326 time_t lastsave
; /* Unix time of last save succeeede */
327 size_t usedmemory
; /* Used memory in megabytes */
328 /* Fields used only for stats */
329 time_t stat_starttime
; /* server start time */
330 long long stat_numcommands
; /* number of processed commands */
331 long long stat_numconnections
; /* number of connections received */
344 pid_t bgsavechildpid
;
345 pid_t bgrewritechildpid
;
346 sds bgrewritebuf
; /* buffer taken by parent during oppend only rewrite */
347 struct saveparam
*saveparams
;
352 char *appendfilename
;
356 /* Replication related */
361 redisClient
*master
; /* client that is master for this slave */
363 unsigned int maxclients
;
364 unsigned long long maxmemory
;
365 unsigned int blockedclients
;
366 /* Sort parameters - qsort_r() is only available under BSD so we
367 * have to take this state global, in order to pass it to sortCompare() */
371 /* Virtual memory configuration */
375 unsigned long long vm_max_memory
;
376 /* Virtual memory state */
379 off_t vm_next_page
; /* Next probably empty page */
380 off_t vm_near_pages
; /* Number of pages allocated sequentially */
381 unsigned char *vm_bitmap
; /* Bitmap of free/used pages */
382 time_t unixtime
; /* Unix time sampled every second. */
385 typedef void redisCommandProc(redisClient
*c
);
386 struct redisCommand
{
388 redisCommandProc
*proc
;
393 struct redisFunctionSym
{
395 unsigned long pointer
;
398 typedef struct _redisSortObject
{
406 typedef struct _redisSortOperation
{
409 } redisSortOperation
;
411 /* ZSETs use a specialized version of Skiplists */
413 typedef struct zskiplistNode
{
414 struct zskiplistNode
**forward
;
415 struct zskiplistNode
*backward
;
420 typedef struct zskiplist
{
421 struct zskiplistNode
*header
, *tail
;
422 unsigned long length
;
426 typedef struct zset
{
431 /* Our shared "common" objects */
433 struct sharedObjectsStruct
{
434 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
435 *colon
, *nullbulk
, *nullmultibulk
, *queued
,
436 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
437 *outofrangeerr
, *plus
,
438 *select0
, *select1
, *select2
, *select3
, *select4
,
439 *select5
, *select6
, *select7
, *select8
, *select9
;
442 /* Global vars that are actally used as constants. The following double
443 * values are used for double on-disk serialization, and are initialized
444 * at runtime to avoid strange compiler optimizations. */
446 static double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
448 /*================================ Prototypes =============================== */
450 static void freeStringObject(robj
*o
);
451 static void freeListObject(robj
*o
);
452 static void freeSetObject(robj
*o
);
453 static void decrRefCount(void *o
);
454 static robj
*createObject(int type
, void *ptr
);
455 static void freeClient(redisClient
*c
);
456 static int rdbLoad(char *filename
);
457 static void addReply(redisClient
*c
, robj
*obj
);
458 static void addReplySds(redisClient
*c
, sds s
);
459 static void incrRefCount(robj
*o
);
460 static int rdbSaveBackground(char *filename
);
461 static robj
*createStringObject(char *ptr
, size_t len
);
462 static robj
*dupStringObject(robj
*o
);
463 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
464 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
465 static int syncWithMaster(void);
466 static robj
*tryObjectSharing(robj
*o
);
467 static int tryObjectEncoding(robj
*o
);
468 static robj
*getDecodedObject(robj
*o
);
469 static int removeExpire(redisDb
*db
, robj
*key
);
470 static int expireIfNeeded(redisDb
*db
, robj
*key
);
471 static int deleteIfVolatile(redisDb
*db
, robj
*key
);
472 static int deleteKey(redisDb
*db
, robj
*key
);
473 static time_t getExpire(redisDb
*db
, robj
*key
);
474 static int setExpire(redisDb
*db
, robj
*key
, time_t when
);
475 static void updateSlavesWaitingBgsave(int bgsaveerr
);
476 static void freeMemoryIfNeeded(void);
477 static int processCommand(redisClient
*c
);
478 static void setupSigSegvAction(void);
479 static void rdbRemoveTempFile(pid_t childpid
);
480 static void aofRemoveTempFile(pid_t childpid
);
481 static size_t stringObjectLen(robj
*o
);
482 static void processInputBuffer(redisClient
*c
);
483 static zskiplist
*zslCreate(void);
484 static void zslFree(zskiplist
*zsl
);
485 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
);
486 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
487 static void initClientMultiState(redisClient
*c
);
488 static void freeClientMultiState(redisClient
*c
);
489 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
);
490 static void unblockClient(redisClient
*c
);
491 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
);
492 static void vmInit(void);
493 static void vmMarkPagesFree(off_t page
, off_t count
);
494 static robj
*vmLoadObject(robj
*key
);
495 static int vmSwapOneObject(void);
497 static void authCommand(redisClient
*c
);
498 static void pingCommand(redisClient
*c
);
499 static void echoCommand(redisClient
*c
);
500 static void setCommand(redisClient
*c
);
501 static void setnxCommand(redisClient
*c
);
502 static void getCommand(redisClient
*c
);
503 static void delCommand(redisClient
*c
);
504 static void existsCommand(redisClient
*c
);
505 static void incrCommand(redisClient
*c
);
506 static void decrCommand(redisClient
*c
);
507 static void incrbyCommand(redisClient
*c
);
508 static void decrbyCommand(redisClient
*c
);
509 static void selectCommand(redisClient
*c
);
510 static void randomkeyCommand(redisClient
*c
);
511 static void keysCommand(redisClient
*c
);
512 static void dbsizeCommand(redisClient
*c
);
513 static void lastsaveCommand(redisClient
*c
);
514 static void saveCommand(redisClient
*c
);
515 static void bgsaveCommand(redisClient
*c
);
516 static void bgrewriteaofCommand(redisClient
*c
);
517 static void shutdownCommand(redisClient
*c
);
518 static void moveCommand(redisClient
*c
);
519 static void renameCommand(redisClient
*c
);
520 static void renamenxCommand(redisClient
*c
);
521 static void lpushCommand(redisClient
*c
);
522 static void rpushCommand(redisClient
*c
);
523 static void lpopCommand(redisClient
*c
);
524 static void rpopCommand(redisClient
*c
);
525 static void llenCommand(redisClient
*c
);
526 static void lindexCommand(redisClient
*c
);
527 static void lrangeCommand(redisClient
*c
);
528 static void ltrimCommand(redisClient
*c
);
529 static void typeCommand(redisClient
*c
);
530 static void lsetCommand(redisClient
*c
);
531 static void saddCommand(redisClient
*c
);
532 static void sremCommand(redisClient
*c
);
533 static void smoveCommand(redisClient
*c
);
534 static void sismemberCommand(redisClient
*c
);
535 static void scardCommand(redisClient
*c
);
536 static void spopCommand(redisClient
*c
);
537 static void srandmemberCommand(redisClient
*c
);
538 static void sinterCommand(redisClient
*c
);
539 static void sinterstoreCommand(redisClient
*c
);
540 static void sunionCommand(redisClient
*c
);
541 static void sunionstoreCommand(redisClient
*c
);
542 static void sdiffCommand(redisClient
*c
);
543 static void sdiffstoreCommand(redisClient
*c
);
544 static void syncCommand(redisClient
*c
);
545 static void flushdbCommand(redisClient
*c
);
546 static void flushallCommand(redisClient
*c
);
547 static void sortCommand(redisClient
*c
);
548 static void lremCommand(redisClient
*c
);
549 static void rpoplpushcommand(redisClient
*c
);
550 static void infoCommand(redisClient
*c
);
551 static void mgetCommand(redisClient
*c
);
552 static void monitorCommand(redisClient
*c
);
553 static void expireCommand(redisClient
*c
);
554 static void expireatCommand(redisClient
*c
);
555 static void getsetCommand(redisClient
*c
);
556 static void ttlCommand(redisClient
*c
);
557 static void slaveofCommand(redisClient
*c
);
558 static void debugCommand(redisClient
*c
);
559 static void msetCommand(redisClient
*c
);
560 static void msetnxCommand(redisClient
*c
);
561 static void zaddCommand(redisClient
*c
);
562 static void zincrbyCommand(redisClient
*c
);
563 static void zrangeCommand(redisClient
*c
);
564 static void zrangebyscoreCommand(redisClient
*c
);
565 static void zrevrangeCommand(redisClient
*c
);
566 static void zcardCommand(redisClient
*c
);
567 static void zremCommand(redisClient
*c
);
568 static void zscoreCommand(redisClient
*c
);
569 static void zremrangebyscoreCommand(redisClient
*c
);
570 static void multiCommand(redisClient
*c
);
571 static void execCommand(redisClient
*c
);
572 static void blpopCommand(redisClient
*c
);
573 static void brpopCommand(redisClient
*c
);
575 /*================================= Globals ================================= */
578 static struct redisServer server
; /* server global state */
579 static struct redisCommand cmdTable
[] = {
580 {"get",getCommand
,2,REDIS_CMD_INLINE
},
581 {"set",setCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
582 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
583 {"del",delCommand
,-2,REDIS_CMD_INLINE
},
584 {"exists",existsCommand
,2,REDIS_CMD_INLINE
},
585 {"incr",incrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
586 {"decr",decrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
587 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
},
588 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
589 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
590 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
},
591 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
},
592 {"brpop",brpopCommand
,-3,REDIS_CMD_INLINE
},
593 {"blpop",blpopCommand
,-3,REDIS_CMD_INLINE
},
594 {"llen",llenCommand
,2,REDIS_CMD_INLINE
},
595 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
},
596 {"lset",lsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
597 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
},
598 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
},
599 {"lrem",lremCommand
,4,REDIS_CMD_BULK
},
600 {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
601 {"sadd",saddCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
602 {"srem",sremCommand
,3,REDIS_CMD_BULK
},
603 {"smove",smoveCommand
,4,REDIS_CMD_BULK
},
604 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
},
605 {"scard",scardCommand
,2,REDIS_CMD_INLINE
},
606 {"spop",spopCommand
,2,REDIS_CMD_INLINE
},
607 {"srandmember",srandmemberCommand
,2,REDIS_CMD_INLINE
},
608 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
609 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
610 {"sunion",sunionCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
611 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
612 {"sdiff",sdiffCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
613 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
614 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
},
615 {"zadd",zaddCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
616 {"zincrby",zincrbyCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
617 {"zrem",zremCommand
,3,REDIS_CMD_BULK
},
618 {"zremrangebyscore",zremrangebyscoreCommand
,4,REDIS_CMD_INLINE
},
619 {"zrange",zrangeCommand
,-4,REDIS_CMD_INLINE
},
620 {"zrangebyscore",zrangebyscoreCommand
,-4,REDIS_CMD_INLINE
},
621 {"zrevrange",zrevrangeCommand
,-4,REDIS_CMD_INLINE
},
622 {"zcard",zcardCommand
,2,REDIS_CMD_INLINE
},
623 {"zscore",zscoreCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
624 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
625 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
626 {"getset",getsetCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
627 {"mset",msetCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
628 {"msetnx",msetnxCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
629 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
},
630 {"select",selectCommand
,2,REDIS_CMD_INLINE
},
631 {"move",moveCommand
,3,REDIS_CMD_INLINE
},
632 {"rename",renameCommand
,3,REDIS_CMD_INLINE
},
633 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
},
634 {"expire",expireCommand
,3,REDIS_CMD_INLINE
},
635 {"expireat",expireatCommand
,3,REDIS_CMD_INLINE
},
636 {"keys",keysCommand
,2,REDIS_CMD_INLINE
},
637 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
},
638 {"auth",authCommand
,2,REDIS_CMD_INLINE
},
639 {"ping",pingCommand
,1,REDIS_CMD_INLINE
},
640 {"echo",echoCommand
,2,REDIS_CMD_BULK
},
641 {"save",saveCommand
,1,REDIS_CMD_INLINE
},
642 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
},
643 {"bgrewriteaof",bgrewriteaofCommand
,1,REDIS_CMD_INLINE
},
644 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
},
645 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
},
646 {"type",typeCommand
,2,REDIS_CMD_INLINE
},
647 {"multi",multiCommand
,1,REDIS_CMD_INLINE
},
648 {"exec",execCommand
,1,REDIS_CMD_INLINE
},
649 {"sync",syncCommand
,1,REDIS_CMD_INLINE
},
650 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
},
651 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
},
652 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
653 {"info",infoCommand
,1,REDIS_CMD_INLINE
},
654 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
},
655 {"ttl",ttlCommand
,2,REDIS_CMD_INLINE
},
656 {"slaveof",slaveofCommand
,3,REDIS_CMD_INLINE
},
657 {"debug",debugCommand
,-2,REDIS_CMD_INLINE
},
661 /*============================ Utility functions ============================ */
663 /* Glob-style pattern matching. */
664 int stringmatchlen(const char *pattern
, int patternLen
,
665 const char *string
, int stringLen
, int nocase
)
670 while (pattern
[1] == '*') {
675 return 1; /* match */
677 if (stringmatchlen(pattern
+1, patternLen
-1,
678 string
, stringLen
, nocase
))
679 return 1; /* match */
683 return 0; /* no match */
687 return 0; /* no match */
697 not = pattern
[0] == '^';
704 if (pattern
[0] == '\\') {
707 if (pattern
[0] == string
[0])
709 } else if (pattern
[0] == ']') {
711 } else if (patternLen
== 0) {
715 } else if (pattern
[1] == '-' && patternLen
>= 3) {
716 int start
= pattern
[0];
717 int end
= pattern
[2];
725 start
= tolower(start
);
731 if (c
>= start
&& c
<= end
)
735 if (pattern
[0] == string
[0])
738 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
748 return 0; /* no match */
754 if (patternLen
>= 2) {
761 if (pattern
[0] != string
[0])
762 return 0; /* no match */
764 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
765 return 0; /* no match */
773 if (stringLen
== 0) {
774 while(*pattern
== '*') {
781 if (patternLen
== 0 && stringLen
== 0)
786 static void redisLog(int level
, const char *fmt
, ...) {
790 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
794 if (level
>= server
.verbosity
) {
800 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
801 fprintf(fp
,"%s %c ",buf
,c
[level
]);
802 vfprintf(fp
, fmt
, ap
);
808 if (server
.logfile
) fclose(fp
);
811 /*====================== Hash table type implementation ==================== */
813 /* This is an hash table type that uses the SDS dynamic strings libary as
814 * keys and radis objects as values (objects can hold SDS strings,
817 static void dictVanillaFree(void *privdata
, void *val
)
819 DICT_NOTUSED(privdata
);
823 static void dictListDestructor(void *privdata
, void *val
)
825 DICT_NOTUSED(privdata
);
826 listRelease((list
*)val
);
829 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
833 DICT_NOTUSED(privdata
);
835 l1
= sdslen((sds
)key1
);
836 l2
= sdslen((sds
)key2
);
837 if (l1
!= l2
) return 0;
838 return memcmp(key1
, key2
, l1
) == 0;
841 static void dictRedisObjectDestructor(void *privdata
, void *val
)
843 DICT_NOTUSED(privdata
);
845 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
849 static int dictObjKeyCompare(void *privdata
, const void *key1
,
852 const robj
*o1
= key1
, *o2
= key2
;
853 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
856 static unsigned int dictObjHash(const void *key
) {
858 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
861 static int dictEncObjKeyCompare(void *privdata
, const void *key1
,
864 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
867 o1
= getDecodedObject(o1
);
868 o2
= getDecodedObject(o2
);
869 cmp
= sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
875 static unsigned int dictEncObjHash(const void *key
) {
876 robj
*o
= (robj
*) key
;
878 o
= getDecodedObject(o
);
879 unsigned int hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
884 static dictType setDictType
= {
885 dictEncObjHash
, /* hash function */
888 dictEncObjKeyCompare
, /* key compare */
889 dictRedisObjectDestructor
, /* key destructor */
890 NULL
/* val destructor */
893 static dictType zsetDictType
= {
894 dictEncObjHash
, /* hash function */
897 dictEncObjKeyCompare
, /* key compare */
898 dictRedisObjectDestructor
, /* key destructor */
899 dictVanillaFree
/* val destructor of malloc(sizeof(double)) */
902 static dictType hashDictType
= {
903 dictObjHash
, /* hash function */
906 dictObjKeyCompare
, /* key compare */
907 dictRedisObjectDestructor
, /* key destructor */
908 dictRedisObjectDestructor
/* val destructor */
911 /* Keylist hash table type has unencoded redis objects as keys and
912 * lists as values. It's used for blocking operations (BLPOP) */
913 static dictType keylistDictType
= {
914 dictObjHash
, /* hash function */
917 dictObjKeyCompare
, /* key compare */
918 dictRedisObjectDestructor
, /* key destructor */
919 dictListDestructor
/* val destructor */
922 /* ========================= Random utility functions ======================= */
924 /* Redis generally does not try to recover from out of memory conditions
925 * when allocating objects or strings, it is not clear if it will be possible
926 * to report this condition to the client since the networking layer itself
927 * is based on heap allocation for send buffers, so we simply abort.
928 * At least the code will be simpler to read... */
929 static void oom(const char *msg
) {
930 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
935 /* ====================== Redis server networking stuff ===================== */
936 static void closeTimedoutClients(void) {
939 time_t now
= time(NULL
);
941 listRewind(server
.clients
);
942 while ((ln
= listYield(server
.clients
)) != NULL
) {
943 c
= listNodeValue(ln
);
944 if (server
.maxidletime
&&
945 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
946 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
947 (now
- c
->lastinteraction
> server
.maxidletime
))
949 redisLog(REDIS_DEBUG
,"Closing idle client");
951 } else if (c
->flags
& REDIS_BLOCKED
) {
952 if (c
->blockingto
!= 0 && c
->blockingto
< now
) {
953 addReply(c
,shared
.nullmultibulk
);
960 static int htNeedsResize(dict
*dict
) {
961 long long size
, used
;
963 size
= dictSlots(dict
);
964 used
= dictSize(dict
);
965 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
966 (used
*100/size
< REDIS_HT_MINFILL
));
969 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
970 * we resize the hash table to save memory */
971 static void tryResizeHashTables(void) {
974 for (j
= 0; j
< server
.dbnum
; j
++) {
975 if (htNeedsResize(server
.db
[j
].dict
)) {
976 redisLog(REDIS_DEBUG
,"The hash table %d is too sparse, resize it...",j
);
977 dictResize(server
.db
[j
].dict
);
978 redisLog(REDIS_DEBUG
,"Hash table %d resized.",j
);
980 if (htNeedsResize(server
.db
[j
].expires
))
981 dictResize(server
.db
[j
].expires
);
985 /* A background saving child (BGSAVE) terminated its work. Handle this. */
986 void backgroundSaveDoneHandler(int statloc
) {
987 int exitcode
= WEXITSTATUS(statloc
);
988 int bysignal
= WIFSIGNALED(statloc
);
990 if (!bysignal
&& exitcode
== 0) {
991 redisLog(REDIS_NOTICE
,
992 "Background saving terminated with success");
994 server
.lastsave
= time(NULL
);
995 } else if (!bysignal
&& exitcode
!= 0) {
996 redisLog(REDIS_WARNING
, "Background saving error");
998 redisLog(REDIS_WARNING
,
999 "Background saving terminated by signal");
1000 rdbRemoveTempFile(server
.bgsavechildpid
);
1002 server
.bgsavechildpid
= -1;
1003 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1004 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1005 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);
1008 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1010 void backgroundRewriteDoneHandler(int statloc
) {
1011 int exitcode
= WEXITSTATUS(statloc
);
1012 int bysignal
= WIFSIGNALED(statloc
);
1014 if (!bysignal
&& exitcode
== 0) {
1018 redisLog(REDIS_NOTICE
,
1019 "Background append only file rewriting terminated with success");
1020 /* Now it's time to flush the differences accumulated by the parent */
1021 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) server
.bgrewritechildpid
);
1022 fd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
1024 redisLog(REDIS_WARNING
, "Not able to open the temp append only file produced by the child: %s", strerror(errno
));
1027 /* Flush our data... */
1028 if (write(fd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
)) !=
1029 (signed) sdslen(server
.bgrewritebuf
)) {
1030 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
));
1034 redisLog(REDIS_NOTICE
,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server
.bgrewritebuf
));
1035 /* Now our work is to rename the temp file into the stable file. And
1036 * switch the file descriptor used by the server for append only. */
1037 if (rename(tmpfile
,server
.appendfilename
) == -1) {
1038 redisLog(REDIS_WARNING
,"Can't rename the temp append only file into the stable one: %s", strerror(errno
));
1042 /* Mission completed... almost */
1043 redisLog(REDIS_NOTICE
,"Append only file successfully rewritten.");
1044 if (server
.appendfd
!= -1) {
1045 /* If append only is actually enabled... */
1046 close(server
.appendfd
);
1047 server
.appendfd
= fd
;
1049 server
.appendseldb
= -1; /* Make sure it will issue SELECT */
1050 redisLog(REDIS_NOTICE
,"The new append only file was selected for future appends.");
1052 /* If append only is disabled we just generate a dump in this
1053 * format. Why not? */
1056 } else if (!bysignal
&& exitcode
!= 0) {
1057 redisLog(REDIS_WARNING
, "Background append only file rewriting error");
1059 redisLog(REDIS_WARNING
,
1060 "Background append only file rewriting terminated by signal");
1063 sdsfree(server
.bgrewritebuf
);
1064 server
.bgrewritebuf
= sdsempty();
1065 aofRemoveTempFile(server
.bgrewritechildpid
);
1066 server
.bgrewritechildpid
= -1;
1069 static int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
1070 int j
, loops
= server
.cronloops
++;
1071 REDIS_NOTUSED(eventLoop
);
1073 REDIS_NOTUSED(clientData
);
1075 /* We take a cached value of the unix time in the global state because
1076 * with virtual memory and aging there is to store the current time
1077 * in objects at every object access, and accuracy is not needed.
1078 * To access a global var is faster than calling time(NULL) */
1079 server
.unixtime
= time(NULL
);
1081 /* Update the global state with the amount of used memory */
1082 server
.usedmemory
= zmalloc_used_memory();
1084 /* Show some info about non-empty databases */
1085 for (j
= 0; j
< server
.dbnum
; j
++) {
1086 long long size
, used
, vkeys
;
1088 size
= dictSlots(server
.db
[j
].dict
);
1089 used
= dictSize(server
.db
[j
].dict
);
1090 vkeys
= dictSize(server
.db
[j
].expires
);
1091 if (!(loops
% 5) && (used
|| vkeys
)) {
1092 redisLog(REDIS_DEBUG
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
1093 /* dictPrintStats(server.dict); */
1097 /* We don't want to resize the hash tables while a bacground saving
1098 * is in progress: the saving child is created using fork() that is
1099 * implemented with a copy-on-write semantic in most modern systems, so
1100 * if we resize the HT while there is the saving child at work actually
1101 * a lot of memory movements in the parent will cause a lot of pages
1103 if (server
.bgsavechildpid
== -1) tryResizeHashTables();
1105 /* Show information about connected clients */
1107 redisLog(REDIS_DEBUG
,"%d clients connected (%d slaves), %zu bytes in use, %d shared objects",
1108 listLength(server
.clients
)-listLength(server
.slaves
),
1109 listLength(server
.slaves
),
1111 dictSize(server
.sharingpool
));
1114 /* Close connections of timedout clients */
1115 if ((server
.maxidletime
&& !(loops
% 10)) || server
.blockedclients
)
1116 closeTimedoutClients();
1118 /* Check if a background saving or AOF rewrite in progress terminated */
1119 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
1123 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
1124 if (pid
== server
.bgsavechildpid
) {
1125 backgroundSaveDoneHandler(statloc
);
1127 backgroundRewriteDoneHandler(statloc
);
1131 /* If there is not a background saving in progress check if
1132 * we have to save now */
1133 time_t now
= time(NULL
);
1134 for (j
= 0; j
< server
.saveparamslen
; j
++) {
1135 struct saveparam
*sp
= server
.saveparams
+j
;
1137 if (server
.dirty
>= sp
->changes
&&
1138 now
-server
.lastsave
> sp
->seconds
) {
1139 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
1140 sp
->changes
, sp
->seconds
);
1141 rdbSaveBackground(server
.dbfilename
);
1147 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1148 * will use few CPU cycles if there are few expiring keys, otherwise
1149 * it will get more aggressive to avoid that too much memory is used by
1150 * keys that can be removed from the keyspace. */
1151 for (j
= 0; j
< server
.dbnum
; j
++) {
1153 redisDb
*db
= server
.db
+j
;
1155 /* Continue to expire if at the end of the cycle more than 25%
1156 * of the keys were expired. */
1158 long num
= dictSize(db
->expires
);
1159 time_t now
= time(NULL
);
1162 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
1163 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
1168 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
1169 t
= (time_t) dictGetEntryVal(de
);
1171 deleteKey(db
,dictGetEntryKey(de
));
1175 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
1178 /* Swap a few keys on disk if we are over the memory limit and VM
1180 while (server
.vm_enabled
&& zmalloc_used_memory() > server
.vm_max_memory
) {
1181 if (vmSwapOneObject() == REDIS_ERR
) {
1182 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit reached but unable to swap more objects out!");
1187 /* Check if we should connect to a MASTER */
1188 if (server
.replstate
== REDIS_REPL_CONNECT
) {
1189 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
1190 if (syncWithMaster() == REDIS_OK
) {
1191 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
1197 static void createSharedObjects(void) {
1198 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
1199 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
1200 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
1201 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
1202 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
1203 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
1204 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
1205 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
1206 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
1207 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
1208 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
1209 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
1210 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1211 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
1212 "-ERR no such key\r\n"));
1213 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
1214 "-ERR syntax error\r\n"));
1215 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
1216 "-ERR source and destination objects are the same\r\n"));
1217 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
1218 "-ERR index out of range\r\n"));
1219 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
1220 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
1221 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
1222 shared
.select0
= createStringObject("select 0\r\n",10);
1223 shared
.select1
= createStringObject("select 1\r\n",10);
1224 shared
.select2
= createStringObject("select 2\r\n",10);
1225 shared
.select3
= createStringObject("select 3\r\n",10);
1226 shared
.select4
= createStringObject("select 4\r\n",10);
1227 shared
.select5
= createStringObject("select 5\r\n",10);
1228 shared
.select6
= createStringObject("select 6\r\n",10);
1229 shared
.select7
= createStringObject("select 7\r\n",10);
1230 shared
.select8
= createStringObject("select 8\r\n",10);
1231 shared
.select9
= createStringObject("select 9\r\n",10);
1234 static void appendServerSaveParams(time_t seconds
, int changes
) {
1235 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
1236 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
1237 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
1238 server
.saveparamslen
++;
1241 static void resetServerSaveParams() {
1242 zfree(server
.saveparams
);
1243 server
.saveparams
= NULL
;
1244 server
.saveparamslen
= 0;
1247 static void initServerConfig() {
1248 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
1249 server
.port
= REDIS_SERVERPORT
;
1250 server
.verbosity
= REDIS_DEBUG
;
1251 server
.maxidletime
= REDIS_MAXIDLETIME
;
1252 server
.saveparams
= NULL
;
1253 server
.logfile
= NULL
; /* NULL = log on standard output */
1254 server
.bindaddr
= NULL
;
1255 server
.glueoutputbuf
= 1;
1256 server
.daemonize
= 0;
1257 server
.appendonly
= 0;
1258 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1259 server
.lastfsync
= time(NULL
);
1260 server
.appendfd
= -1;
1261 server
.appendseldb
= -1; /* Make sure the first time will not match */
1262 server
.pidfile
= "/var/run/redis.pid";
1263 server
.dbfilename
= "dump.rdb";
1264 server
.appendfilename
= "appendonly.aof";
1265 server
.requirepass
= NULL
;
1266 server
.shareobjects
= 0;
1267 server
.rdbcompression
= 1;
1268 server
.sharingpoolsize
= 1024;
1269 server
.maxclients
= 0;
1270 server
.blockedclients
= 0;
1271 server
.maxmemory
= 0;
1272 server
.vm_enabled
= 0;
1273 server
.vm_page_size
= 256; /* 256 bytes per page */
1274 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
1275 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
1277 resetServerSaveParams();
1279 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1280 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1281 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1282 /* Replication related */
1284 server
.masterauth
= NULL
;
1285 server
.masterhost
= NULL
;
1286 server
.masterport
= 6379;
1287 server
.master
= NULL
;
1288 server
.replstate
= REDIS_REPL_NONE
;
1290 /* Double constants initialization */
1292 R_PosInf
= 1.0/R_Zero
;
1293 R_NegInf
= -1.0/R_Zero
;
1294 R_Nan
= R_Zero
/R_Zero
;
1297 static void initServer() {
1300 signal(SIGHUP
, SIG_IGN
);
1301 signal(SIGPIPE
, SIG_IGN
);
1302 setupSigSegvAction();
1304 server
.clients
= listCreate();
1305 server
.slaves
= listCreate();
1306 server
.monitors
= listCreate();
1307 server
.objfreelist
= listCreate();
1308 createSharedObjects();
1309 server
.el
= aeCreateEventLoop();
1310 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
1311 server
.sharingpool
= dictCreate(&setDictType
,NULL
);
1312 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
1313 if (server
.fd
== -1) {
1314 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
1317 for (j
= 0; j
< server
.dbnum
; j
++) {
1318 server
.db
[j
].dict
= dictCreate(&hashDictType
,NULL
);
1319 server
.db
[j
].expires
= dictCreate(&setDictType
,NULL
);
1320 server
.db
[j
].blockingkeys
= dictCreate(&keylistDictType
,NULL
);
1321 server
.db
[j
].id
= j
;
1323 server
.cronloops
= 0;
1324 server
.bgsavechildpid
= -1;
1325 server
.bgrewritechildpid
= -1;
1326 server
.bgrewritebuf
= sdsempty();
1327 server
.lastsave
= time(NULL
);
1329 server
.usedmemory
= 0;
1330 server
.stat_numcommands
= 0;
1331 server
.stat_numconnections
= 0;
1332 server
.stat_starttime
= time(NULL
);
1333 server
.unixtime
= time(NULL
);
1334 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
1336 if (server
.appendonly
) {
1337 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1338 if (server
.appendfd
== -1) {
1339 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1345 if (server
.vm_enabled
) vmInit();
1348 /* Empty the whole database */
1349 static long long emptyDb() {
1351 long long removed
= 0;
1353 for (j
= 0; j
< server
.dbnum
; j
++) {
1354 removed
+= dictSize(server
.db
[j
].dict
);
1355 dictEmpty(server
.db
[j
].dict
);
1356 dictEmpty(server
.db
[j
].expires
);
1361 static int yesnotoi(char *s
) {
1362 if (!strcasecmp(s
,"yes")) return 1;
1363 else if (!strcasecmp(s
,"no")) return 0;
1367 /* I agree, this is a very rudimental way to load a configuration...
1368 will improve later if the config gets more complex */
1369 static void loadServerConfig(char *filename
) {
1371 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
1375 if (filename
[0] == '-' && filename
[1] == '\0')
1378 if ((fp
= fopen(filename
,"r")) == NULL
) {
1379 redisLog(REDIS_WARNING
,"Fatal error, can't open config file");
1384 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
1390 line
= sdstrim(line
," \t\r\n");
1392 /* Skip comments and blank lines*/
1393 if (line
[0] == '#' || line
[0] == '\0') {
1398 /* Split into arguments */
1399 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
1400 sdstolower(argv
[0]);
1402 /* Execute config directives */
1403 if (!strcasecmp(argv
[0],"timeout") && argc
== 2) {
1404 server
.maxidletime
= atoi(argv
[1]);
1405 if (server
.maxidletime
< 0) {
1406 err
= "Invalid timeout value"; goto loaderr
;
1408 } else if (!strcasecmp(argv
[0],"port") && argc
== 2) {
1409 server
.port
= atoi(argv
[1]);
1410 if (server
.port
< 1 || server
.port
> 65535) {
1411 err
= "Invalid port"; goto loaderr
;
1413 } else if (!strcasecmp(argv
[0],"bind") && argc
== 2) {
1414 server
.bindaddr
= zstrdup(argv
[1]);
1415 } else if (!strcasecmp(argv
[0],"save") && argc
== 3) {
1416 int seconds
= atoi(argv
[1]);
1417 int changes
= atoi(argv
[2]);
1418 if (seconds
< 1 || changes
< 0) {
1419 err
= "Invalid save parameters"; goto loaderr
;
1421 appendServerSaveParams(seconds
,changes
);
1422 } else if (!strcasecmp(argv
[0],"dir") && argc
== 2) {
1423 if (chdir(argv
[1]) == -1) {
1424 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
1425 argv
[1], strerror(errno
));
1428 } else if (!strcasecmp(argv
[0],"loglevel") && argc
== 2) {
1429 if (!strcasecmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
1430 else if (!strcasecmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
1431 else if (!strcasecmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
1433 err
= "Invalid log level. Must be one of debug, notice, warning";
1436 } else if (!strcasecmp(argv
[0],"logfile") && argc
== 2) {
1439 server
.logfile
= zstrdup(argv
[1]);
1440 if (!strcasecmp(server
.logfile
,"stdout")) {
1441 zfree(server
.logfile
);
1442 server
.logfile
= NULL
;
1444 if (server
.logfile
) {
1445 /* Test if we are able to open the file. The server will not
1446 * be able to abort just for this problem later... */
1447 logfp
= fopen(server
.logfile
,"a");
1448 if (logfp
== NULL
) {
1449 err
= sdscatprintf(sdsempty(),
1450 "Can't open the log file: %s", strerror(errno
));
1455 } else if (!strcasecmp(argv
[0],"databases") && argc
== 2) {
1456 server
.dbnum
= atoi(argv
[1]);
1457 if (server
.dbnum
< 1) {
1458 err
= "Invalid number of databases"; goto loaderr
;
1460 } else if (!strcasecmp(argv
[0],"maxclients") && argc
== 2) {
1461 server
.maxclients
= atoi(argv
[1]);
1462 } else if (!strcasecmp(argv
[0],"maxmemory") && argc
== 2) {
1463 server
.maxmemory
= strtoll(argv
[1], NULL
, 10);
1464 } else if (!strcasecmp(argv
[0],"slaveof") && argc
== 3) {
1465 server
.masterhost
= sdsnew(argv
[1]);
1466 server
.masterport
= atoi(argv
[2]);
1467 server
.replstate
= REDIS_REPL_CONNECT
;
1468 } else if (!strcasecmp(argv
[0],"masterauth") && argc
== 2) {
1469 server
.masterauth
= zstrdup(argv
[1]);
1470 } else if (!strcasecmp(argv
[0],"glueoutputbuf") && argc
== 2) {
1471 if ((server
.glueoutputbuf
= yesnotoi(argv
[1])) == -1) {
1472 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1474 } else if (!strcasecmp(argv
[0],"shareobjects") && argc
== 2) {
1475 if ((server
.shareobjects
= yesnotoi(argv
[1])) == -1) {
1476 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1478 } else if (!strcasecmp(argv
[0],"rdbcompression") && argc
== 2) {
1479 if ((server
.rdbcompression
= yesnotoi(argv
[1])) == -1) {
1480 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1482 } else if (!strcasecmp(argv
[0],"shareobjectspoolsize") && argc
== 2) {
1483 server
.sharingpoolsize
= atoi(argv
[1]);
1484 if (server
.sharingpoolsize
< 1) {
1485 err
= "invalid object sharing pool size"; goto loaderr
;
1487 } else if (!strcasecmp(argv
[0],"daemonize") && argc
== 2) {
1488 if ((server
.daemonize
= yesnotoi(argv
[1])) == -1) {
1489 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1491 } else if (!strcasecmp(argv
[0],"appendonly") && argc
== 2) {
1492 if ((server
.appendonly
= yesnotoi(argv
[1])) == -1) {
1493 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1495 } else if (!strcasecmp(argv
[0],"appendfsync") && argc
== 2) {
1496 if (!strcasecmp(argv
[1],"no")) {
1497 server
.appendfsync
= APPENDFSYNC_NO
;
1498 } else if (!strcasecmp(argv
[1],"always")) {
1499 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1500 } else if (!strcasecmp(argv
[1],"everysec")) {
1501 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1503 err
= "argument must be 'no', 'always' or 'everysec'";
1506 } else if (!strcasecmp(argv
[0],"requirepass") && argc
== 2) {
1507 server
.requirepass
= zstrdup(argv
[1]);
1508 } else if (!strcasecmp(argv
[0],"pidfile") && argc
== 2) {
1509 server
.pidfile
= zstrdup(argv
[1]);
1510 } else if (!strcasecmp(argv
[0],"dbfilename") && argc
== 2) {
1511 server
.dbfilename
= zstrdup(argv
[1]);
1512 } else if (!strcasecmp(argv
[0],"vm-enabled") && argc
== 2) {
1513 if ((server
.vm_enabled
= yesnotoi(argv
[1])) == -1) {
1514 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1516 } else if (!strcasecmp(argv
[0],"vm-max-memory") && argc
== 2) {
1517 server
.vm_max_memory
= strtoll(argv
[1], NULL
, 10);
1518 } else if (!strcasecmp(argv
[0],"vm-page-size") && argc
== 2) {
1519 server
.vm_page_size
= strtoll(argv
[1], NULL
, 10);
1520 } else if (!strcasecmp(argv
[0],"vm-pages") && argc
== 2) {
1521 server
.vm_pages
= strtoll(argv
[1], NULL
, 10);
1523 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
1525 for (j
= 0; j
< argc
; j
++)
1530 if (fp
!= stdin
) fclose(fp
);
1534 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
1535 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
1536 fprintf(stderr
, ">>> '%s'\n", line
);
1537 fprintf(stderr
, "%s\n", err
);
1541 static void freeClientArgv(redisClient
*c
) {
1544 for (j
= 0; j
< c
->argc
; j
++)
1545 decrRefCount(c
->argv
[j
]);
1546 for (j
= 0; j
< c
->mbargc
; j
++)
1547 decrRefCount(c
->mbargv
[j
]);
1552 static void freeClient(redisClient
*c
) {
1555 /* Note that if the client we are freeing is blocked into a blocking
1556 * call, we have to set querybuf to NULL *before* to call unblockClient()
1557 * to avoid processInputBuffer() will get called. Also it is important
1558 * to remove the file events after this, because this call adds
1559 * the READABLE event. */
1560 sdsfree(c
->querybuf
);
1562 if (c
->flags
& REDIS_BLOCKED
)
1565 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
1566 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1567 listRelease(c
->reply
);
1570 ln
= listSearchKey(server
.clients
,c
);
1571 redisAssert(ln
!= NULL
);
1572 listDelNode(server
.clients
,ln
);
1573 if (c
->flags
& REDIS_SLAVE
) {
1574 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
1576 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
1577 ln
= listSearchKey(l
,c
);
1578 redisAssert(ln
!= NULL
);
1581 if (c
->flags
& REDIS_MASTER
) {
1582 server
.master
= NULL
;
1583 server
.replstate
= REDIS_REPL_CONNECT
;
1587 freeClientMultiState(c
);
1591 #define GLUEREPLY_UP_TO (1024)
1592 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
1594 char buf
[GLUEREPLY_UP_TO
];
1598 listRewind(c
->reply
);
1599 while((ln
= listYield(c
->reply
))) {
1603 objlen
= sdslen(o
->ptr
);
1604 if (copylen
+ objlen
<= GLUEREPLY_UP_TO
) {
1605 memcpy(buf
+copylen
,o
->ptr
,objlen
);
1607 listDelNode(c
->reply
,ln
);
1609 if (copylen
== 0) return;
1613 /* Now the output buffer is empty, add the new single element */
1614 o
= createObject(REDIS_STRING
,sdsnewlen(buf
,copylen
));
1615 listAddNodeHead(c
->reply
,o
);
1618 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1619 redisClient
*c
= privdata
;
1620 int nwritten
= 0, totwritten
= 0, objlen
;
1623 REDIS_NOTUSED(mask
);
1625 /* Use writev() if we have enough buffers to send */
1626 if (!server
.glueoutputbuf
&&
1627 listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD
&&
1628 !(c
->flags
& REDIS_MASTER
))
1630 sendReplyToClientWritev(el
, fd
, privdata
, mask
);
1634 while(listLength(c
->reply
)) {
1635 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
1636 glueReplyBuffersIfNeeded(c
);
1638 o
= listNodeValue(listFirst(c
->reply
));
1639 objlen
= sdslen(o
->ptr
);
1642 listDelNode(c
->reply
,listFirst(c
->reply
));
1646 if (c
->flags
& REDIS_MASTER
) {
1647 /* Don't reply to a master */
1648 nwritten
= objlen
- c
->sentlen
;
1650 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
1651 if (nwritten
<= 0) break;
1653 c
->sentlen
+= nwritten
;
1654 totwritten
+= nwritten
;
1655 /* If we fully sent the object on head go to the next one */
1656 if (c
->sentlen
== objlen
) {
1657 listDelNode(c
->reply
,listFirst(c
->reply
));
1660 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
1661 * bytes, in a single threaded server it's a good idea to serve
1662 * other clients as well, even if a very large request comes from
1663 * super fast link that is always able to accept data (in real world
1664 * scenario think about 'KEYS *' against the loopback interfae) */
1665 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
1667 if (nwritten
== -1) {
1668 if (errno
== EAGAIN
) {
1671 redisLog(REDIS_DEBUG
,
1672 "Error writing to client: %s", strerror(errno
));
1677 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
1678 if (listLength(c
->reply
) == 0) {
1680 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1684 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
)
1686 redisClient
*c
= privdata
;
1687 int nwritten
= 0, totwritten
= 0, objlen
, willwrite
;
1689 struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
];
1690 int offset
, ion
= 0;
1692 REDIS_NOTUSED(mask
);
1695 while (listLength(c
->reply
)) {
1696 offset
= c
->sentlen
;
1700 /* fill-in the iov[] array */
1701 for(node
= listFirst(c
->reply
); node
; node
= listNextNode(node
)) {
1702 o
= listNodeValue(node
);
1703 objlen
= sdslen(o
->ptr
);
1705 if (totwritten
+ objlen
- offset
> REDIS_MAX_WRITE_PER_EVENT
)
1708 if(ion
== REDIS_WRITEV_IOVEC_COUNT
)
1709 break; /* no more iovecs */
1711 iov
[ion
].iov_base
= ((char*)o
->ptr
) + offset
;
1712 iov
[ion
].iov_len
= objlen
- offset
;
1713 willwrite
+= objlen
- offset
;
1714 offset
= 0; /* just for the first item */
1721 /* write all collected blocks at once */
1722 if((nwritten
= writev(fd
, iov
, ion
)) < 0) {
1723 if (errno
!= EAGAIN
) {
1724 redisLog(REDIS_DEBUG
,
1725 "Error writing to client: %s", strerror(errno
));
1732 totwritten
+= nwritten
;
1733 offset
= c
->sentlen
;
1735 /* remove written robjs from c->reply */
1736 while (nwritten
&& listLength(c
->reply
)) {
1737 o
= listNodeValue(listFirst(c
->reply
));
1738 objlen
= sdslen(o
->ptr
);
1740 if(nwritten
>= objlen
- offset
) {
1741 listDelNode(c
->reply
, listFirst(c
->reply
));
1742 nwritten
-= objlen
- offset
;
1746 c
->sentlen
+= nwritten
;
1754 c
->lastinteraction
= time(NULL
);
1756 if (listLength(c
->reply
) == 0) {
1758 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1762 static struct redisCommand
*lookupCommand(char *name
) {
1764 while(cmdTable
[j
].name
!= NULL
) {
1765 if (!strcasecmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
1771 /* resetClient prepare the client to process the next command */
1772 static void resetClient(redisClient
*c
) {
1778 /* Call() is the core of Redis execution of a command */
1779 static void call(redisClient
*c
, struct redisCommand
*cmd
) {
1782 dirty
= server
.dirty
;
1784 if (server
.appendonly
&& server
.dirty
-dirty
)
1785 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1786 if (server
.dirty
-dirty
&& listLength(server
.slaves
))
1787 replicationFeedSlaves(server
.slaves
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1788 if (listLength(server
.monitors
))
1789 replicationFeedSlaves(server
.monitors
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1790 server
.stat_numcommands
++;
1793 /* If this function gets called we already read a whole
1794 * command, argments are in the client argv/argc fields.
1795 * processCommand() execute the command or prepare the
1796 * server for a bulk read from the client.
1798 * If 1 is returned the client is still alive and valid and
1799 * and other operations can be performed by the caller. Otherwise
1800 * if 0 is returned the client was destroied (i.e. after QUIT). */
1801 static int processCommand(redisClient
*c
) {
1802 struct redisCommand
*cmd
;
1804 /* Free some memory if needed (maxmemory setting) */
1805 if (server
.maxmemory
) freeMemoryIfNeeded();
1807 /* Handle the multi bulk command type. This is an alternative protocol
1808 * supported by Redis in order to receive commands that are composed of
1809 * multiple binary-safe "bulk" arguments. The latency of processing is
1810 * a bit higher but this allows things like multi-sets, so if this
1811 * protocol is used only for MSET and similar commands this is a big win. */
1812 if (c
->multibulk
== 0 && c
->argc
== 1 && ((char*)(c
->argv
[0]->ptr
))[0] == '*') {
1813 c
->multibulk
= atoi(((char*)c
->argv
[0]->ptr
)+1);
1814 if (c
->multibulk
<= 0) {
1818 decrRefCount(c
->argv
[c
->argc
-1]);
1822 } else if (c
->multibulk
) {
1823 if (c
->bulklen
== -1) {
1824 if (((char*)c
->argv
[0]->ptr
)[0] != '$') {
1825 addReplySds(c
,sdsnew("-ERR multi bulk protocol error\r\n"));
1829 int bulklen
= atoi(((char*)c
->argv
[0]->ptr
)+1);
1830 decrRefCount(c
->argv
[0]);
1831 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1833 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1838 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1842 c
->mbargv
= zrealloc(c
->mbargv
,(sizeof(robj
*))*(c
->mbargc
+1));
1843 c
->mbargv
[c
->mbargc
] = c
->argv
[0];
1847 if (c
->multibulk
== 0) {
1851 /* Here we need to swap the multi-bulk argc/argv with the
1852 * normal argc/argv of the client structure. */
1854 c
->argv
= c
->mbargv
;
1855 c
->mbargv
= auxargv
;
1858 c
->argc
= c
->mbargc
;
1859 c
->mbargc
= auxargc
;
1861 /* We need to set bulklen to something different than -1
1862 * in order for the code below to process the command without
1863 * to try to read the last argument of a bulk command as
1864 * a special argument. */
1866 /* continue below and process the command */
1873 /* -- end of multi bulk commands processing -- */
1875 /* The QUIT command is handled as a special case. Normal command
1876 * procs are unable to close the client connection safely */
1877 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
1881 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1884 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
1885 (char*)c
->argv
[0]->ptr
));
1888 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
1889 (c
->argc
< -cmd
->arity
)) {
1891 sdscatprintf(sdsempty(),
1892 "-ERR wrong number of arguments for '%s' command\r\n",
1896 } else if (server
.maxmemory
&& cmd
->flags
& REDIS_CMD_DENYOOM
&& zmalloc_used_memory() > server
.maxmemory
) {
1897 addReplySds(c
,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
1900 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
1901 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
1903 decrRefCount(c
->argv
[c
->argc
-1]);
1904 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1906 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1911 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1912 /* It is possible that the bulk read is already in the
1913 * buffer. Check this condition and handle it accordingly.
1914 * This is just a fast path, alternative to call processInputBuffer().
1915 * It's a good idea since the code is small and this condition
1916 * happens most of the times. */
1917 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
1918 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
1920 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
1925 /* Let's try to share objects on the command arguments vector */
1926 if (server
.shareobjects
) {
1928 for(j
= 1; j
< c
->argc
; j
++)
1929 c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]);
1931 /* Let's try to encode the bulk object to save space. */
1932 if (cmd
->flags
& REDIS_CMD_BULK
)
1933 tryObjectEncoding(c
->argv
[c
->argc
-1]);
1935 /* Check if the user is authenticated */
1936 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
1937 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
1942 /* Exec the command */
1943 if (c
->flags
& REDIS_MULTI
&& cmd
->proc
!= execCommand
) {
1944 queueMultiCommand(c
,cmd
);
1945 addReply(c
,shared
.queued
);
1950 /* Prepare the client for the next command */
1951 if (c
->flags
& REDIS_CLOSE
) {
1959 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
1963 /* (args*2)+1 is enough room for args, spaces, newlines */
1964 robj
*static_outv
[REDIS_STATIC_ARGS
*2+1];
1966 if (argc
<= REDIS_STATIC_ARGS
) {
1969 outv
= zmalloc(sizeof(robj
*)*(argc
*2+1));
1972 for (j
= 0; j
< argc
; j
++) {
1973 if (j
!= 0) outv
[outc
++] = shared
.space
;
1974 if ((cmd
->flags
& REDIS_CMD_BULK
) && j
== argc
-1) {
1977 lenobj
= createObject(REDIS_STRING
,
1978 sdscatprintf(sdsempty(),"%lu\r\n",
1979 (unsigned long) stringObjectLen(argv
[j
])));
1980 lenobj
->refcount
= 0;
1981 outv
[outc
++] = lenobj
;
1983 outv
[outc
++] = argv
[j
];
1985 outv
[outc
++] = shared
.crlf
;
1987 /* Increment all the refcounts at start and decrement at end in order to
1988 * be sure to free objects if there is no slave in a replication state
1989 * able to be feed with commands */
1990 for (j
= 0; j
< outc
; j
++) incrRefCount(outv
[j
]);
1992 while((ln
= listYield(slaves
))) {
1993 redisClient
*slave
= ln
->value
;
1995 /* Don't feed slaves that are still waiting for BGSAVE to start */
1996 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) continue;
1998 /* Feed all the other slaves, MONITORs and so on */
1999 if (slave
->slaveseldb
!= dictid
) {
2003 case 0: selectcmd
= shared
.select0
; break;
2004 case 1: selectcmd
= shared
.select1
; break;
2005 case 2: selectcmd
= shared
.select2
; break;
2006 case 3: selectcmd
= shared
.select3
; break;
2007 case 4: selectcmd
= shared
.select4
; break;
2008 case 5: selectcmd
= shared
.select5
; break;
2009 case 6: selectcmd
= shared
.select6
; break;
2010 case 7: selectcmd
= shared
.select7
; break;
2011 case 8: selectcmd
= shared
.select8
; break;
2012 case 9: selectcmd
= shared
.select9
; break;
2014 selectcmd
= createObject(REDIS_STRING
,
2015 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
2016 selectcmd
->refcount
= 0;
2019 addReply(slave
,selectcmd
);
2020 slave
->slaveseldb
= dictid
;
2022 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
2024 for (j
= 0; j
< outc
; j
++) decrRefCount(outv
[j
]);
2025 if (outv
!= static_outv
) zfree(outv
);
2028 static void processInputBuffer(redisClient
*c
) {
2030 /* Before to process the input buffer, make sure the client is not
2031 * waitig for a blocking operation such as BLPOP. Note that the first
2032 * iteration the client is never blocked, otherwise the processInputBuffer
2033 * would not be called at all, but after the execution of the first commands
2034 * in the input buffer the client may be blocked, and the "goto again"
2035 * will try to reiterate. The following line will make it return asap. */
2036 if (c
->flags
& REDIS_BLOCKED
) return;
2037 if (c
->bulklen
== -1) {
2038 /* Read the first line of the query */
2039 char *p
= strchr(c
->querybuf
,'\n');
2046 query
= c
->querybuf
;
2047 c
->querybuf
= sdsempty();
2048 querylen
= 1+(p
-(query
));
2049 if (sdslen(query
) > querylen
) {
2050 /* leave data after the first line of the query in the buffer */
2051 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
2053 *p
= '\0'; /* remove "\n" */
2054 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
2055 sdsupdatelen(query
);
2057 /* Now we can split the query in arguments */
2058 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
2061 if (c
->argv
) zfree(c
->argv
);
2062 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
2064 for (j
= 0; j
< argc
; j
++) {
2065 if (sdslen(argv
[j
])) {
2066 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
2074 /* Execute the command. If the client is still valid
2075 * after processCommand() return and there is something
2076 * on the query buffer try to process the next command. */
2077 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2079 /* Nothing to process, argc == 0. Just process the query
2080 * buffer if it's not empty or return to the caller */
2081 if (sdslen(c
->querybuf
)) goto again
;
2084 } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) {
2085 redisLog(REDIS_DEBUG
, "Client protocol error");
2090 /* Bulk read handling. Note that if we are at this point
2091 the client already sent a command terminated with a newline,
2092 we are reading the bulk data that is actually the last
2093 argument of the command. */
2094 int qbl
= sdslen(c
->querybuf
);
2096 if (c
->bulklen
<= qbl
) {
2097 /* Copy everything but the final CRLF as final argument */
2098 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2100 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2101 /* Process the command. If the client is still valid after
2102 * the processing and there is more data in the buffer
2103 * try to parse it. */
2104 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2110 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2111 redisClient
*c
= (redisClient
*) privdata
;
2112 char buf
[REDIS_IOBUF_LEN
];
2115 REDIS_NOTUSED(mask
);
2117 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
2119 if (errno
== EAGAIN
) {
2122 redisLog(REDIS_DEBUG
, "Reading from client: %s",strerror(errno
));
2126 } else if (nread
== 0) {
2127 redisLog(REDIS_DEBUG
, "Client closed connection");
2132 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
2133 c
->lastinteraction
= time(NULL
);
2137 processInputBuffer(c
);
2140 static int selectDb(redisClient
*c
, int id
) {
2141 if (id
< 0 || id
>= server
.dbnum
)
2143 c
->db
= &server
.db
[id
];
2147 static void *dupClientReplyValue(void *o
) {
2148 incrRefCount((robj
*)o
);
2152 static redisClient
*createClient(int fd
) {
2153 redisClient
*c
= zmalloc(sizeof(*c
));
2155 anetNonBlock(NULL
,fd
);
2156 anetTcpNoDelay(NULL
,fd
);
2157 if (!c
) return NULL
;
2160 c
->querybuf
= sdsempty();
2169 c
->lastinteraction
= time(NULL
);
2170 c
->authenticated
= 0;
2171 c
->replstate
= REDIS_REPL_NONE
;
2172 c
->reply
= listCreate();
2173 c
->blockingkeys
= NULL
;
2174 c
->blockingkeysnum
= 0;
2175 listSetFreeMethod(c
->reply
,decrRefCount
);
2176 listSetDupMethod(c
->reply
,dupClientReplyValue
);
2177 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
2178 readQueryFromClient
, c
) == AE_ERR
) {
2182 listAddNodeTail(server
.clients
,c
);
2183 initClientMultiState(c
);
2187 static void addReply(redisClient
*c
, robj
*obj
) {
2188 if (listLength(c
->reply
) == 0 &&
2189 (c
->replstate
== REDIS_REPL_NONE
||
2190 c
->replstate
== REDIS_REPL_ONLINE
) &&
2191 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
2192 sendReplyToClient
, c
) == AE_ERR
) return;
2193 listAddNodeTail(c
->reply
,getDecodedObject(obj
));
2196 static void addReplySds(redisClient
*c
, sds s
) {
2197 robj
*o
= createObject(REDIS_STRING
,s
);
2202 static void addReplyDouble(redisClient
*c
, double d
) {
2205 snprintf(buf
,sizeof(buf
),"%.17g",d
);
2206 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2207 (unsigned long) strlen(buf
),buf
));
2210 static void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
2213 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
2214 len
= sdslen(obj
->ptr
);
2216 long n
= (long)obj
->ptr
;
2218 /* Compute how many bytes will take this integer as a radix 10 string */
2224 while((n
= n
/10) != 0) {
2228 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",(unsigned long)len
));
2231 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2236 REDIS_NOTUSED(mask
);
2237 REDIS_NOTUSED(privdata
);
2239 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
2240 if (cfd
== AE_ERR
) {
2241 redisLog(REDIS_DEBUG
,"Accepting client connection: %s", server
.neterr
);
2244 redisLog(REDIS_DEBUG
,"Accepted %s:%d", cip
, cport
);
2245 if ((c
= createClient(cfd
)) == NULL
) {
2246 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
2247 close(cfd
); /* May be already closed, just ingore errors */
2250 /* If maxclient directive is set and this is one client more... close the
2251 * connection. Note that we create the client instead to check before
2252 * for this condition, since now the socket is already set in nonblocking
2253 * mode and we can send an error for free using the Kernel I/O */
2254 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
2255 char *err
= "-ERR max number of clients reached\r\n";
2257 /* That's a best effort error message, don't check write errors */
2258 if (write(c
->fd
,err
,strlen(err
)) == -1) {
2259 /* Nothing to do, Just to avoid the warning... */
2264 server
.stat_numconnections
++;
2267 /* ======================= Redis objects implementation ===================== */
2269 static robj
*createObject(int type
, void *ptr
) {
2272 if (listLength(server
.objfreelist
)) {
2273 listNode
*head
= listFirst(server
.objfreelist
);
2274 o
= listNodeValue(head
);
2275 listDelNode(server
.objfreelist
,head
);
2277 if (server
.vm_enabled
) {
2278 o
= zmalloc(sizeof(*o
));
2280 o
= zmalloc(sizeof(*o
)-sizeof(struct redisObjectVM
));
2284 o
->encoding
= REDIS_ENCODING_RAW
;
2287 if (server
.vm_enabled
) {
2288 o
->vm
.atime
= server
.unixtime
;
2289 o
->storage
= REDIS_VM_MEMORY
;
2294 static robj
*createStringObject(char *ptr
, size_t len
) {
2295 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
2298 static robj
*dupStringObject(robj
*o
) {
2299 return createStringObject(o
->ptr
,sdslen(o
->ptr
));
2302 static robj
*createListObject(void) {
2303 list
*l
= listCreate();
2305 listSetFreeMethod(l
,decrRefCount
);
2306 return createObject(REDIS_LIST
,l
);
2309 static robj
*createSetObject(void) {
2310 dict
*d
= dictCreate(&setDictType
,NULL
);
2311 return createObject(REDIS_SET
,d
);
2314 static robj
*createZsetObject(void) {
2315 zset
*zs
= zmalloc(sizeof(*zs
));
2317 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
2318 zs
->zsl
= zslCreate();
2319 return createObject(REDIS_ZSET
,zs
);
2322 static void freeStringObject(robj
*o
) {
2323 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2328 static void freeListObject(robj
*o
) {
2329 listRelease((list
*) o
->ptr
);
2332 static void freeSetObject(robj
*o
) {
2333 dictRelease((dict
*) o
->ptr
);
2336 static void freeZsetObject(robj
*o
) {
2339 dictRelease(zs
->dict
);
2344 static void freeHashObject(robj
*o
) {
2345 dictRelease((dict
*) o
->ptr
);
2348 static void incrRefCount(robj
*o
) {
2349 assert(!server
.vm_enabled
|| o
->storage
== REDIS_VM_MEMORY
);
2353 static void decrRefCount(void *obj
) {
2356 /* REDIS_VM_SWAPPED */
2357 if (server
.vm_enabled
&& o
->storage
== REDIS_VM_SWAPPED
) {
2358 assert(o
->refcount
== 1);
2359 assert(o
->type
== REDIS_STRING
);
2360 freeStringObject(o
);
2361 vmMarkPagesFree(o
->vm
.page
,o
->vm
.usedpages
);
2362 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2363 !listAddNodeHead(server
.objfreelist
,o
))
2367 /* REDIS_VM_MEMORY */
2368 if (--(o
->refcount
) == 0) {
2370 case REDIS_STRING
: freeStringObject(o
); break;
2371 case REDIS_LIST
: freeListObject(o
); break;
2372 case REDIS_SET
: freeSetObject(o
); break;
2373 case REDIS_ZSET
: freeZsetObject(o
); break;
2374 case REDIS_HASH
: freeHashObject(o
); break;
2375 default: redisAssert(0 != 0); break;
2377 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2378 !listAddNodeHead(server
.objfreelist
,o
))
2383 static robj
*lookupKey(redisDb
*db
, robj
*key
) {
2384 dictEntry
*de
= dictFind(db
->dict
,key
);
2386 robj
*key
= dictGetEntryKey(de
);
2387 robj
*val
= dictGetEntryVal(de
);
2389 if (server
.vm_enabled
) {
2390 if (key
->storage
== REDIS_VM_MEMORY
) {
2391 /* Update the access time of the key for the aging algorithm. */
2392 key
->vm
.atime
= server
.unixtime
;
2394 /* Our value was swapped on disk. Bring it at home. */
2395 assert(val
== NULL
);
2396 val
= vmLoadObject(key
);
2397 dictGetEntryVal(de
) = val
;
2406 static robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
2407 expireIfNeeded(db
,key
);
2408 return lookupKey(db
,key
);
2411 static robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
2412 deleteIfVolatile(db
,key
);
2413 return lookupKey(db
,key
);
2416 static int deleteKey(redisDb
*db
, robj
*key
) {
2419 /* We need to protect key from destruction: after the first dictDelete()
2420 * it may happen that 'key' is no longer valid if we don't increment
2421 * it's count. This may happen when we get the object reference directly
2422 * from the hash table with dictRandomKey() or dict iterators */
2424 if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
);
2425 retval
= dictDelete(db
->dict
,key
);
2428 return retval
== DICT_OK
;
2431 /* Try to share an object against the shared objects pool */
2432 static robj
*tryObjectSharing(robj
*o
) {
2433 struct dictEntry
*de
;
2436 if (o
== NULL
|| server
.shareobjects
== 0) return o
;
2438 redisAssert(o
->type
== REDIS_STRING
);
2439 de
= dictFind(server
.sharingpool
,o
);
2441 robj
*shared
= dictGetEntryKey(de
);
2443 c
= ((unsigned long) dictGetEntryVal(de
))+1;
2444 dictGetEntryVal(de
) = (void*) c
;
2445 incrRefCount(shared
);
2449 /* Here we are using a stream algorihtm: Every time an object is
2450 * shared we increment its count, everytime there is a miss we
2451 * recrement the counter of a random object. If this object reaches
2452 * zero we remove the object and put the current object instead. */
2453 if (dictSize(server
.sharingpool
) >=
2454 server
.sharingpoolsize
) {
2455 de
= dictGetRandomKey(server
.sharingpool
);
2456 redisAssert(de
!= NULL
);
2457 c
= ((unsigned long) dictGetEntryVal(de
))-1;
2458 dictGetEntryVal(de
) = (void*) c
;
2460 dictDelete(server
.sharingpool
,de
->key
);
2463 c
= 0; /* If the pool is empty we want to add this object */
2468 retval
= dictAdd(server
.sharingpool
,o
,(void*)1);
2469 redisAssert(retval
== DICT_OK
);
2476 /* Check if the nul-terminated string 's' can be represented by a long
2477 * (that is, is a number that fits into long without any other space or
2478 * character before or after the digits).
2480 * If so, the function returns REDIS_OK and *longval is set to the value
2481 * of the number. Otherwise REDIS_ERR is returned */
2482 static int isStringRepresentableAsLong(sds s
, long *longval
) {
2483 char buf
[32], *endptr
;
2487 value
= strtol(s
, &endptr
, 10);
2488 if (endptr
[0] != '\0') return REDIS_ERR
;
2489 slen
= snprintf(buf
,32,"%ld",value
);
2491 /* If the number converted back into a string is not identical
2492 * then it's not possible to encode the string as integer */
2493 if (sdslen(s
) != (unsigned)slen
|| memcmp(buf
,s
,slen
)) return REDIS_ERR
;
2494 if (longval
) *longval
= value
;
2498 /* Try to encode a string object in order to save space */
2499 static int tryObjectEncoding(robj
*o
) {
2503 if (o
->encoding
!= REDIS_ENCODING_RAW
)
2504 return REDIS_ERR
; /* Already encoded */
2506 /* It's not save to encode shared objects: shared objects can be shared
2507 * everywhere in the "object space" of Redis. Encoded objects can only
2508 * appear as "values" (and not, for instance, as keys) */
2509 if (o
->refcount
> 1) return REDIS_ERR
;
2511 /* Currently we try to encode only strings */
2512 redisAssert(o
->type
== REDIS_STRING
);
2514 /* Check if we can represent this string as a long integer */
2515 if (isStringRepresentableAsLong(s
,&value
) == REDIS_ERR
) return REDIS_ERR
;
2517 /* Ok, this object can be encoded */
2518 o
->encoding
= REDIS_ENCODING_INT
;
2520 o
->ptr
= (void*) value
;
2524 /* Get a decoded version of an encoded object (returned as a new object).
2525 * If the object is already raw-encoded just increment the ref count. */
2526 static robj
*getDecodedObject(robj
*o
) {
2529 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2533 if (o
->type
== REDIS_STRING
&& o
->encoding
== REDIS_ENCODING_INT
) {
2536 snprintf(buf
,32,"%ld",(long)o
->ptr
);
2537 dec
= createStringObject(buf
,strlen(buf
));
2540 redisAssert(1 != 1);
2544 /* Compare two string objects via strcmp() or alike.
2545 * Note that the objects may be integer-encoded. In such a case we
2546 * use snprintf() to get a string representation of the numbers on the stack
2547 * and compare the strings, it's much faster than calling getDecodedObject().
2549 * Important note: if objects are not integer encoded, but binary-safe strings,
2550 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
2552 static int compareStringObjects(robj
*a
, robj
*b
) {
2553 redisAssert(a
->type
== REDIS_STRING
&& b
->type
== REDIS_STRING
);
2554 char bufa
[128], bufb
[128], *astr
, *bstr
;
2557 if (a
== b
) return 0;
2558 if (a
->encoding
!= REDIS_ENCODING_RAW
) {
2559 snprintf(bufa
,sizeof(bufa
),"%ld",(long) a
->ptr
);
2565 if (b
->encoding
!= REDIS_ENCODING_RAW
) {
2566 snprintf(bufb
,sizeof(bufb
),"%ld",(long) b
->ptr
);
2572 return bothsds
? sdscmp(astr
,bstr
) : strcmp(astr
,bstr
);
2575 static size_t stringObjectLen(robj
*o
) {
2576 redisAssert(o
->type
== REDIS_STRING
);
2577 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2578 return sdslen(o
->ptr
);
2582 return snprintf(buf
,32,"%ld",(long)o
->ptr
);
2586 /*============================ RDB saving/loading =========================== */
2588 static int rdbSaveType(FILE *fp
, unsigned char type
) {
2589 if (fwrite(&type
,1,1,fp
) == 0) return -1;
2593 static int rdbSaveTime(FILE *fp
, time_t t
) {
2594 int32_t t32
= (int32_t) t
;
2595 if (fwrite(&t32
,4,1,fp
) == 0) return -1;
2599 /* check rdbLoadLen() comments for more info */
2600 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
2601 unsigned char buf
[2];
2604 /* Save a 6 bit len */
2605 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
2606 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2607 } else if (len
< (1<<14)) {
2608 /* Save a 14 bit len */
2609 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
2611 if (fwrite(buf
,2,1,fp
) == 0) return -1;
2613 /* Save a 32 bit len */
2614 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
2615 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2617 if (fwrite(&len
,4,1,fp
) == 0) return -1;
2622 /* String objects in the form "2391" "-100" without any space and with a
2623 * range of values that can fit in an 8, 16 or 32 bit signed value can be
2624 * encoded as integers to save space */
2625 static int rdbTryIntegerEncoding(sds s
, unsigned char *enc
) {
2627 char *endptr
, buf
[32];
2629 /* Check if it's possible to encode this value as a number */
2630 value
= strtoll(s
, &endptr
, 10);
2631 if (endptr
[0] != '\0') return 0;
2632 snprintf(buf
,32,"%lld",value
);
2634 /* If the number converted back into a string is not identical
2635 * then it's not possible to encode the string as integer */
2636 if (strlen(buf
) != sdslen(s
) || memcmp(buf
,s
,sdslen(s
))) return 0;
2638 /* Finally check if it fits in our ranges */
2639 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
2640 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
2641 enc
[1] = value
&0xFF;
2643 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
2644 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
2645 enc
[1] = value
&0xFF;
2646 enc
[2] = (value
>>8)&0xFF;
2648 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
2649 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
2650 enc
[1] = value
&0xFF;
2651 enc
[2] = (value
>>8)&0xFF;
2652 enc
[3] = (value
>>16)&0xFF;
2653 enc
[4] = (value
>>24)&0xFF;
2660 static int rdbSaveLzfStringObject(FILE *fp
, robj
*obj
) {
2661 unsigned int comprlen
, outlen
;
2665 /* We require at least four bytes compression for this to be worth it */
2666 outlen
= sdslen(obj
->ptr
)-4;
2667 if (outlen
<= 0) return 0;
2668 if ((out
= zmalloc(outlen
+1)) == NULL
) return 0;
2669 comprlen
= lzf_compress(obj
->ptr
, sdslen(obj
->ptr
), out
, outlen
);
2670 if (comprlen
== 0) {
2674 /* Data compressed! Let's save it on disk */
2675 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
2676 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
2677 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
2678 if (rdbSaveLen(fp
,sdslen(obj
->ptr
)) == -1) goto writeerr
;
2679 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
2688 /* Save a string objet as [len][data] on disk. If the object is a string
2689 * representation of an integer value we try to safe it in a special form */
2690 static int rdbSaveStringObjectRaw(FILE *fp
, robj
*obj
) {
2694 len
= sdslen(obj
->ptr
);
2696 /* Try integer encoding */
2698 unsigned char buf
[5];
2699 if ((enclen
= rdbTryIntegerEncoding(obj
->ptr
,buf
)) > 0) {
2700 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
2705 /* Try LZF compression - under 20 bytes it's unable to compress even
2706 * aaaaaaaaaaaaaaaaaa so skip it */
2707 if (server
.rdbcompression
&& len
> 20) {
2710 retval
= rdbSaveLzfStringObject(fp
,obj
);
2711 if (retval
== -1) return -1;
2712 if (retval
> 0) return 0;
2713 /* retval == 0 means data can't be compressed, save the old way */
2716 /* Store verbatim */
2717 if (rdbSaveLen(fp
,len
) == -1) return -1;
2718 if (len
&& fwrite(obj
->ptr
,len
,1,fp
) == 0) return -1;
2722 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
2723 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
2726 obj
= getDecodedObject(obj
);
2727 retval
= rdbSaveStringObjectRaw(fp
,obj
);
2732 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
2733 * 8 bit integer specifing the length of the representation.
2734 * This 8 bit integer has special values in order to specify the following
2740 static int rdbSaveDoubleValue(FILE *fp
, double val
) {
2741 unsigned char buf
[128];
2747 } else if (!isfinite(val
)) {
2749 buf
[0] = (val
< 0) ? 255 : 254;
2751 snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
);
2752 buf
[0] = strlen((char*)buf
+1);
2755 if (fwrite(buf
,len
,1,fp
) == 0) return -1;
2759 /* Save a Redis object. */
2760 static int rdbSaveObject(FILE *fp
, robj
*o
) {
2761 if (o
->type
== REDIS_STRING
) {
2762 /* Save a string value */
2763 if (rdbSaveStringObject(fp
,o
) == -1) return -1;
2764 } else if (o
->type
== REDIS_LIST
) {
2765 /* Save a list value */
2766 list
*list
= o
->ptr
;
2770 if (rdbSaveLen(fp
,listLength(list
)) == -1) return -1;
2771 while((ln
= listYield(list
))) {
2772 robj
*eleobj
= listNodeValue(ln
);
2774 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2776 } else if (o
->type
== REDIS_SET
) {
2777 /* Save a set value */
2779 dictIterator
*di
= dictGetIterator(set
);
2782 if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1;
2783 while((de
= dictNext(di
)) != NULL
) {
2784 robj
*eleobj
= dictGetEntryKey(de
);
2786 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2788 dictReleaseIterator(di
);
2789 } else if (o
->type
== REDIS_ZSET
) {
2790 /* Save a set value */
2792 dictIterator
*di
= dictGetIterator(zs
->dict
);
2795 if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1;
2796 while((de
= dictNext(di
)) != NULL
) {
2797 robj
*eleobj
= dictGetEntryKey(de
);
2798 double *score
= dictGetEntryVal(de
);
2800 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2801 if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1;
2803 dictReleaseIterator(di
);
2805 redisAssert(0 != 0);
2810 /* Return the length the object will have on disk if saved with
2811 * the rdbSaveObject() function. Currently we use a trick to get
2812 * this length with very little changes to the code. In the future
2813 * we could switch to a faster solution. */
2814 static off_t
rdbSavedObjectLen(robj
*o
) {
2815 static FILE *fp
= NULL
;
2817 if (fp
== NULL
) fp
= fopen("/dev/null","w");
2821 assert(rdbSaveObject(fp
,o
) != 1);
2825 /* Return the number of pages required to save this object in the swap file */
2826 static off_t
rdbSavedObjectPages(robj
*o
) {
2827 off_t bytes
= rdbSavedObjectLen(o
);
2829 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
2832 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
2833 static int rdbSave(char *filename
) {
2834 dictIterator
*di
= NULL
;
2839 time_t now
= time(NULL
);
2841 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
2842 fp
= fopen(tmpfile
,"w");
2844 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
2847 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
2848 for (j
= 0; j
< server
.dbnum
; j
++) {
2849 redisDb
*db
= server
.db
+j
;
2851 if (dictSize(d
) == 0) continue;
2852 di
= dictGetIterator(d
);
2858 /* Write the SELECT DB opcode */
2859 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
2860 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
2862 /* Iterate this DB writing every entry */
2863 while((de
= dictNext(di
)) != NULL
) {
2864 robj
*key
= dictGetEntryKey(de
);
2865 robj
*o
= dictGetEntryVal(de
);
2866 time_t expiretime
= getExpire(db
,key
);
2868 /* Save the expire time */
2869 if (expiretime
!= -1) {
2870 /* If this key is already expired skip it */
2871 if (expiretime
< now
) continue;
2872 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
2873 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
2875 /* Save the key and associated value */
2876 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
2877 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
2878 /* Save the actual value */
2879 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
2881 dictReleaseIterator(di
);
2884 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
2886 /* Make sure data will not remain on the OS's output buffers */
2891 /* Use RENAME to make sure the DB file is changed atomically only
2892 * if the generate DB file is ok. */
2893 if (rename(tmpfile
,filename
) == -1) {
2894 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
2898 redisLog(REDIS_NOTICE
,"DB saved on disk");
2900 server
.lastsave
= time(NULL
);
2906 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
2907 if (di
) dictReleaseIterator(di
);
2911 static int rdbSaveBackground(char *filename
) {
2914 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
2915 if ((childpid
= fork()) == 0) {
2918 if (rdbSave(filename
) == REDIS_OK
) {
2925 if (childpid
== -1) {
2926 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
2930 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
2931 server
.bgsavechildpid
= childpid
;
2934 return REDIS_OK
; /* unreached */
2937 static void rdbRemoveTempFile(pid_t childpid
) {
2940 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
2944 static int rdbLoadType(FILE *fp
) {
2946 if (fread(&type
,1,1,fp
) == 0) return -1;
2950 static time_t rdbLoadTime(FILE *fp
) {
2952 if (fread(&t32
,4,1,fp
) == 0) return -1;
2953 return (time_t) t32
;
2956 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
2957 * of this file for a description of how this are stored on disk.
2959 * isencoded is set to 1 if the readed length is not actually a length but
2960 * an "encoding type", check the above comments for more info */
2961 static uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
2962 unsigned char buf
[2];
2966 if (isencoded
) *isencoded
= 0;
2967 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
2968 type
= (buf
[0]&0xC0)>>6;
2969 if (type
== REDIS_RDB_6BITLEN
) {
2970 /* Read a 6 bit len */
2972 } else if (type
== REDIS_RDB_ENCVAL
) {
2973 /* Read a 6 bit len encoding type */
2974 if (isencoded
) *isencoded
= 1;
2976 } else if (type
== REDIS_RDB_14BITLEN
) {
2977 /* Read a 14 bit len */
2978 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
2979 return ((buf
[0]&0x3F)<<8)|buf
[1];
2981 /* Read a 32 bit len */
2982 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
2987 static robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
) {
2988 unsigned char enc
[4];
2991 if (enctype
== REDIS_RDB_ENC_INT8
) {
2992 if (fread(enc
,1,1,fp
) == 0) return NULL
;
2993 val
= (signed char)enc
[0];
2994 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
2996 if (fread(enc
,2,1,fp
) == 0) return NULL
;
2997 v
= enc
[0]|(enc
[1]<<8);
2999 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
3001 if (fread(enc
,4,1,fp
) == 0) return NULL
;
3002 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
3005 val
= 0; /* anti-warning */
3008 return createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",val
));
3011 static robj
*rdbLoadLzfStringObject(FILE*fp
) {
3012 unsigned int len
, clen
;
3013 unsigned char *c
= NULL
;
3016 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3017 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3018 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
3019 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
3020 if (fread(c
,clen
,1,fp
) == 0) goto err
;
3021 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
3023 return createObject(REDIS_STRING
,val
);
3030 static robj
*rdbLoadStringObject(FILE*fp
) {
3035 len
= rdbLoadLen(fp
,&isencoded
);
3038 case REDIS_RDB_ENC_INT8
:
3039 case REDIS_RDB_ENC_INT16
:
3040 case REDIS_RDB_ENC_INT32
:
3041 return tryObjectSharing(rdbLoadIntegerObject(fp
,len
));
3042 case REDIS_RDB_ENC_LZF
:
3043 return tryObjectSharing(rdbLoadLzfStringObject(fp
));
3049 if (len
== REDIS_RDB_LENERR
) return NULL
;
3050 val
= sdsnewlen(NULL
,len
);
3051 if (len
&& fread(val
,len
,1,fp
) == 0) {
3055 return tryObjectSharing(createObject(REDIS_STRING
,val
));
3058 /* For information about double serialization check rdbSaveDoubleValue() */
3059 static int rdbLoadDoubleValue(FILE *fp
, double *val
) {
3063 if (fread(&len
,1,1,fp
) == 0) return -1;
3065 case 255: *val
= R_NegInf
; return 0;
3066 case 254: *val
= R_PosInf
; return 0;
3067 case 253: *val
= R_Nan
; return 0;
3069 if (fread(buf
,len
,1,fp
) == 0) return -1;
3071 sscanf(buf
, "%lg", val
);
3076 /* Load a Redis object of the specified type from the specified file.
3077 * On success a newly allocated object is returned, otherwise NULL. */
3078 static robj
*rdbLoadObject(int type
, FILE *fp
) {
3081 if (type
== REDIS_STRING
) {
3082 /* Read string value */
3083 if ((o
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3084 tryObjectEncoding(o
);
3085 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
3086 /* Read list/set value */
3089 if ((listlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3090 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
3091 /* Load every single element of the list/set */
3095 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3096 tryObjectEncoding(ele
);
3097 if (type
== REDIS_LIST
) {
3098 listAddNodeTail((list
*)o
->ptr
,ele
);
3100 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
3103 } else if (type
== REDIS_ZSET
) {
3104 /* Read list/set value */
3108 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3109 o
= createZsetObject();
3111 /* Load every single element of the list/set */
3114 double *score
= zmalloc(sizeof(double));
3116 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3117 tryObjectEncoding(ele
);
3118 if (rdbLoadDoubleValue(fp
,score
) == -1) return NULL
;
3119 dictAdd(zs
->dict
,ele
,score
);
3120 zslInsert(zs
->zsl
,*score
,ele
);
3121 incrRefCount(ele
); /* added to skiplist */
3124 redisAssert(0 != 0);
3129 static int rdbLoad(char *filename
) {
3131 robj
*keyobj
= NULL
;
3133 int type
, retval
, rdbver
;
3134 dict
*d
= server
.db
[0].dict
;
3135 redisDb
*db
= server
.db
+0;
3137 time_t expiretime
= -1, now
= time(NULL
);
3139 fp
= fopen(filename
,"r");
3140 if (!fp
) return REDIS_ERR
;
3141 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
3143 if (memcmp(buf
,"REDIS",5) != 0) {
3145 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
3148 rdbver
= atoi(buf
+5);
3151 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
3158 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3159 if (type
== REDIS_EXPIRETIME
) {
3160 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
3161 /* We read the time so we need to read the object type again */
3162 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3164 if (type
== REDIS_EOF
) break;
3165 /* Handle SELECT DB opcode as a special case */
3166 if (type
== REDIS_SELECTDB
) {
3167 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
3169 if (dbid
>= (unsigned)server
.dbnum
) {
3170 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
3173 db
= server
.db
+dbid
;
3178 if ((keyobj
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
3180 if ((o
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
3181 /* Add the new object in the hash table */
3182 retval
= dictAdd(d
,keyobj
,o
);
3183 if (retval
== DICT_ERR
) {
3184 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
3187 /* Set the expire time if needed */
3188 if (expiretime
!= -1) {
3189 setExpire(db
,keyobj
,expiretime
);
3190 /* Delete this key if already expired */
3191 if (expiretime
< now
) deleteKey(db
,keyobj
);
3199 eoferr
: /* unexpected end of file is handled here with a fatal exit */
3200 if (keyobj
) decrRefCount(keyobj
);
3201 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
3203 return REDIS_ERR
; /* Just to avoid warning */
3206 /*================================== Commands =============================== */
3208 static void authCommand(redisClient
*c
) {
3209 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
3210 c
->authenticated
= 1;
3211 addReply(c
,shared
.ok
);
3213 c
->authenticated
= 0;
3214 addReplySds(c
,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
3218 static void pingCommand(redisClient
*c
) {
3219 addReply(c
,shared
.pong
);
3222 static void echoCommand(redisClient
*c
) {
3223 addReplyBulkLen(c
,c
->argv
[1]);
3224 addReply(c
,c
->argv
[1]);
3225 addReply(c
,shared
.crlf
);
3228 /*=================================== Strings =============================== */
3230 static void setGenericCommand(redisClient
*c
, int nx
) {
3233 if (nx
) deleteIfVolatile(c
->db
,c
->argv
[1]);
3234 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3235 if (retval
== DICT_ERR
) {
3237 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3238 incrRefCount(c
->argv
[2]);
3240 addReply(c
,shared
.czero
);
3244 incrRefCount(c
->argv
[1]);
3245 incrRefCount(c
->argv
[2]);
3248 removeExpire(c
->db
,c
->argv
[1]);
3249 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3252 static void setCommand(redisClient
*c
) {
3253 setGenericCommand(c
,0);
3256 static void setnxCommand(redisClient
*c
) {
3257 setGenericCommand(c
,1);
3260 static int getGenericCommand(redisClient
*c
) {
3261 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3264 addReply(c
,shared
.nullbulk
);
3267 if (o
->type
!= REDIS_STRING
) {
3268 addReply(c
,shared
.wrongtypeerr
);
3271 addReplyBulkLen(c
,o
);
3273 addReply(c
,shared
.crlf
);
3279 static void getCommand(redisClient
*c
) {
3280 getGenericCommand(c
);
3283 static void getsetCommand(redisClient
*c
) {
3284 if (getGenericCommand(c
) == REDIS_ERR
) return;
3285 if (dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]) == DICT_ERR
) {
3286 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3288 incrRefCount(c
->argv
[1]);
3290 incrRefCount(c
->argv
[2]);
3292 removeExpire(c
->db
,c
->argv
[1]);
3295 static void mgetCommand(redisClient
*c
) {
3298 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
3299 for (j
= 1; j
< c
->argc
; j
++) {
3300 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[j
]);
3302 addReply(c
,shared
.nullbulk
);
3304 if (o
->type
!= REDIS_STRING
) {
3305 addReply(c
,shared
.nullbulk
);
3307 addReplyBulkLen(c
,o
);
3309 addReply(c
,shared
.crlf
);
3315 static void msetGenericCommand(redisClient
*c
, int nx
) {
3316 int j
, busykeys
= 0;
3318 if ((c
->argc
% 2) == 0) {
3319 addReplySds(c
,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
3322 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
3323 * set nothing at all if at least one already key exists. */
3325 for (j
= 1; j
< c
->argc
; j
+= 2) {
3326 if (lookupKeyWrite(c
->db
,c
->argv
[j
]) != NULL
) {
3332 addReply(c
, shared
.czero
);
3336 for (j
= 1; j
< c
->argc
; j
+= 2) {
3339 tryObjectEncoding(c
->argv
[j
+1]);
3340 retval
= dictAdd(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3341 if (retval
== DICT_ERR
) {
3342 dictReplace(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3343 incrRefCount(c
->argv
[j
+1]);
3345 incrRefCount(c
->argv
[j
]);
3346 incrRefCount(c
->argv
[j
+1]);
3348 removeExpire(c
->db
,c
->argv
[j
]);
3350 server
.dirty
+= (c
->argc
-1)/2;
3351 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3354 static void msetCommand(redisClient
*c
) {
3355 msetGenericCommand(c
,0);
3358 static void msetnxCommand(redisClient
*c
) {
3359 msetGenericCommand(c
,1);
3362 static void incrDecrCommand(redisClient
*c
, long long incr
) {
3367 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3371 if (o
->type
!= REDIS_STRING
) {
3376 if (o
->encoding
== REDIS_ENCODING_RAW
)
3377 value
= strtoll(o
->ptr
, &eptr
, 10);
3378 else if (o
->encoding
== REDIS_ENCODING_INT
)
3379 value
= (long)o
->ptr
;
3381 redisAssert(1 != 1);
3386 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
3387 tryObjectEncoding(o
);
3388 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],o
);
3389 if (retval
== DICT_ERR
) {
3390 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
3391 removeExpire(c
->db
,c
->argv
[1]);
3393 incrRefCount(c
->argv
[1]);
3396 addReply(c
,shared
.colon
);
3398 addReply(c
,shared
.crlf
);
3401 static void incrCommand(redisClient
*c
) {
3402 incrDecrCommand(c
,1);
3405 static void decrCommand(redisClient
*c
) {
3406 incrDecrCommand(c
,-1);
3409 static void incrbyCommand(redisClient
*c
) {
3410 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3411 incrDecrCommand(c
,incr
);
3414 static void decrbyCommand(redisClient
*c
) {
3415 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3416 incrDecrCommand(c
,-incr
);
3419 /* ========================= Type agnostic commands ========================= */
3421 static void delCommand(redisClient
*c
) {
3424 for (j
= 1; j
< c
->argc
; j
++) {
3425 if (deleteKey(c
->db
,c
->argv
[j
])) {
3432 addReply(c
,shared
.czero
);
3435 addReply(c
,shared
.cone
);
3438 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",deleted
));
3443 static void existsCommand(redisClient
*c
) {
3444 addReply(c
,lookupKeyRead(c
->db
,c
->argv
[1]) ? shared
.cone
: shared
.czero
);
3447 static void selectCommand(redisClient
*c
) {
3448 int id
= atoi(c
->argv
[1]->ptr
);
3450 if (selectDb(c
,id
) == REDIS_ERR
) {
3451 addReplySds(c
,sdsnew("-ERR invalid DB index\r\n"));
3453 addReply(c
,shared
.ok
);
3457 static void randomkeyCommand(redisClient
*c
) {
3461 de
= dictGetRandomKey(c
->db
->dict
);
3462 if (!de
|| expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break;
3465 addReply(c
,shared
.plus
);
3466 addReply(c
,shared
.crlf
);
3468 addReply(c
,shared
.plus
);
3469 addReply(c
,dictGetEntryKey(de
));
3470 addReply(c
,shared
.crlf
);
3474 static void keysCommand(redisClient
*c
) {
3477 sds pattern
= c
->argv
[1]->ptr
;
3478 int plen
= sdslen(pattern
);
3479 unsigned long numkeys
= 0, keyslen
= 0;
3480 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
3482 di
= dictGetIterator(c
->db
->dict
);
3484 decrRefCount(lenobj
);
3485 while((de
= dictNext(di
)) != NULL
) {
3486 robj
*keyobj
= dictGetEntryKey(de
);
3488 sds key
= keyobj
->ptr
;
3489 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
3490 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
3491 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
3493 addReply(c
,shared
.space
);
3496 keyslen
+= sdslen(key
);
3500 dictReleaseIterator(di
);
3501 lenobj
->ptr
= sdscatprintf(sdsempty(),"$%lu\r\n",keyslen
+(numkeys
? (numkeys
-1) : 0));
3502 addReply(c
,shared
.crlf
);
3505 static void dbsizeCommand(redisClient
*c
) {
3507 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
)));
3510 static void lastsaveCommand(redisClient
*c
) {
3512 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
3515 static void typeCommand(redisClient
*c
) {
3519 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3524 case REDIS_STRING
: type
= "+string"; break;
3525 case REDIS_LIST
: type
= "+list"; break;
3526 case REDIS_SET
: type
= "+set"; break;
3527 case REDIS_ZSET
: type
= "+zset"; break;
3528 default: type
= "unknown"; break;
3531 addReplySds(c
,sdsnew(type
));
3532 addReply(c
,shared
.crlf
);
3535 static void saveCommand(redisClient
*c
) {
3536 if (server
.bgsavechildpid
!= -1) {
3537 addReplySds(c
,sdsnew("-ERR background save in progress\r\n"));
3540 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
3541 addReply(c
,shared
.ok
);
3543 addReply(c
,shared
.err
);
3547 static void bgsaveCommand(redisClient
*c
) {
3548 if (server
.bgsavechildpid
!= -1) {
3549 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
3552 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
3553 char *status
= "+Background saving started\r\n";
3554 addReplySds(c
,sdsnew(status
));
3556 addReply(c
,shared
.err
);
3560 static void shutdownCommand(redisClient
*c
) {
3561 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
3562 /* Kill the saving child if there is a background saving in progress.
3563 We want to avoid race conditions, for instance our saving child may
3564 overwrite the synchronous saving did by SHUTDOWN. */
3565 if (server
.bgsavechildpid
!= -1) {
3566 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
3567 kill(server
.bgsavechildpid
,SIGKILL
);
3568 rdbRemoveTempFile(server
.bgsavechildpid
);
3570 if (server
.appendonly
) {
3571 /* Append only file: fsync() the AOF and exit */
3572 fsync(server
.appendfd
);
3575 /* Snapshotting. Perform a SYNC SAVE and exit */
3576 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
3577 if (server
.daemonize
)
3578 unlink(server
.pidfile
);
3579 redisLog(REDIS_WARNING
,"%zu bytes used at exit",zmalloc_used_memory());
3580 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
3583 /* Ooops.. error saving! The best we can do is to continue operating.
3584 * Note that if there was a background saving process, in the next
3585 * cron() Redis will be notified that the background saving aborted,
3586 * handling special stuff like slaves pending for synchronization... */
3587 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
3588 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
3593 static void renameGenericCommand(redisClient
*c
, int nx
) {
3596 /* To use the same key as src and dst is probably an error */
3597 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
3598 addReply(c
,shared
.sameobjecterr
);
3602 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3604 addReply(c
,shared
.nokeyerr
);
3608 deleteIfVolatile(c
->db
,c
->argv
[2]);
3609 if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
3612 addReply(c
,shared
.czero
);
3615 dictReplace(c
->db
->dict
,c
->argv
[2],o
);
3617 incrRefCount(c
->argv
[2]);
3619 deleteKey(c
->db
,c
->argv
[1]);
3621 addReply(c
,nx
? shared
.cone
: shared
.ok
);
3624 static void renameCommand(redisClient
*c
) {
3625 renameGenericCommand(c
,0);
3628 static void renamenxCommand(redisClient
*c
) {
3629 renameGenericCommand(c
,1);
3632 static void moveCommand(redisClient
*c
) {
3637 /* Obtain source and target DB pointers */
3640 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
3641 addReply(c
,shared
.outofrangeerr
);
3645 selectDb(c
,srcid
); /* Back to the source DB */
3647 /* If the user is moving using as target the same
3648 * DB as the source DB it is probably an error. */
3650 addReply(c
,shared
.sameobjecterr
);
3654 /* Check if the element exists and get a reference */
3655 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3657 addReply(c
,shared
.czero
);
3661 /* Try to add the element to the target DB */
3662 deleteIfVolatile(dst
,c
->argv
[1]);
3663 if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) {
3664 addReply(c
,shared
.czero
);
3667 incrRefCount(c
->argv
[1]);
3670 /* OK! key moved, free the entry in the source DB */
3671 deleteKey(src
,c
->argv
[1]);
3673 addReply(c
,shared
.cone
);
3676 /* =================================== Lists ================================ */
3677 static void pushGenericCommand(redisClient
*c
, int where
) {
3681 lobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3683 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
3684 addReply(c
,shared
.ok
);
3687 lobj
= createListObject();
3689 if (where
== REDIS_HEAD
) {
3690 listAddNodeHead(list
,c
->argv
[2]);
3692 listAddNodeTail(list
,c
->argv
[2]);
3694 dictAdd(c
->db
->dict
,c
->argv
[1],lobj
);
3695 incrRefCount(c
->argv
[1]);
3696 incrRefCount(c
->argv
[2]);
3698 if (lobj
->type
!= REDIS_LIST
) {
3699 addReply(c
,shared
.wrongtypeerr
);
3702 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
3703 addReply(c
,shared
.ok
);
3707 if (where
== REDIS_HEAD
) {
3708 listAddNodeHead(list
,c
->argv
[2]);
3710 listAddNodeTail(list
,c
->argv
[2]);
3712 incrRefCount(c
->argv
[2]);
3715 addReply(c
,shared
.ok
);
3718 static void lpushCommand(redisClient
*c
) {
3719 pushGenericCommand(c
,REDIS_HEAD
);
3722 static void rpushCommand(redisClient
*c
) {
3723 pushGenericCommand(c
,REDIS_TAIL
);
3726 static void llenCommand(redisClient
*c
) {
3730 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3732 addReply(c
,shared
.czero
);
3735 if (o
->type
!= REDIS_LIST
) {
3736 addReply(c
,shared
.wrongtypeerr
);
3739 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
)));
3744 static void lindexCommand(redisClient
*c
) {
3746 int index
= atoi(c
->argv
[2]->ptr
);
3748 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3750 addReply(c
,shared
.nullbulk
);
3752 if (o
->type
!= REDIS_LIST
) {
3753 addReply(c
,shared
.wrongtypeerr
);
3755 list
*list
= o
->ptr
;
3758 ln
= listIndex(list
, index
);
3760 addReply(c
,shared
.nullbulk
);
3762 robj
*ele
= listNodeValue(ln
);
3763 addReplyBulkLen(c
,ele
);
3765 addReply(c
,shared
.crlf
);
3771 static void lsetCommand(redisClient
*c
) {
3773 int index
= atoi(c
->argv
[2]->ptr
);
3775 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3777 addReply(c
,shared
.nokeyerr
);
3779 if (o
->type
!= REDIS_LIST
) {
3780 addReply(c
,shared
.wrongtypeerr
);
3782 list
*list
= o
->ptr
;
3785 ln
= listIndex(list
, index
);
3787 addReply(c
,shared
.outofrangeerr
);
3789 robj
*ele
= listNodeValue(ln
);
3792 listNodeValue(ln
) = c
->argv
[3];
3793 incrRefCount(c
->argv
[3]);
3794 addReply(c
,shared
.ok
);
3801 static void popGenericCommand(redisClient
*c
, int where
) {
3804 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3806 addReply(c
,shared
.nullbulk
);
3808 if (o
->type
!= REDIS_LIST
) {
3809 addReply(c
,shared
.wrongtypeerr
);
3811 list
*list
= o
->ptr
;
3814 if (where
== REDIS_HEAD
)
3815 ln
= listFirst(list
);
3817 ln
= listLast(list
);
3820 addReply(c
,shared
.nullbulk
);
3822 robj
*ele
= listNodeValue(ln
);
3823 addReplyBulkLen(c
,ele
);
3825 addReply(c
,shared
.crlf
);
3826 listDelNode(list
,ln
);
3833 static void lpopCommand(redisClient
*c
) {
3834 popGenericCommand(c
,REDIS_HEAD
);
3837 static void rpopCommand(redisClient
*c
) {
3838 popGenericCommand(c
,REDIS_TAIL
);
3841 static void lrangeCommand(redisClient
*c
) {
3843 int start
= atoi(c
->argv
[2]->ptr
);
3844 int end
= atoi(c
->argv
[3]->ptr
);
3846 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3848 addReply(c
,shared
.nullmultibulk
);
3850 if (o
->type
!= REDIS_LIST
) {
3851 addReply(c
,shared
.wrongtypeerr
);
3853 list
*list
= o
->ptr
;
3855 int llen
= listLength(list
);
3859 /* convert negative indexes */
3860 if (start
< 0) start
= llen
+start
;
3861 if (end
< 0) end
= llen
+end
;
3862 if (start
< 0) start
= 0;
3863 if (end
< 0) end
= 0;
3865 /* indexes sanity checks */
3866 if (start
> end
|| start
>= llen
) {
3867 /* Out of range start or start > end result in empty list */
3868 addReply(c
,shared
.emptymultibulk
);
3871 if (end
>= llen
) end
= llen
-1;
3872 rangelen
= (end
-start
)+1;
3874 /* Return the result in form of a multi-bulk reply */
3875 ln
= listIndex(list
, start
);
3876 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
3877 for (j
= 0; j
< rangelen
; j
++) {
3878 ele
= listNodeValue(ln
);
3879 addReplyBulkLen(c
,ele
);
3881 addReply(c
,shared
.crlf
);
3888 static void ltrimCommand(redisClient
*c
) {
3890 int start
= atoi(c
->argv
[2]->ptr
);
3891 int end
= atoi(c
->argv
[3]->ptr
);
3893 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3895 addReply(c
,shared
.ok
);
3897 if (o
->type
!= REDIS_LIST
) {
3898 addReply(c
,shared
.wrongtypeerr
);
3900 list
*list
= o
->ptr
;
3902 int llen
= listLength(list
);
3903 int j
, ltrim
, rtrim
;
3905 /* convert negative indexes */
3906 if (start
< 0) start
= llen
+start
;
3907 if (end
< 0) end
= llen
+end
;
3908 if (start
< 0) start
= 0;
3909 if (end
< 0) end
= 0;
3911 /* indexes sanity checks */
3912 if (start
> end
|| start
>= llen
) {
3913 /* Out of range start or start > end result in empty list */
3917 if (end
>= llen
) end
= llen
-1;
3922 /* Remove list elements to perform the trim */
3923 for (j
= 0; j
< ltrim
; j
++) {
3924 ln
= listFirst(list
);
3925 listDelNode(list
,ln
);
3927 for (j
= 0; j
< rtrim
; j
++) {
3928 ln
= listLast(list
);
3929 listDelNode(list
,ln
);
3932 addReply(c
,shared
.ok
);
3937 static void lremCommand(redisClient
*c
) {
3940 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3942 addReply(c
,shared
.czero
);
3944 if (o
->type
!= REDIS_LIST
) {
3945 addReply(c
,shared
.wrongtypeerr
);
3947 list
*list
= o
->ptr
;
3948 listNode
*ln
, *next
;
3949 int toremove
= atoi(c
->argv
[2]->ptr
);
3954 toremove
= -toremove
;
3957 ln
= fromtail
? list
->tail
: list
->head
;
3959 robj
*ele
= listNodeValue(ln
);
3961 next
= fromtail
? ln
->prev
: ln
->next
;
3962 if (compareStringObjects(ele
,c
->argv
[3]) == 0) {
3963 listDelNode(list
,ln
);
3966 if (toremove
&& removed
== toremove
) break;
3970 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
3975 /* This is the semantic of this command:
3976 * RPOPLPUSH srclist dstlist:
3977 * IF LLEN(srclist) > 0
3978 * element = RPOP srclist
3979 * LPUSH dstlist element
3986 * The idea is to be able to get an element from a list in a reliable way
3987 * since the element is not just returned but pushed against another list
3988 * as well. This command was originally proposed by Ezra Zygmuntowicz.
3990 static void rpoplpushcommand(redisClient
*c
) {
3993 sobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3995 addReply(c
,shared
.nullbulk
);
3997 if (sobj
->type
!= REDIS_LIST
) {
3998 addReply(c
,shared
.wrongtypeerr
);
4000 list
*srclist
= sobj
->ptr
;
4001 listNode
*ln
= listLast(srclist
);
4004 addReply(c
,shared
.nullbulk
);
4006 robj
*dobj
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4007 robj
*ele
= listNodeValue(ln
);
4010 if (dobj
&& dobj
->type
!= REDIS_LIST
) {
4011 addReply(c
,shared
.wrongtypeerr
);
4015 /* Add the element to the target list (unless it's directly
4016 * passed to some BLPOP-ing client */
4017 if (!handleClientsWaitingListPush(c
,c
->argv
[2],ele
)) {
4019 /* Create the list if the key does not exist */
4020 dobj
= createListObject();
4021 dictAdd(c
->db
->dict
,c
->argv
[2],dobj
);
4022 incrRefCount(c
->argv
[2]);
4024 dstlist
= dobj
->ptr
;
4025 listAddNodeHead(dstlist
,ele
);
4029 /* Send the element to the client as reply as well */
4030 addReplyBulkLen(c
,ele
);
4032 addReply(c
,shared
.crlf
);
4034 /* Finally remove the element from the source list */
4035 listDelNode(srclist
,ln
);
4043 /* ==================================== Sets ================================ */
4045 static void saddCommand(redisClient
*c
) {
4048 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4050 set
= createSetObject();
4051 dictAdd(c
->db
->dict
,c
->argv
[1],set
);
4052 incrRefCount(c
->argv
[1]);
4054 if (set
->type
!= REDIS_SET
) {
4055 addReply(c
,shared
.wrongtypeerr
);
4059 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
4060 incrRefCount(c
->argv
[2]);
4062 addReply(c
,shared
.cone
);
4064 addReply(c
,shared
.czero
);
4068 static void sremCommand(redisClient
*c
) {
4071 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4073 addReply(c
,shared
.czero
);
4075 if (set
->type
!= REDIS_SET
) {
4076 addReply(c
,shared
.wrongtypeerr
);
4079 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
4081 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4082 addReply(c
,shared
.cone
);
4084 addReply(c
,shared
.czero
);
4089 static void smoveCommand(redisClient
*c
) {
4090 robj
*srcset
, *dstset
;
4092 srcset
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4093 dstset
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4095 /* If the source key does not exist return 0, if it's of the wrong type
4097 if (srcset
== NULL
|| srcset
->type
!= REDIS_SET
) {
4098 addReply(c
, srcset
? shared
.wrongtypeerr
: shared
.czero
);
4101 /* Error if the destination key is not a set as well */
4102 if (dstset
&& dstset
->type
!= REDIS_SET
) {
4103 addReply(c
,shared
.wrongtypeerr
);
4106 /* Remove the element from the source set */
4107 if (dictDelete(srcset
->ptr
,c
->argv
[3]) == DICT_ERR
) {
4108 /* Key not found in the src set! return zero */
4109 addReply(c
,shared
.czero
);
4113 /* Add the element to the destination set */
4115 dstset
= createSetObject();
4116 dictAdd(c
->db
->dict
,c
->argv
[2],dstset
);
4117 incrRefCount(c
->argv
[2]);
4119 if (dictAdd(dstset
->ptr
,c
->argv
[3],NULL
) == DICT_OK
)
4120 incrRefCount(c
->argv
[3]);
4121 addReply(c
,shared
.cone
);
4124 static void sismemberCommand(redisClient
*c
) {
4127 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4129 addReply(c
,shared
.czero
);
4131 if (set
->type
!= REDIS_SET
) {
4132 addReply(c
,shared
.wrongtypeerr
);
4135 if (dictFind(set
->ptr
,c
->argv
[2]))
4136 addReply(c
,shared
.cone
);
4138 addReply(c
,shared
.czero
);
4142 static void scardCommand(redisClient
*c
) {
4146 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4148 addReply(c
,shared
.czero
);
4151 if (o
->type
!= REDIS_SET
) {
4152 addReply(c
,shared
.wrongtypeerr
);
4155 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4161 static void spopCommand(redisClient
*c
) {
4165 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4167 addReply(c
,shared
.nullbulk
);
4169 if (set
->type
!= REDIS_SET
) {
4170 addReply(c
,shared
.wrongtypeerr
);
4173 de
= dictGetRandomKey(set
->ptr
);
4175 addReply(c
,shared
.nullbulk
);
4177 robj
*ele
= dictGetEntryKey(de
);
4179 addReplyBulkLen(c
,ele
);
4181 addReply(c
,shared
.crlf
);
4182 dictDelete(set
->ptr
,ele
);
4183 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4189 static void srandmemberCommand(redisClient
*c
) {
4193 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4195 addReply(c
,shared
.nullbulk
);
4197 if (set
->type
!= REDIS_SET
) {
4198 addReply(c
,shared
.wrongtypeerr
);
4201 de
= dictGetRandomKey(set
->ptr
);
4203 addReply(c
,shared
.nullbulk
);
4205 robj
*ele
= dictGetEntryKey(de
);
4207 addReplyBulkLen(c
,ele
);
4209 addReply(c
,shared
.crlf
);
4214 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
4215 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
4217 return dictSize(*d1
)-dictSize(*d2
);
4220 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, unsigned long setsnum
, robj
*dstkey
) {
4221 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4224 robj
*lenobj
= NULL
, *dstset
= NULL
;
4225 unsigned long j
, cardinality
= 0;
4227 for (j
= 0; j
< setsnum
; j
++) {
4231 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4232 lookupKeyRead(c
->db
,setskeys
[j
]);
4236 if (deleteKey(c
->db
,dstkey
))
4238 addReply(c
,shared
.czero
);
4240 addReply(c
,shared
.nullmultibulk
);
4244 if (setobj
->type
!= REDIS_SET
) {
4246 addReply(c
,shared
.wrongtypeerr
);
4249 dv
[j
] = setobj
->ptr
;
4251 /* Sort sets from the smallest to largest, this will improve our
4252 * algorithm's performace */
4253 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
4255 /* The first thing we should output is the total number of elements...
4256 * since this is a multi-bulk write, but at this stage we don't know
4257 * the intersection set size, so we use a trick, append an empty object
4258 * to the output list and save the pointer to later modify it with the
4261 lenobj
= createObject(REDIS_STRING
,NULL
);
4263 decrRefCount(lenobj
);
4265 /* If we have a target key where to store the resulting set
4266 * create this key with an empty set inside */
4267 dstset
= createSetObject();
4270 /* Iterate all the elements of the first (smallest) set, and test
4271 * the element against all the other sets, if at least one set does
4272 * not include the element it is discarded */
4273 di
= dictGetIterator(dv
[0]);
4275 while((de
= dictNext(di
)) != NULL
) {
4278 for (j
= 1; j
< setsnum
; j
++)
4279 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
4281 continue; /* at least one set does not contain the member */
4282 ele
= dictGetEntryKey(de
);
4284 addReplyBulkLen(c
,ele
);
4286 addReply(c
,shared
.crlf
);
4289 dictAdd(dstset
->ptr
,ele
,NULL
);
4293 dictReleaseIterator(di
);
4296 /* Store the resulting set into the target */
4297 deleteKey(c
->db
,dstkey
);
4298 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4299 incrRefCount(dstkey
);
4303 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",cardinality
);
4305 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4306 dictSize((dict
*)dstset
->ptr
)));
4312 static void sinterCommand(redisClient
*c
) {
4313 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
4316 static void sinterstoreCommand(redisClient
*c
) {
4317 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
4320 #define REDIS_OP_UNION 0
4321 #define REDIS_OP_DIFF 1
4323 static void sunionDiffGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
, int op
) {
4324 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4327 robj
*dstset
= NULL
;
4328 int j
, cardinality
= 0;
4330 for (j
= 0; j
< setsnum
; j
++) {
4334 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4335 lookupKeyRead(c
->db
,setskeys
[j
]);
4340 if (setobj
->type
!= REDIS_SET
) {
4342 addReply(c
,shared
.wrongtypeerr
);
4345 dv
[j
] = setobj
->ptr
;
4348 /* We need a temp set object to store our union. If the dstkey
4349 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
4350 * this set object will be the resulting object to set into the target key*/
4351 dstset
= createSetObject();
4353 /* Iterate all the elements of all the sets, add every element a single
4354 * time to the result set */
4355 for (j
= 0; j
< setsnum
; j
++) {
4356 if (op
== REDIS_OP_DIFF
&& j
== 0 && !dv
[j
]) break; /* result set is empty */
4357 if (!dv
[j
]) continue; /* non existing keys are like empty sets */
4359 di
= dictGetIterator(dv
[j
]);
4361 while((de
= dictNext(di
)) != NULL
) {
4364 /* dictAdd will not add the same element multiple times */
4365 ele
= dictGetEntryKey(de
);
4366 if (op
== REDIS_OP_UNION
|| j
== 0) {
4367 if (dictAdd(dstset
->ptr
,ele
,NULL
) == DICT_OK
) {
4371 } else if (op
== REDIS_OP_DIFF
) {
4372 if (dictDelete(dstset
->ptr
,ele
) == DICT_OK
) {
4377 dictReleaseIterator(di
);
4379 if (op
== REDIS_OP_DIFF
&& cardinality
== 0) break; /* result set is empty */
4382 /* Output the content of the resulting set, if not in STORE mode */
4384 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",cardinality
));
4385 di
= dictGetIterator(dstset
->ptr
);
4386 while((de
= dictNext(di
)) != NULL
) {
4389 ele
= dictGetEntryKey(de
);
4390 addReplyBulkLen(c
,ele
);
4392 addReply(c
,shared
.crlf
);
4394 dictReleaseIterator(di
);
4396 /* If we have a target key where to store the resulting set
4397 * create this key with the result set inside */
4398 deleteKey(c
->db
,dstkey
);
4399 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4400 incrRefCount(dstkey
);
4405 decrRefCount(dstset
);
4407 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4408 dictSize((dict
*)dstset
->ptr
)));
4414 static void sunionCommand(redisClient
*c
) {
4415 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_UNION
);
4418 static void sunionstoreCommand(redisClient
*c
) {
4419 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_UNION
);
4422 static void sdiffCommand(redisClient
*c
) {
4423 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_DIFF
);
4426 static void sdiffstoreCommand(redisClient
*c
) {
4427 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_DIFF
);
4430 /* ==================================== ZSets =============================== */
4432 /* ZSETs are ordered sets using two data structures to hold the same elements
4433 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
4436 * The elements are added to an hash table mapping Redis objects to scores.
4437 * At the same time the elements are added to a skip list mapping scores
4438 * to Redis objects (so objects are sorted by scores in this "view"). */
4440 /* This skiplist implementation is almost a C translation of the original
4441 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
4442 * Alternative to Balanced Trees", modified in three ways:
4443 * a) this implementation allows for repeated values.
4444 * b) the comparison is not just by key (our 'score') but by satellite data.
4445 * c) there is a back pointer, so it's a doubly linked list with the back
4446 * pointers being only at "level 1". This allows to traverse the list
4447 * from tail to head, useful for ZREVRANGE. */
4449 static zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
4450 zskiplistNode
*zn
= zmalloc(sizeof(*zn
));
4452 zn
->forward
= zmalloc(sizeof(zskiplistNode
*) * level
);
4458 static zskiplist
*zslCreate(void) {
4462 zsl
= zmalloc(sizeof(*zsl
));
4465 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
4466 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++)
4467 zsl
->header
->forward
[j
] = NULL
;
4468 zsl
->header
->backward
= NULL
;
4473 static void zslFreeNode(zskiplistNode
*node
) {
4474 decrRefCount(node
->obj
);
4475 zfree(node
->forward
);
4479 static void zslFree(zskiplist
*zsl
) {
4480 zskiplistNode
*node
= zsl
->header
->forward
[0], *next
;
4482 zfree(zsl
->header
->forward
);
4485 next
= node
->forward
[0];
4492 static int zslRandomLevel(void) {
4494 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
4499 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
4500 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4504 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4505 while (x
->forward
[i
] &&
4506 (x
->forward
[i
]->score
< score
||
4507 (x
->forward
[i
]->score
== score
&&
4508 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
4512 /* we assume the key is not already inside, since we allow duplicated
4513 * scores, and the re-insertion of score and redis object should never
4514 * happpen since the caller of zslInsert() should test in the hash table
4515 * if the element is already inside or not. */
4516 level
= zslRandomLevel();
4517 if (level
> zsl
->level
) {
4518 for (i
= zsl
->level
; i
< level
; i
++)
4519 update
[i
] = zsl
->header
;
4522 x
= zslCreateNode(level
,score
,obj
);
4523 for (i
= 0; i
< level
; i
++) {
4524 x
->forward
[i
] = update
[i
]->forward
[i
];
4525 update
[i
]->forward
[i
] = x
;
4527 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
4529 x
->forward
[0]->backward
= x
;
4535 /* Delete an element with matching score/object from the skiplist. */
4536 static int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
4537 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4541 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4542 while (x
->forward
[i
] &&
4543 (x
->forward
[i
]->score
< score
||
4544 (x
->forward
[i
]->score
== score
&&
4545 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
4549 /* We may have multiple elements with the same score, what we need
4550 * is to find the element with both the right score and object. */
4552 if (x
&& score
== x
->score
&& compareStringObjects(x
->obj
,obj
) == 0) {
4553 for (i
= 0; i
< zsl
->level
; i
++) {
4554 if (update
[i
]->forward
[i
] != x
) break;
4555 update
[i
]->forward
[i
] = x
->forward
[i
];
4557 if (x
->forward
[0]) {
4558 x
->forward
[0]->backward
= (x
->backward
== zsl
->header
) ?
4561 zsl
->tail
= x
->backward
;
4564 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
4569 return 0; /* not found */
4571 return 0; /* not found */
4574 /* Delete all the elements with score between min and max from the skiplist.
4575 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
4576 * Note that this function takes the reference to the hash table view of the
4577 * sorted set, in order to remove the elements from the hash table too. */
4578 static unsigned long zslDeleteRange(zskiplist
*zsl
, double min
, double max
, dict
*dict
) {
4579 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4580 unsigned long removed
= 0;
4584 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4585 while (x
->forward
[i
] && x
->forward
[i
]->score
< min
)
4589 /* We may have multiple elements with the same score, what we need
4590 * is to find the element with both the right score and object. */
4592 while (x
&& x
->score
<= max
) {
4593 zskiplistNode
*next
;
4595 for (i
= 0; i
< zsl
->level
; i
++) {
4596 if (update
[i
]->forward
[i
] != x
) break;
4597 update
[i
]->forward
[i
] = x
->forward
[i
];
4599 if (x
->forward
[0]) {
4600 x
->forward
[0]->backward
= (x
->backward
== zsl
->header
) ?
4603 zsl
->tail
= x
->backward
;
4605 next
= x
->forward
[0];
4606 dictDelete(dict
,x
->obj
);
4608 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
4614 return removed
; /* not found */
4617 /* Find the first node having a score equal or greater than the specified one.
4618 * Returns NULL if there is no match. */
4619 static zskiplistNode
*zslFirstWithScore(zskiplist
*zsl
, double score
) {
4624 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4625 while (x
->forward
[i
] && x
->forward
[i
]->score
< score
)
4628 /* We may have multiple elements with the same score, what we need
4629 * is to find the element with both the right score and object. */
4630 return x
->forward
[0];
4633 /* The actual Z-commands implementations */
4635 /* This generic command implements both ZADD and ZINCRBY.
4636 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
4637 * the increment if the operation is a ZINCRBY (doincrement == 1). */
4638 static void zaddGenericCommand(redisClient
*c
, robj
*key
, robj
*ele
, double scoreval
, int doincrement
) {
4643 zsetobj
= lookupKeyWrite(c
->db
,key
);
4644 if (zsetobj
== NULL
) {
4645 zsetobj
= createZsetObject();
4646 dictAdd(c
->db
->dict
,key
,zsetobj
);
4649 if (zsetobj
->type
!= REDIS_ZSET
) {
4650 addReply(c
,shared
.wrongtypeerr
);
4656 /* Ok now since we implement both ZADD and ZINCRBY here the code
4657 * needs to handle the two different conditions. It's all about setting
4658 * '*score', that is, the new score to set, to the right value. */
4659 score
= zmalloc(sizeof(double));
4663 /* Read the old score. If the element was not present starts from 0 */
4664 de
= dictFind(zs
->dict
,ele
);
4666 double *oldscore
= dictGetEntryVal(de
);
4667 *score
= *oldscore
+ scoreval
;
4675 /* What follows is a simple remove and re-insert operation that is common
4676 * to both ZADD and ZINCRBY... */
4677 if (dictAdd(zs
->dict
,ele
,score
) == DICT_OK
) {
4678 /* case 1: New element */
4679 incrRefCount(ele
); /* added to hash */
4680 zslInsert(zs
->zsl
,*score
,ele
);
4681 incrRefCount(ele
); /* added to skiplist */
4684 addReplyDouble(c
,*score
);
4686 addReply(c
,shared
.cone
);
4691 /* case 2: Score update operation */
4692 de
= dictFind(zs
->dict
,ele
);
4693 redisAssert(de
!= NULL
);
4694 oldscore
= dictGetEntryVal(de
);
4695 if (*score
!= *oldscore
) {
4698 /* Remove and insert the element in the skip list with new score */
4699 deleted
= zslDelete(zs
->zsl
,*oldscore
,ele
);
4700 redisAssert(deleted
!= 0);
4701 zslInsert(zs
->zsl
,*score
,ele
);
4703 /* Update the score in the hash table */
4704 dictReplace(zs
->dict
,ele
,score
);
4710 addReplyDouble(c
,*score
);
4712 addReply(c
,shared
.czero
);
4716 static void zaddCommand(redisClient
*c
) {
4719 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
4720 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0);
4723 static void zincrbyCommand(redisClient
*c
) {
4726 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
4727 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1);
4730 static void zremCommand(redisClient
*c
) {
4734 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4735 if (zsetobj
== NULL
) {
4736 addReply(c
,shared
.czero
);
4742 if (zsetobj
->type
!= REDIS_ZSET
) {
4743 addReply(c
,shared
.wrongtypeerr
);
4747 de
= dictFind(zs
->dict
,c
->argv
[2]);
4749 addReply(c
,shared
.czero
);
4752 /* Delete from the skiplist */
4753 oldscore
= dictGetEntryVal(de
);
4754 deleted
= zslDelete(zs
->zsl
,*oldscore
,c
->argv
[2]);
4755 redisAssert(deleted
!= 0);
4757 /* Delete from the hash table */
4758 dictDelete(zs
->dict
,c
->argv
[2]);
4759 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
4761 addReply(c
,shared
.cone
);
4765 static void zremrangebyscoreCommand(redisClient
*c
) {
4766 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
4767 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
4771 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4772 if (zsetobj
== NULL
) {
4773 addReply(c
,shared
.czero
);
4777 if (zsetobj
->type
!= REDIS_ZSET
) {
4778 addReply(c
,shared
.wrongtypeerr
);
4782 deleted
= zslDeleteRange(zs
->zsl
,min
,max
,zs
->dict
);
4783 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
4784 server
.dirty
+= deleted
;
4785 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",deleted
));
4789 static void zrangeGenericCommand(redisClient
*c
, int reverse
) {
4791 int start
= atoi(c
->argv
[2]->ptr
);
4792 int end
= atoi(c
->argv
[3]->ptr
);
4795 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
4797 } else if (c
->argc
>= 5) {
4798 addReply(c
,shared
.syntaxerr
);
4802 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4804 addReply(c
,shared
.nullmultibulk
);
4806 if (o
->type
!= REDIS_ZSET
) {
4807 addReply(c
,shared
.wrongtypeerr
);
4809 zset
*zsetobj
= o
->ptr
;
4810 zskiplist
*zsl
= zsetobj
->zsl
;
4813 int llen
= zsl
->length
;
4817 /* convert negative indexes */
4818 if (start
< 0) start
= llen
+start
;
4819 if (end
< 0) end
= llen
+end
;
4820 if (start
< 0) start
= 0;
4821 if (end
< 0) end
= 0;
4823 /* indexes sanity checks */
4824 if (start
> end
|| start
>= llen
) {
4825 /* Out of range start or start > end result in empty list */
4826 addReply(c
,shared
.emptymultibulk
);
4829 if (end
>= llen
) end
= llen
-1;
4830 rangelen
= (end
-start
)+1;
4832 /* Return the result in form of a multi-bulk reply */
4838 ln
= zsl
->header
->forward
[0];
4840 ln
= ln
->forward
[0];
4843 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",
4844 withscores
? (rangelen
*2) : rangelen
));
4845 for (j
= 0; j
< rangelen
; j
++) {
4847 addReplyBulkLen(c
,ele
);
4849 addReply(c
,shared
.crlf
);
4851 addReplyDouble(c
,ln
->score
);
4852 ln
= reverse
? ln
->backward
: ln
->forward
[0];
4858 static void zrangeCommand(redisClient
*c
) {
4859 zrangeGenericCommand(c
,0);
4862 static void zrevrangeCommand(redisClient
*c
) {
4863 zrangeGenericCommand(c
,1);
4866 static void zrangebyscoreCommand(redisClient
*c
) {
4868 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
4869 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
4870 int offset
= 0, limit
= -1;
4872 if (c
->argc
!= 4 && c
->argc
!= 7) {
4874 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
4876 } else if (c
->argc
== 7 && strcasecmp(c
->argv
[4]->ptr
,"limit")) {
4877 addReply(c
,shared
.syntaxerr
);
4879 } else if (c
->argc
== 7) {
4880 offset
= atoi(c
->argv
[5]->ptr
);
4881 limit
= atoi(c
->argv
[6]->ptr
);
4882 if (offset
< 0) offset
= 0;
4885 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4887 addReply(c
,shared
.nullmultibulk
);
4889 if (o
->type
!= REDIS_ZSET
) {
4890 addReply(c
,shared
.wrongtypeerr
);
4892 zset
*zsetobj
= o
->ptr
;
4893 zskiplist
*zsl
= zsetobj
->zsl
;
4896 unsigned int rangelen
= 0;
4898 /* Get the first node with the score >= min */
4899 ln
= zslFirstWithScore(zsl
,min
);
4901 /* No element matching the speciifed interval */
4902 addReply(c
,shared
.emptymultibulk
);
4906 /* We don't know in advance how many matching elements there
4907 * are in the list, so we push this object that will represent
4908 * the multi-bulk length in the output buffer, and will "fix"
4910 lenobj
= createObject(REDIS_STRING
,NULL
);
4912 decrRefCount(lenobj
);
4914 while(ln
&& ln
->score
<= max
) {
4917 ln
= ln
->forward
[0];
4920 if (limit
== 0) break;
4922 addReplyBulkLen(c
,ele
);
4924 addReply(c
,shared
.crlf
);
4925 ln
= ln
->forward
[0];
4927 if (limit
> 0) limit
--;
4929 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",rangelen
);
4934 static void zcardCommand(redisClient
*c
) {
4938 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4940 addReply(c
,shared
.czero
);
4943 if (o
->type
!= REDIS_ZSET
) {
4944 addReply(c
,shared
.wrongtypeerr
);
4947 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",zs
->zsl
->length
));
4952 static void zscoreCommand(redisClient
*c
) {
4956 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4958 addReply(c
,shared
.nullbulk
);
4961 if (o
->type
!= REDIS_ZSET
) {
4962 addReply(c
,shared
.wrongtypeerr
);
4967 de
= dictFind(zs
->dict
,c
->argv
[2]);
4969 addReply(c
,shared
.nullbulk
);
4971 double *score
= dictGetEntryVal(de
);
4973 addReplyDouble(c
,*score
);
4979 /* ========================= Non type-specific commands ==================== */
4981 static void flushdbCommand(redisClient
*c
) {
4982 server
.dirty
+= dictSize(c
->db
->dict
);
4983 dictEmpty(c
->db
->dict
);
4984 dictEmpty(c
->db
->expires
);
4985 addReply(c
,shared
.ok
);
4988 static void flushallCommand(redisClient
*c
) {
4989 server
.dirty
+= emptyDb();
4990 addReply(c
,shared
.ok
);
4991 rdbSave(server
.dbfilename
);
4995 static redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
4996 redisSortOperation
*so
= zmalloc(sizeof(*so
));
4998 so
->pattern
= pattern
;
5002 /* Return the value associated to the key with a name obtained
5003 * substituting the first occurence of '*' in 'pattern' with 'subst' */
5004 static robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
5008 int prefixlen
, sublen
, postfixlen
;
5009 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
5013 char buf
[REDIS_SORTKEY_MAX
+1];
5016 /* If the pattern is "#" return the substitution object itself in order
5017 * to implement the "SORT ... GET #" feature. */
5018 spat
= pattern
->ptr
;
5019 if (spat
[0] == '#' && spat
[1] == '\0') {
5023 /* The substitution object may be specially encoded. If so we create
5024 * a decoded object on the fly. Otherwise getDecodedObject will just
5025 * increment the ref count, that we'll decrement later. */
5026 subst
= getDecodedObject(subst
);
5029 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
5030 p
= strchr(spat
,'*');
5032 decrRefCount(subst
);
5037 sublen
= sdslen(ssub
);
5038 postfixlen
= sdslen(spat
)-(prefixlen
+1);
5039 memcpy(keyname
.buf
,spat
,prefixlen
);
5040 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
5041 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
5042 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
5043 keyname
.len
= prefixlen
+sublen
+postfixlen
;
5045 initStaticStringObject(keyobj
,((char*)&keyname
)+(sizeof(long)*2))
5046 decrRefCount(subst
);
5048 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
5049 return lookupKeyRead(db
,&keyobj
);
5052 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
5053 * the additional parameter is not standard but a BSD-specific we have to
5054 * pass sorting parameters via the global 'server' structure */
5055 static int sortCompare(const void *s1
, const void *s2
) {
5056 const redisSortObject
*so1
= s1
, *so2
= s2
;
5059 if (!server
.sort_alpha
) {
5060 /* Numeric sorting. Here it's trivial as we precomputed scores */
5061 if (so1
->u
.score
> so2
->u
.score
) {
5063 } else if (so1
->u
.score
< so2
->u
.score
) {
5069 /* Alphanumeric sorting */
5070 if (server
.sort_bypattern
) {
5071 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
5072 /* At least one compare object is NULL */
5073 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
5075 else if (so1
->u
.cmpobj
== NULL
)
5080 /* We have both the objects, use strcoll */
5081 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
5084 /* Compare elements directly */
5087 dec1
= getDecodedObject(so1
->obj
);
5088 dec2
= getDecodedObject(so2
->obj
);
5089 cmp
= strcoll(dec1
->ptr
,dec2
->ptr
);
5094 return server
.sort_desc
? -cmp
: cmp
;
5097 /* The SORT command is the most complex command in Redis. Warning: this code
5098 * is optimized for speed and a bit less for readability */
5099 static void sortCommand(redisClient
*c
) {
5102 int desc
= 0, alpha
= 0;
5103 int limit_start
= 0, limit_count
= -1, start
, end
;
5104 int j
, dontsort
= 0, vectorlen
;
5105 int getop
= 0; /* GET operation counter */
5106 robj
*sortval
, *sortby
= NULL
, *storekey
= NULL
;
5107 redisSortObject
*vector
; /* Resulting vector to sort */
5109 /* Lookup the key to sort. It must be of the right types */
5110 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
5111 if (sortval
== NULL
) {
5112 addReply(c
,shared
.nullmultibulk
);
5115 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
&&
5116 sortval
->type
!= REDIS_ZSET
)
5118 addReply(c
,shared
.wrongtypeerr
);
5122 /* Create a list of operations to perform for every sorted element.
5123 * Operations can be GET/DEL/INCR/DECR */
5124 operations
= listCreate();
5125 listSetFreeMethod(operations
,zfree
);
5128 /* Now we need to protect sortval incrementing its count, in the future
5129 * SORT may have options able to overwrite/delete keys during the sorting
5130 * and the sorted key itself may get destroied */
5131 incrRefCount(sortval
);
5133 /* The SORT command has an SQL-alike syntax, parse it */
5134 while(j
< c
->argc
) {
5135 int leftargs
= c
->argc
-j
-1;
5136 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
5138 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
5140 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
5142 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
5143 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
5144 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
5146 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"store") && leftargs
>= 1) {
5147 storekey
= c
->argv
[j
+1];
5149 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
5150 sortby
= c
->argv
[j
+1];
5151 /* If the BY pattern does not contain '*', i.e. it is constant,
5152 * we don't need to sort nor to lookup the weight keys. */
5153 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
5155 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
5156 listAddNodeTail(operations
,createSortOperation(
5157 REDIS_SORT_GET
,c
->argv
[j
+1]));
5161 decrRefCount(sortval
);
5162 listRelease(operations
);
5163 addReply(c
,shared
.syntaxerr
);
5169 /* Load the sorting vector with all the objects to sort */
5170 switch(sortval
->type
) {
5171 case REDIS_LIST
: vectorlen
= listLength((list
*)sortval
->ptr
); break;
5172 case REDIS_SET
: vectorlen
= dictSize((dict
*)sortval
->ptr
); break;
5173 case REDIS_ZSET
: vectorlen
= dictSize(((zset
*)sortval
->ptr
)->dict
); break;
5174 default: vectorlen
= 0; redisAssert(0); /* Avoid GCC warning */
5176 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
5179 if (sortval
->type
== REDIS_LIST
) {
5180 list
*list
= sortval
->ptr
;
5184 while((ln
= listYield(list
))) {
5185 robj
*ele
= ln
->value
;
5186 vector
[j
].obj
= ele
;
5187 vector
[j
].u
.score
= 0;
5188 vector
[j
].u
.cmpobj
= NULL
;
5196 if (sortval
->type
== REDIS_SET
) {
5199 zset
*zs
= sortval
->ptr
;
5203 di
= dictGetIterator(set
);
5204 while((setele
= dictNext(di
)) != NULL
) {
5205 vector
[j
].obj
= dictGetEntryKey(setele
);
5206 vector
[j
].u
.score
= 0;
5207 vector
[j
].u
.cmpobj
= NULL
;
5210 dictReleaseIterator(di
);
5212 redisAssert(j
== vectorlen
);
5214 /* Now it's time to load the right scores in the sorting vector */
5215 if (dontsort
== 0) {
5216 for (j
= 0; j
< vectorlen
; j
++) {
5220 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
5221 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
5223 vector
[j
].u
.cmpobj
= getDecodedObject(byval
);
5225 if (byval
->encoding
== REDIS_ENCODING_RAW
) {
5226 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
5228 /* Don't need to decode the object if it's
5229 * integer-encoded (the only encoding supported) so
5230 * far. We can just cast it */
5231 if (byval
->encoding
== REDIS_ENCODING_INT
) {
5232 vector
[j
].u
.score
= (long)byval
->ptr
;
5234 redisAssert(1 != 1);
5239 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_RAW
)
5240 vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
5242 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_INT
)
5243 vector
[j
].u
.score
= (long) vector
[j
].obj
->ptr
;
5245 redisAssert(1 != 1);
5252 /* We are ready to sort the vector... perform a bit of sanity check
5253 * on the LIMIT option too. We'll use a partial version of quicksort. */
5254 start
= (limit_start
< 0) ? 0 : limit_start
;
5255 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
5256 if (start
>= vectorlen
) {
5257 start
= vectorlen
-1;
5260 if (end
>= vectorlen
) end
= vectorlen
-1;
5262 if (dontsort
== 0) {
5263 server
.sort_desc
= desc
;
5264 server
.sort_alpha
= alpha
;
5265 server
.sort_bypattern
= sortby
? 1 : 0;
5266 if (sortby
&& (start
!= 0 || end
!= vectorlen
-1))
5267 pqsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
, start
,end
);
5269 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
5272 /* Send command output to the output buffer, performing the specified
5273 * GET/DEL/INCR/DECR operations if any. */
5274 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
5275 if (storekey
== NULL
) {
5276 /* STORE option not specified, sent the sorting result to client */
5277 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
5278 for (j
= start
; j
<= end
; j
++) {
5281 addReplyBulkLen(c
,vector
[j
].obj
);
5282 addReply(c
,vector
[j
].obj
);
5283 addReply(c
,shared
.crlf
);
5285 listRewind(operations
);
5286 while((ln
= listYield(operations
))) {
5287 redisSortOperation
*sop
= ln
->value
;
5288 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
5291 if (sop
->type
== REDIS_SORT_GET
) {
5292 if (!val
|| val
->type
!= REDIS_STRING
) {
5293 addReply(c
,shared
.nullbulk
);
5295 addReplyBulkLen(c
,val
);
5297 addReply(c
,shared
.crlf
);
5300 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
5305 robj
*listObject
= createListObject();
5306 list
*listPtr
= (list
*) listObject
->ptr
;
5308 /* STORE option specified, set the sorting result as a List object */
5309 for (j
= start
; j
<= end
; j
++) {
5312 listAddNodeTail(listPtr
,vector
[j
].obj
);
5313 incrRefCount(vector
[j
].obj
);
5315 listRewind(operations
);
5316 while((ln
= listYield(operations
))) {
5317 redisSortOperation
*sop
= ln
->value
;
5318 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
5321 if (sop
->type
== REDIS_SORT_GET
) {
5322 if (!val
|| val
->type
!= REDIS_STRING
) {
5323 listAddNodeTail(listPtr
,createStringObject("",0));
5325 listAddNodeTail(listPtr
,val
);
5329 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
5333 if (dictReplace(c
->db
->dict
,storekey
,listObject
)) {
5334 incrRefCount(storekey
);
5336 /* Note: we add 1 because the DB is dirty anyway since even if the
5337 * SORT result is empty a new key is set and maybe the old content
5339 server
.dirty
+= 1+outputlen
;
5340 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",outputlen
));
5344 decrRefCount(sortval
);
5345 listRelease(operations
);
5346 for (j
= 0; j
< vectorlen
; j
++) {
5347 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
5348 decrRefCount(vector
[j
].u
.cmpobj
);
5353 /* Create the string returned by the INFO command. This is decoupled
5354 * by the INFO command itself as we need to report the same information
5355 * on memory corruption problems. */
5356 static sds
genRedisInfoString(void) {
5358 time_t uptime
= time(NULL
)-server
.stat_starttime
;
5361 info
= sdscatprintf(sdsempty(),
5362 "redis_version:%s\r\n"
5364 "multiplexing_api:%s\r\n"
5365 "uptime_in_seconds:%ld\r\n"
5366 "uptime_in_days:%ld\r\n"
5367 "connected_clients:%d\r\n"
5368 "connected_slaves:%d\r\n"
5369 "blocked_clients:%d\r\n"
5370 "used_memory:%zu\r\n"
5371 "changes_since_last_save:%lld\r\n"
5372 "bgsave_in_progress:%d\r\n"
5373 "last_save_time:%ld\r\n"
5374 "bgrewriteaof_in_progress:%d\r\n"
5375 "total_connections_received:%lld\r\n"
5376 "total_commands_processed:%lld\r\n"
5379 (sizeof(long) == 8) ? "64" : "32",
5383 listLength(server
.clients
)-listLength(server
.slaves
),
5384 listLength(server
.slaves
),
5385 server
.blockedclients
,
5388 server
.bgsavechildpid
!= -1,
5390 server
.bgrewritechildpid
!= -1,
5391 server
.stat_numconnections
,
5392 server
.stat_numcommands
,
5393 server
.masterhost
== NULL
? "master" : "slave"
5395 if (server
.masterhost
) {
5396 info
= sdscatprintf(info
,
5397 "master_host:%s\r\n"
5398 "master_port:%d\r\n"
5399 "master_link_status:%s\r\n"
5400 "master_last_io_seconds_ago:%d\r\n"
5403 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
5405 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1
5408 for (j
= 0; j
< server
.dbnum
; j
++) {
5409 long long keys
, vkeys
;
5411 keys
= dictSize(server
.db
[j
].dict
);
5412 vkeys
= dictSize(server
.db
[j
].expires
);
5413 if (keys
|| vkeys
) {
5414 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
5421 static void infoCommand(redisClient
*c
) {
5422 sds info
= genRedisInfoString();
5423 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
5424 (unsigned long)sdslen(info
)));
5425 addReplySds(c
,info
);
5426 addReply(c
,shared
.crlf
);
5429 static void monitorCommand(redisClient
*c
) {
5430 /* ignore MONITOR if aleady slave or in monitor mode */
5431 if (c
->flags
& REDIS_SLAVE
) return;
5433 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
5435 listAddNodeTail(server
.monitors
,c
);
5436 addReply(c
,shared
.ok
);
5439 /* ================================= Expire ================================= */
5440 static int removeExpire(redisDb
*db
, robj
*key
) {
5441 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
5448 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
5449 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
5457 /* Return the expire time of the specified key, or -1 if no expire
5458 * is associated with this key (i.e. the key is non volatile) */
5459 static time_t getExpire(redisDb
*db
, robj
*key
) {
5462 /* No expire? return ASAP */
5463 if (dictSize(db
->expires
) == 0 ||
5464 (de
= dictFind(db
->expires
,key
)) == NULL
) return -1;
5466 return (time_t) dictGetEntryVal(de
);
5469 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
5473 /* No expire? return ASAP */
5474 if (dictSize(db
->expires
) == 0 ||
5475 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
5477 /* Lookup the expire */
5478 when
= (time_t) dictGetEntryVal(de
);
5479 if (time(NULL
) <= when
) return 0;
5481 /* Delete the key */
5482 dictDelete(db
->expires
,key
);
5483 return dictDelete(db
->dict
,key
) == DICT_OK
;
5486 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
5489 /* No expire? return ASAP */
5490 if (dictSize(db
->expires
) == 0 ||
5491 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
5493 /* Delete the key */
5495 dictDelete(db
->expires
,key
);
5496 return dictDelete(db
->dict
,key
) == DICT_OK
;
5499 static void expireGenericCommand(redisClient
*c
, robj
*key
, time_t seconds
) {
5502 de
= dictFind(c
->db
->dict
,key
);
5504 addReply(c
,shared
.czero
);
5508 if (deleteKey(c
->db
,key
)) server
.dirty
++;
5509 addReply(c
, shared
.cone
);
5512 time_t when
= time(NULL
)+seconds
;
5513 if (setExpire(c
->db
,key
,when
)) {
5514 addReply(c
,shared
.cone
);
5517 addReply(c
,shared
.czero
);
5523 static void expireCommand(redisClient
*c
) {
5524 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10));
5527 static void expireatCommand(redisClient
*c
) {
5528 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10)-time(NULL
));
5531 static void ttlCommand(redisClient
*c
) {
5535 expire
= getExpire(c
->db
,c
->argv
[1]);
5537 ttl
= (int) (expire
-time(NULL
));
5538 if (ttl
< 0) ttl
= -1;
5540 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",ttl
));
5543 /* ================================ MULTI/EXEC ============================== */
5545 /* Client state initialization for MULTI/EXEC */
5546 static void initClientMultiState(redisClient
*c
) {
5547 c
->mstate
.commands
= NULL
;
5548 c
->mstate
.count
= 0;
5551 /* Release all the resources associated with MULTI/EXEC state */
5552 static void freeClientMultiState(redisClient
*c
) {
5555 for (j
= 0; j
< c
->mstate
.count
; j
++) {
5557 multiCmd
*mc
= c
->mstate
.commands
+j
;
5559 for (i
= 0; i
< mc
->argc
; i
++)
5560 decrRefCount(mc
->argv
[i
]);
5563 zfree(c
->mstate
.commands
);
5566 /* Add a new command into the MULTI commands queue */
5567 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
) {
5571 c
->mstate
.commands
= zrealloc(c
->mstate
.commands
,
5572 sizeof(multiCmd
)*(c
->mstate
.count
+1));
5573 mc
= c
->mstate
.commands
+c
->mstate
.count
;
5576 mc
->argv
= zmalloc(sizeof(robj
*)*c
->argc
);
5577 memcpy(mc
->argv
,c
->argv
,sizeof(robj
*)*c
->argc
);
5578 for (j
= 0; j
< c
->argc
; j
++)
5579 incrRefCount(mc
->argv
[j
]);
5583 static void multiCommand(redisClient
*c
) {
5584 c
->flags
|= REDIS_MULTI
;
5585 addReply(c
,shared
.ok
);
5588 static void execCommand(redisClient
*c
) {
5593 if (!(c
->flags
& REDIS_MULTI
)) {
5594 addReplySds(c
,sdsnew("-ERR EXEC without MULTI\r\n"));
5598 orig_argv
= c
->argv
;
5599 orig_argc
= c
->argc
;
5600 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->mstate
.count
));
5601 for (j
= 0; j
< c
->mstate
.count
; j
++) {
5602 c
->argc
= c
->mstate
.commands
[j
].argc
;
5603 c
->argv
= c
->mstate
.commands
[j
].argv
;
5604 call(c
,c
->mstate
.commands
[j
].cmd
);
5606 c
->argv
= orig_argv
;
5607 c
->argc
= orig_argc
;
5608 freeClientMultiState(c
);
5609 initClientMultiState(c
);
5610 c
->flags
&= (~REDIS_MULTI
);
5613 /* =========================== Blocking Operations ========================= */
5615 /* Currently Redis blocking operations support is limited to list POP ops,
5616 * so the current implementation is not fully generic, but it is also not
5617 * completely specific so it will not require a rewrite to support new
5618 * kind of blocking operations in the future.
5620 * Still it's important to note that list blocking operations can be already
5621 * used as a notification mechanism in order to implement other blocking
5622 * operations at application level, so there must be a very strong evidence
5623 * of usefulness and generality before new blocking operations are implemented.
5625 * This is how the current blocking POP works, we use BLPOP as example:
5626 * - If the user calls BLPOP and the key exists and contains a non empty list
5627 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
5628 * if there is not to block.
5629 * - If instead BLPOP is called and the key does not exists or the list is
5630 * empty we need to block. In order to do so we remove the notification for
5631 * new data to read in the client socket (so that we'll not serve new
5632 * requests if the blocking request is not served). Also we put the client
5633 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
5634 * blocking for this keys.
5635 * - If a PUSH operation against a key with blocked clients waiting is
5636 * performed, we serve the first in the list: basically instead to push
5637 * the new element inside the list we return it to the (first / oldest)
5638 * blocking client, unblock the client, and remove it form the list.
5640 * The above comment and the source code should be enough in order to understand
5641 * the implementation and modify / fix it later.
5644 /* Set a client in blocking mode for the specified key, with the specified
5646 static void blockForKeys(redisClient
*c
, robj
**keys
, int numkeys
, time_t timeout
) {
5651 c
->blockingkeys
= zmalloc(sizeof(robj
*)*numkeys
);
5652 c
->blockingkeysnum
= numkeys
;
5653 c
->blockingto
= timeout
;
5654 for (j
= 0; j
< numkeys
; j
++) {
5655 /* Add the key in the client structure, to map clients -> keys */
5656 c
->blockingkeys
[j
] = keys
[j
];
5657 incrRefCount(keys
[j
]);
5659 /* And in the other "side", to map keys -> clients */
5660 de
= dictFind(c
->db
->blockingkeys
,keys
[j
]);
5664 /* For every key we take a list of clients blocked for it */
5666 retval
= dictAdd(c
->db
->blockingkeys
,keys
[j
],l
);
5667 incrRefCount(keys
[j
]);
5668 assert(retval
== DICT_OK
);
5670 l
= dictGetEntryVal(de
);
5672 listAddNodeTail(l
,c
);
5674 /* Mark the client as a blocked client */
5675 c
->flags
|= REDIS_BLOCKED
;
5676 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
5677 server
.blockedclients
++;
5680 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
5681 static void unblockClient(redisClient
*c
) {
5686 assert(c
->blockingkeys
!= NULL
);
5687 /* The client may wait for multiple keys, so unblock it for every key. */
5688 for (j
= 0; j
< c
->blockingkeysnum
; j
++) {
5689 /* Remove this client from the list of clients waiting for this key. */
5690 de
= dictFind(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
5692 l
= dictGetEntryVal(de
);
5693 listDelNode(l
,listSearchKey(l
,c
));
5694 /* If the list is empty we need to remove it to avoid wasting memory */
5695 if (listLength(l
) == 0)
5696 dictDelete(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
5697 decrRefCount(c
->blockingkeys
[j
]);
5699 /* Cleanup the client structure */
5700 zfree(c
->blockingkeys
);
5701 c
->blockingkeys
= NULL
;
5702 c
->flags
&= (~REDIS_BLOCKED
);
5703 server
.blockedclients
--;
5704 /* Ok now we are ready to get read events from socket, note that we
5705 * can't trap errors here as it's possible that unblockClients() is
5706 * called from freeClient() itself, and the only thing we can do
5707 * if we failed to register the READABLE event is to kill the client.
5708 * Still the following function should never fail in the real world as
5709 * we are sure the file descriptor is sane, and we exit on out of mem. */
5710 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
, readQueryFromClient
, c
);
5711 /* As a final step we want to process data if there is some command waiting
5712 * in the input buffer. Note that this is safe even if unblockClient()
5713 * gets called from freeClient() because freeClient() will be smart
5714 * enough to call this function *after* c->querybuf was set to NULL. */
5715 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0) processInputBuffer(c
);
5718 /* This should be called from any function PUSHing into lists.
5719 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
5720 * 'ele' is the element pushed.
5722 * If the function returns 0 there was no client waiting for a list push
5725 * If the function returns 1 there was a client waiting for a list push
5726 * against this key, the element was passed to this client thus it's not
5727 * needed to actually add it to the list and the caller should return asap. */
5728 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
) {
5729 struct dictEntry
*de
;
5730 redisClient
*receiver
;
5734 de
= dictFind(c
->db
->blockingkeys
,key
);
5735 if (de
== NULL
) return 0;
5736 l
= dictGetEntryVal(de
);
5739 receiver
= ln
->value
;
5741 addReplySds(receiver
,sdsnew("*2\r\n"));
5742 addReplyBulkLen(receiver
,key
);
5743 addReply(receiver
,key
);
5744 addReply(receiver
,shared
.crlf
);
5745 addReplyBulkLen(receiver
,ele
);
5746 addReply(receiver
,ele
);
5747 addReply(receiver
,shared
.crlf
);
5748 unblockClient(receiver
);
5752 /* Blocking RPOP/LPOP */
5753 static void blockingPopGenericCommand(redisClient
*c
, int where
) {
5758 for (j
= 1; j
< c
->argc
-1; j
++) {
5759 o
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
5761 if (o
->type
!= REDIS_LIST
) {
5762 addReply(c
,shared
.wrongtypeerr
);
5765 list
*list
= o
->ptr
;
5766 if (listLength(list
) != 0) {
5767 /* If the list contains elements fall back to the usual
5768 * non-blocking POP operation */
5769 robj
*argv
[2], **orig_argv
;
5772 /* We need to alter the command arguments before to call
5773 * popGenericCommand() as the command takes a single key. */
5774 orig_argv
= c
->argv
;
5775 orig_argc
= c
->argc
;
5776 argv
[1] = c
->argv
[j
];
5780 /* Also the return value is different, we need to output
5781 * the multi bulk reply header and the key name. The
5782 * "real" command will add the last element (the value)
5783 * for us. If this souds like an hack to you it's just
5784 * because it is... */
5785 addReplySds(c
,sdsnew("*2\r\n"));
5786 addReplyBulkLen(c
,argv
[1]);
5787 addReply(c
,argv
[1]);
5788 addReply(c
,shared
.crlf
);
5789 popGenericCommand(c
,where
);
5791 /* Fix the client structure with the original stuff */
5792 c
->argv
= orig_argv
;
5793 c
->argc
= orig_argc
;
5799 /* If the list is empty or the key does not exists we must block */
5800 timeout
= strtol(c
->argv
[c
->argc
-1]->ptr
,NULL
,10);
5801 if (timeout
> 0) timeout
+= time(NULL
);
5802 blockForKeys(c
,c
->argv
+1,c
->argc
-2,timeout
);
5805 static void blpopCommand(redisClient
*c
) {
5806 blockingPopGenericCommand(c
,REDIS_HEAD
);
5809 static void brpopCommand(redisClient
*c
) {
5810 blockingPopGenericCommand(c
,REDIS_TAIL
);
5813 /* =============================== Replication ============================= */
5815 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
5816 ssize_t nwritten
, ret
= size
;
5817 time_t start
= time(NULL
);
5821 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
5822 nwritten
= write(fd
,ptr
,size
);
5823 if (nwritten
== -1) return -1;
5827 if ((time(NULL
)-start
) > timeout
) {
5835 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
5836 ssize_t nread
, totread
= 0;
5837 time_t start
= time(NULL
);
5841 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
5842 nread
= read(fd
,ptr
,size
);
5843 if (nread
== -1) return -1;
5848 if ((time(NULL
)-start
) > timeout
) {
5856 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
5863 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
5866 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
5877 static void syncCommand(redisClient
*c
) {
5878 /* ignore SYNC if aleady slave or in monitor mode */
5879 if (c
->flags
& REDIS_SLAVE
) return;
5881 /* SYNC can't be issued when the server has pending data to send to
5882 * the client about already issued commands. We need a fresh reply
5883 * buffer registering the differences between the BGSAVE and the current
5884 * dataset, so that we can copy to other slaves if needed. */
5885 if (listLength(c
->reply
) != 0) {
5886 addReplySds(c
,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
5890 redisLog(REDIS_NOTICE
,"Slave ask for synchronization");
5891 /* Here we need to check if there is a background saving operation
5892 * in progress, or if it is required to start one */
5893 if (server
.bgsavechildpid
!= -1) {
5894 /* Ok a background save is in progress. Let's check if it is a good
5895 * one for replication, i.e. if there is another slave that is
5896 * registering differences since the server forked to save */
5900 listRewind(server
.slaves
);
5901 while((ln
= listYield(server
.slaves
))) {
5903 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) break;
5906 /* Perfect, the server is already registering differences for
5907 * another slave. Set the right state, and copy the buffer. */
5908 listRelease(c
->reply
);
5909 c
->reply
= listDup(slave
->reply
);
5910 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
5911 redisLog(REDIS_NOTICE
,"Waiting for end of BGSAVE for SYNC");
5913 /* No way, we need to wait for the next BGSAVE in order to
5914 * register differences */
5915 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
5916 redisLog(REDIS_NOTICE
,"Waiting for next BGSAVE for SYNC");
5919 /* Ok we don't have a BGSAVE in progress, let's start one */
5920 redisLog(REDIS_NOTICE
,"Starting BGSAVE for SYNC");
5921 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
5922 redisLog(REDIS_NOTICE
,"Replication failed, can't BGSAVE");
5923 addReplySds(c
,sdsnew("-ERR Unalbe to perform background save\r\n"));
5926 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
5929 c
->flags
|= REDIS_SLAVE
;
5931 listAddNodeTail(server
.slaves
,c
);
5935 static void sendBulkToSlave(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
5936 redisClient
*slave
= privdata
;
5938 REDIS_NOTUSED(mask
);
5939 char buf
[REDIS_IOBUF_LEN
];
5940 ssize_t nwritten
, buflen
;
5942 if (slave
->repldboff
== 0) {
5943 /* Write the bulk write count before to transfer the DB. In theory here
5944 * we don't know how much room there is in the output buffer of the
5945 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
5946 * operations) will never be smaller than the few bytes we need. */
5949 bulkcount
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
5951 if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
))
5959 lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
);
5960 buflen
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
);
5962 redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s",
5963 (buflen
== 0) ? "premature EOF" : strerror(errno
));
5967 if ((nwritten
= write(fd
,buf
,buflen
)) == -1) {
5968 redisLog(REDIS_DEBUG
,"Write error sending DB to slave: %s",
5973 slave
->repldboff
+= nwritten
;
5974 if (slave
->repldboff
== slave
->repldbsize
) {
5975 close(slave
->repldbfd
);
5976 slave
->repldbfd
= -1;
5977 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
5978 slave
->replstate
= REDIS_REPL_ONLINE
;
5979 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
,
5980 sendReplyToClient
, slave
) == AE_ERR
) {
5984 addReplySds(slave
,sdsempty());
5985 redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded");
5989 /* This function is called at the end of every backgrond saving.
5990 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
5991 * otherwise REDIS_ERR is passed to the function.
5993 * The goal of this function is to handle slaves waiting for a successful
5994 * background saving in order to perform non-blocking synchronization. */
5995 static void updateSlavesWaitingBgsave(int bgsaveerr
) {
5997 int startbgsave
= 0;
5999 listRewind(server
.slaves
);
6000 while((ln
= listYield(server
.slaves
))) {
6001 redisClient
*slave
= ln
->value
;
6003 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) {
6005 slave
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6006 } else if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) {
6007 struct redis_stat buf
;
6009 if (bgsaveerr
!= REDIS_OK
) {
6011 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error");
6014 if ((slave
->repldbfd
= open(server
.dbfilename
,O_RDONLY
)) == -1 ||
6015 redis_fstat(slave
->repldbfd
,&buf
) == -1) {
6017 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
));
6020 slave
->repldboff
= 0;
6021 slave
->repldbsize
= buf
.st_size
;
6022 slave
->replstate
= REDIS_REPL_SEND_BULK
;
6023 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
6024 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, sendBulkToSlave
, slave
) == AE_ERR
) {
6031 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
6032 listRewind(server
.slaves
);
6033 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed");
6034 while((ln
= listYield(server
.slaves
))) {
6035 redisClient
*slave
= ln
->value
;
6037 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
)
6044 static int syncWithMaster(void) {
6045 char buf
[1024], tmpfile
[256], authcmd
[1024];
6047 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
6051 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
6056 /* AUTH with the master if required. */
6057 if(server
.masterauth
) {
6058 snprintf(authcmd
, 1024, "AUTH %s\r\n", server
.masterauth
);
6059 if (syncWrite(fd
, authcmd
, strlen(server
.masterauth
)+7, 5) == -1) {
6061 redisLog(REDIS_WARNING
,"Unable to AUTH to MASTER: %s",
6065 /* Read the AUTH result. */
6066 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6068 redisLog(REDIS_WARNING
,"I/O error reading auth result from MASTER: %s",
6072 if (buf
[0] != '+') {
6074 redisLog(REDIS_WARNING
,"Cannot AUTH to MASTER, is the masterauth password correct?");
6079 /* Issue the SYNC command */
6080 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
6082 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
6086 /* Read the bulk write count */
6087 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6089 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
6093 if (buf
[0] != '$') {
6095 redisLog(REDIS_WARNING
,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
6098 dumpsize
= atoi(buf
+1);
6099 redisLog(REDIS_NOTICE
,"Receiving %d bytes data dump from MASTER",dumpsize
);
6100 /* Read the bulk write data on a temp file */
6101 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
6102 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644);
6105 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
6109 int nread
, nwritten
;
6111 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
6113 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
6119 nwritten
= write(dfd
,buf
,nread
);
6120 if (nwritten
== -1) {
6121 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
6129 if (rename(tmpfile
,server
.dbfilename
) == -1) {
6130 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
6136 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
6137 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
6141 server
.master
= createClient(fd
);
6142 server
.master
->flags
|= REDIS_MASTER
;
6143 server
.master
->authenticated
= 1;
6144 server
.replstate
= REDIS_REPL_CONNECTED
;
6148 static void slaveofCommand(redisClient
*c
) {
6149 if (!strcasecmp(c
->argv
[1]->ptr
,"no") &&
6150 !strcasecmp(c
->argv
[2]->ptr
,"one")) {
6151 if (server
.masterhost
) {
6152 sdsfree(server
.masterhost
);
6153 server
.masterhost
= NULL
;
6154 if (server
.master
) freeClient(server
.master
);
6155 server
.replstate
= REDIS_REPL_NONE
;
6156 redisLog(REDIS_NOTICE
,"MASTER MODE enabled (user request)");
6159 sdsfree(server
.masterhost
);
6160 server
.masterhost
= sdsdup(c
->argv
[1]->ptr
);
6161 server
.masterport
= atoi(c
->argv
[2]->ptr
);
6162 if (server
.master
) freeClient(server
.master
);
6163 server
.replstate
= REDIS_REPL_CONNECT
;
6164 redisLog(REDIS_NOTICE
,"SLAVE OF %s:%d enabled (user request)",
6165 server
.masterhost
, server
.masterport
);
6167 addReply(c
,shared
.ok
);
6170 /* ============================ Maxmemory directive ======================== */
6172 /* This function gets called when 'maxmemory' is set on the config file to limit
6173 * the max memory used by the server, and we are out of memory.
6174 * This function will try to, in order:
6176 * - Free objects from the free list
6177 * - Try to remove keys with an EXPIRE set
6179 * It is not possible to free enough memory to reach used-memory < maxmemory
6180 * the server will start refusing commands that will enlarge even more the
6183 static void freeMemoryIfNeeded(void) {
6184 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
6185 if (listLength(server
.objfreelist
)) {
6188 listNode
*head
= listFirst(server
.objfreelist
);
6189 o
= listNodeValue(head
);
6190 listDelNode(server
.objfreelist
,head
);
6193 int j
, k
, freed
= 0;
6195 for (j
= 0; j
< server
.dbnum
; j
++) {
6197 robj
*minkey
= NULL
;
6198 struct dictEntry
*de
;
6200 if (dictSize(server
.db
[j
].expires
)) {
6202 /* From a sample of three keys drop the one nearest to
6203 * the natural expire */
6204 for (k
= 0; k
< 3; k
++) {
6207 de
= dictGetRandomKey(server
.db
[j
].expires
);
6208 t
= (time_t) dictGetEntryVal(de
);
6209 if (minttl
== -1 || t
< minttl
) {
6210 minkey
= dictGetEntryKey(de
);
6214 deleteKey(server
.db
+j
,minkey
);
6217 if (!freed
) return; /* nothing to free... */
6222 /* ============================== Append Only file ========================== */
6224 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
6225 sds buf
= sdsempty();
6231 /* The DB this command was targetting is not the same as the last command
6232 * we appendend. To issue a SELECT command is needed. */
6233 if (dictid
!= server
.appendseldb
) {
6236 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
6237 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
6238 (unsigned long)strlen(seldb
),seldb
);
6239 server
.appendseldb
= dictid
;
6242 /* "Fix" the argv vector if the command is EXPIRE. We want to translate
6243 * EXPIREs into EXPIREATs calls */
6244 if (cmd
->proc
== expireCommand
) {
6247 tmpargv
[0] = createStringObject("EXPIREAT",8);
6248 tmpargv
[1] = argv
[1];
6249 incrRefCount(argv
[1]);
6250 when
= time(NULL
)+strtol(argv
[2]->ptr
,NULL
,10);
6251 tmpargv
[2] = createObject(REDIS_STRING
,
6252 sdscatprintf(sdsempty(),"%ld",when
));
6256 /* Append the actual command */
6257 buf
= sdscatprintf(buf
,"*%d\r\n",argc
);
6258 for (j
= 0; j
< argc
; j
++) {
6261 o
= getDecodedObject(o
);
6262 buf
= sdscatprintf(buf
,"$%lu\r\n",(unsigned long)sdslen(o
->ptr
));
6263 buf
= sdscatlen(buf
,o
->ptr
,sdslen(o
->ptr
));
6264 buf
= sdscatlen(buf
,"\r\n",2);
6268 /* Free the objects from the modified argv for EXPIREAT */
6269 if (cmd
->proc
== expireCommand
) {
6270 for (j
= 0; j
< 3; j
++)
6271 decrRefCount(argv
[j
]);
6274 /* We want to perform a single write. This should be guaranteed atomic
6275 * at least if the filesystem we are writing is a real physical one.
6276 * While this will save us against the server being killed I don't think
6277 * there is much to do about the whole server stopping for power problems
6279 nwritten
= write(server
.appendfd
,buf
,sdslen(buf
));
6280 if (nwritten
!= (signed)sdslen(buf
)) {
6281 /* Ooops, we are in troubles. The best thing to do for now is
6282 * to simply exit instead to give the illusion that everything is
6283 * working as expected. */
6284 if (nwritten
== -1) {
6285 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
6287 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
6291 /* If a background append only file rewriting is in progress we want to
6292 * accumulate the differences between the child DB and the current one
6293 * in a buffer, so that when the child process will do its work we
6294 * can append the differences to the new append only file. */
6295 if (server
.bgrewritechildpid
!= -1)
6296 server
.bgrewritebuf
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
));
6300 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
||
6301 (server
.appendfsync
== APPENDFSYNC_EVERYSEC
&&
6302 now
-server
.lastfsync
> 1))
6304 fsync(server
.appendfd
); /* Let's try to get this data on the disk */
6305 server
.lastfsync
= now
;
6309 /* In Redis commands are always executed in the context of a client, so in
6310 * order to load the append only file we need to create a fake client. */
6311 static struct redisClient
*createFakeClient(void) {
6312 struct redisClient
*c
= zmalloc(sizeof(*c
));
6316 c
->querybuf
= sdsempty();
6320 /* We set the fake client as a slave waiting for the synchronization
6321 * so that Redis will not try to send replies to this client. */
6322 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
6323 c
->reply
= listCreate();
6324 listSetFreeMethod(c
->reply
,decrRefCount
);
6325 listSetDupMethod(c
->reply
,dupClientReplyValue
);
6329 static void freeFakeClient(struct redisClient
*c
) {
6330 sdsfree(c
->querybuf
);
6331 listRelease(c
->reply
);
6335 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
6336 * error (the append only file is zero-length) REDIS_ERR is returned. On
6337 * fatal error an error message is logged and the program exists. */
6338 int loadAppendOnlyFile(char *filename
) {
6339 struct redisClient
*fakeClient
;
6340 FILE *fp
= fopen(filename
,"r");
6341 struct redis_stat sb
;
6343 if (redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0)
6347 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
6351 fakeClient
= createFakeClient();
6358 struct redisCommand
*cmd
;
6360 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
6366 if (buf
[0] != '*') goto fmterr
;
6368 argv
= zmalloc(sizeof(robj
*)*argc
);
6369 for (j
= 0; j
< argc
; j
++) {
6370 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
6371 if (buf
[0] != '$') goto fmterr
;
6372 len
= strtol(buf
+1,NULL
,10);
6373 argsds
= sdsnewlen(NULL
,len
);
6374 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
6375 argv
[j
] = createObject(REDIS_STRING
,argsds
);
6376 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
6379 /* Command lookup */
6380 cmd
= lookupCommand(argv
[0]->ptr
);
6382 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
6385 /* Try object sharing and encoding */
6386 if (server
.shareobjects
) {
6388 for(j
= 1; j
< argc
; j
++)
6389 argv
[j
] = tryObjectSharing(argv
[j
]);
6391 if (cmd
->flags
& REDIS_CMD_BULK
)
6392 tryObjectEncoding(argv
[argc
-1]);
6393 /* Run the command in the context of a fake client */
6394 fakeClient
->argc
= argc
;
6395 fakeClient
->argv
= argv
;
6396 cmd
->proc(fakeClient
);
6397 /* Discard the reply objects list from the fake client */
6398 while(listLength(fakeClient
->reply
))
6399 listDelNode(fakeClient
->reply
,listFirst(fakeClient
->reply
));
6400 /* Clean up, ready for the next command */
6401 for (j
= 0; j
< argc
; j
++) decrRefCount(argv
[j
]);
6405 freeFakeClient(fakeClient
);
6410 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
6412 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
6416 redisLog(REDIS_WARNING
,"Bad file format reading the append only file");
6420 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
6421 static int fwriteBulk(FILE *fp
, robj
*obj
) {
6423 obj
= getDecodedObject(obj
);
6424 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(long)sdslen(obj
->ptr
));
6425 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) goto err
;
6426 if (sdslen(obj
->ptr
) && fwrite(obj
->ptr
,sdslen(obj
->ptr
),1,fp
) == 0)
6428 if (fwrite("\r\n",2,1,fp
) == 0) goto err
;
6436 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
6437 static int fwriteBulkDouble(FILE *fp
, double d
) {
6438 char buf
[128], dbuf
[128];
6440 snprintf(dbuf
,sizeof(dbuf
),"%.17g\r\n",d
);
6441 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(dbuf
)-2);
6442 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
6443 if (fwrite(dbuf
,strlen(dbuf
),1,fp
) == 0) return 0;
6447 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
6448 static int fwriteBulkLong(FILE *fp
, long l
) {
6449 char buf
[128], lbuf
[128];
6451 snprintf(lbuf
,sizeof(lbuf
),"%ld\r\n",l
);
6452 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(lbuf
)-2);
6453 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
6454 if (fwrite(lbuf
,strlen(lbuf
),1,fp
) == 0) return 0;
6458 /* Write a sequence of commands able to fully rebuild the dataset into
6459 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
6460 static int rewriteAppendOnlyFile(char *filename
) {
6461 dictIterator
*di
= NULL
;
6466 time_t now
= time(NULL
);
6468 /* Note that we have to use a different temp name here compared to the
6469 * one used by rewriteAppendOnlyFileBackground() function. */
6470 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
6471 fp
= fopen(tmpfile
,"w");
6473 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
6476 for (j
= 0; j
< server
.dbnum
; j
++) {
6477 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
6478 redisDb
*db
= server
.db
+j
;
6480 if (dictSize(d
) == 0) continue;
6481 di
= dictGetIterator(d
);
6487 /* SELECT the new DB */
6488 if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
;
6489 if (fwriteBulkLong(fp
,j
) == 0) goto werr
;
6491 /* Iterate this DB writing every entry */
6492 while((de
= dictNext(di
)) != NULL
) {
6493 robj
*key
= dictGetEntryKey(de
);
6494 robj
*o
= dictGetEntryVal(de
);
6495 time_t expiretime
= getExpire(db
,key
);
6497 /* Save the key and associated value */
6498 if (o
->type
== REDIS_STRING
) {
6499 /* Emit a SET command */
6500 char cmd
[]="*3\r\n$3\r\nSET\r\n";
6501 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6503 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6504 if (fwriteBulk(fp
,o
) == 0) goto werr
;
6505 } else if (o
->type
== REDIS_LIST
) {
6506 /* Emit the RPUSHes needed to rebuild the list */
6507 list
*list
= o
->ptr
;
6511 while((ln
= listYield(list
))) {
6512 char cmd
[]="*3\r\n$5\r\nRPUSH\r\n";
6513 robj
*eleobj
= listNodeValue(ln
);
6515 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6516 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6517 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6519 } else if (o
->type
== REDIS_SET
) {
6520 /* Emit the SADDs needed to rebuild the set */
6522 dictIterator
*di
= dictGetIterator(set
);
6525 while((de
= dictNext(di
)) != NULL
) {
6526 char cmd
[]="*3\r\n$4\r\nSADD\r\n";
6527 robj
*eleobj
= dictGetEntryKey(de
);
6529 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6530 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6531 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6533 dictReleaseIterator(di
);
6534 } else if (o
->type
== REDIS_ZSET
) {
6535 /* Emit the ZADDs needed to rebuild the sorted set */
6537 dictIterator
*di
= dictGetIterator(zs
->dict
);
6540 while((de
= dictNext(di
)) != NULL
) {
6541 char cmd
[]="*4\r\n$4\r\nZADD\r\n";
6542 robj
*eleobj
= dictGetEntryKey(de
);
6543 double *score
= dictGetEntryVal(de
);
6545 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6546 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6547 if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
;
6548 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6550 dictReleaseIterator(di
);
6552 redisAssert(0 != 0);
6554 /* Save the expire time */
6555 if (expiretime
!= -1) {
6556 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n";
6557 /* If this key is already expired skip it */
6558 if (expiretime
< now
) continue;
6559 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6560 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6561 if (fwriteBulkLong(fp
,expiretime
) == 0) goto werr
;
6564 dictReleaseIterator(di
);
6567 /* Make sure data will not remain on the OS's output buffers */
6572 /* Use RENAME to make sure the DB file is changed atomically only
6573 * if the generate DB file is ok. */
6574 if (rename(tmpfile
,filename
) == -1) {
6575 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
6579 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
6585 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
6586 if (di
) dictReleaseIterator(di
);
6590 /* This is how rewriting of the append only file in background works:
6592 * 1) The user calls BGREWRITEAOF
6593 * 2) Redis calls this function, that forks():
6594 * 2a) the child rewrite the append only file in a temp file.
6595 * 2b) the parent accumulates differences in server.bgrewritebuf.
6596 * 3) When the child finished '2a' exists.
6597 * 4) The parent will trap the exit code, if it's OK, will append the
6598 * data accumulated into server.bgrewritebuf into the temp file, and
6599 * finally will rename(2) the temp file in the actual file name.
6600 * The the new file is reopened as the new append only file. Profit!
6602 static int rewriteAppendOnlyFileBackground(void) {
6605 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
6606 if ((childpid
= fork()) == 0) {
6611 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
6612 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
6619 if (childpid
== -1) {
6620 redisLog(REDIS_WARNING
,
6621 "Can't rewrite append only file in background: fork: %s",
6625 redisLog(REDIS_NOTICE
,
6626 "Background append only file rewriting started by pid %d",childpid
);
6627 server
.bgrewritechildpid
= childpid
;
6628 /* We set appendseldb to -1 in order to force the next call to the
6629 * feedAppendOnlyFile() to issue a SELECT command, so the differences
6630 * accumulated by the parent into server.bgrewritebuf will start
6631 * with a SELECT statement and it will be safe to merge. */
6632 server
.appendseldb
= -1;
6635 return REDIS_OK
; /* unreached */
6638 static void bgrewriteaofCommand(redisClient
*c
) {
6639 if (server
.bgrewritechildpid
!= -1) {
6640 addReplySds(c
,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
6643 if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
6644 char *status
= "+Background append only file rewriting started\r\n";
6645 addReplySds(c
,sdsnew(status
));
6647 addReply(c
,shared
.err
);
6651 static void aofRemoveTempFile(pid_t childpid
) {
6654 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
6658 /* =============================== Virtual Memory =========================== */
6659 static void vmInit(void) {
6662 server
.vm_fp
= fopen("/tmp/redisvm","w+b");
6663 if (server
.vm_fp
== NULL
) {
6664 redisLog(REDIS_WARNING
,"Impossible to open the swap file. Exiting.");
6667 server
.vm_fd
= fileno(server
.vm_fp
);
6668 server
.vm_next_page
= 0;
6669 server
.vm_near_pages
= 0;
6670 totsize
= server
.vm_pages
*server
.vm_page_size
;
6671 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
6672 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
6673 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
6677 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
6679 server
.vm_bitmap
= zmalloc((server
.vm_pages
+7)/8);
6680 redisLog(REDIS_DEBUG
,"Allocated %lld bytes page table for %lld pages",
6681 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
6682 memset(server
.vm_bitmap
,0,(server
.vm_pages
+7)/8);
6683 /* Try to remove the swap file, so the OS will really delete it from the
6684 * file system when Redis exists. */
6685 unlink("/tmp/redisvm");
6688 /* Mark the page as used */
6689 static void vmMarkPageUsed(off_t page
) {
6690 off_t byte
= page
/8;
6692 server
.vm_bitmap
[byte
] |= 1<<bit
;
6693 printf("Mark used: %lld (byte:%lld bit:%d)\n", (long long)page
,
6694 (long long)byte
, bit
);
6697 /* Mark N contiguous pages as used, with 'page' being the first. */
6698 static void vmMarkPagesUsed(off_t page
, off_t count
) {
6701 for (j
= 0; j
< count
; j
++)
6702 vmMarkPageUsed(page
+j
);
6705 /* Mark the page as free */
6706 static void vmMarkPageFree(off_t page
) {
6707 off_t byte
= page
/8;
6709 server
.vm_bitmap
[byte
] &= ~(1<<bit
);
6712 /* Mark N contiguous pages as free, with 'page' being the first. */
6713 static void vmMarkPagesFree(off_t page
, off_t count
) {
6716 for (j
= 0; j
< count
; j
++)
6717 vmMarkPageFree(page
+j
);
6720 /* Test if the page is free */
6721 static int vmFreePage(off_t page
) {
6722 off_t byte
= page
/8;
6724 return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0;
6727 /* Find N contiguous free pages storing the first page of the cluster in *first.
6728 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
6729 * REDIS_ERR is returned.
6731 * This function uses a simple algorithm: we try to allocate
6732 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
6733 * again from the start of the swap file searching for free spaces.
6735 * If it looks pretty clear that there are no free pages near our offset
6736 * we try to find less populated places doing a forward jump of
6737 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
6738 * without hurry, and then we jump again and so forth...
6740 * This function can be improved using a free list to avoid to guess
6741 * too much, since we could collect data about freed pages.
6743 * note: I implemented this function just after watching an episode of
6744 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
6746 static int vmFindContiguousPages(off_t
*first
, int n
) {
6747 off_t base
, offset
= 0, since_jump
= 0, numfree
= 0;
6749 if (server
.vm_near_pages
== REDIS_VM_MAX_NEAR_PAGES
) {
6750 server
.vm_near_pages
= 0;
6751 server
.vm_next_page
= 0;
6753 server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */
6754 base
= server
.vm_next_page
;
6756 while(offset
< server
.vm_pages
) {
6757 off_t
this = base
+offset
;
6759 printf("THIS: %lld (%c)\n", (long long) this, vmFreePage(this) ? 'F' : 'X');
6760 /* If we overflow, restart from page zero */
6761 if (this >= server
.vm_pages
) {
6762 this -= server
.vm_pages
;
6764 /* Just overflowed, what we found on tail is no longer
6765 * interesting, as it's no longer contiguous. */
6769 if (vmFreePage(this)) {
6770 /* This is a free page */
6772 /* Already got N free pages? Return to the caller, with success */
6774 *first
= this-(n
-1);
6775 server
.vm_next_page
= this+1;
6779 /* The current one is not a free page */
6783 /* Fast-forward if the current page is not free and we already
6784 * searched enough near this place. */
6786 if (!numfree
&& since_jump
>= REDIS_VM_MAX_RANDOM_JUMP
/4) {
6787 offset
+= random() % REDIS_VM_MAX_RANDOM_JUMP
;
6789 /* Note that even if we rewind after the jump, we are don't need
6790 * to make sure numfree is set to zero as we only jump *if* it
6791 * is set to zero. */
6793 /* Otherwise just check the next page */
6800 /* Swap the 'val' object relative to 'key' into disk. Store all the information
6801 * needed to later retrieve the object into the key object.
6802 * If we can't find enough contiguous empty pages to swap the object on disk
6803 * REDIS_ERR is returned. */
6804 static int vmSwapObject(robj
*key
, robj
*val
) {
6805 off_t pages
= rdbSavedObjectPages(val
);
6808 assert(key
->storage
== REDIS_VM_MEMORY
);
6809 assert(key
->refcount
== 1);
6810 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return REDIS_ERR
;
6811 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
6812 redisLog(REDIS_WARNING
,
6813 "Critical VM problem in vmSwapObject(): can't seek: %s",
6817 rdbSaveObject(server
.vm_fp
,val
);
6818 key
->vm
.page
= page
;
6819 key
->vm
.usedpages
= pages
;
6820 key
->storage
= REDIS_VM_SWAPPED
;
6821 key
->vtype
= val
->type
;
6822 decrRefCount(val
); /* Deallocate the object from memory. */
6823 vmMarkPagesUsed(page
,pages
);
6824 redisLog(REDIS_DEBUG
,"VM: object %s swapped out at %lld (%lld pages)",
6825 (unsigned char*) key
->ptr
,
6826 (unsigned long long) page
, (unsigned long long) pages
);
6830 /* Load the value object relative to the 'key' object from swap to memory.
6831 * The newly allocated object is returned. */
6832 static robj
*vmLoadObject(robj
*key
) {
6835 assert(key
->storage
== REDIS_VM_SWAPPED
);
6836 if (fseeko(server
.vm_fp
,key
->vm
.page
*server
.vm_page_size
,SEEK_SET
) == -1) {
6837 redisLog(REDIS_WARNING
,
6838 "Unrecoverable VM problem in vmLoadObject(): can't seek: %s",
6842 val
= rdbLoadObject(key
->vtype
,server
.vm_fp
);
6844 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmLoadObject(): can't load object from swap file: %s", strerror(errno
));
6847 key
->storage
= REDIS_VM_MEMORY
;
6848 key
->vm
.atime
= server
.unixtime
;
6849 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
6850 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk",
6851 (unsigned char*) key
->ptr
);
6855 /* How a good candidate is this object for swapping?
6856 * The better candidate it is, the greater the returned value.
6858 * Currently we try to perform a fast estimation of the object size in
6859 * memory, and combine it with aging informations.
6861 * Basically swappability = idle-time * log(estimated size)
6863 * Bigger objects are preferred over smaller objects, but not
6864 * proportionally, this is why we use the logarithm. This algorithm is
6865 * just a first try and will probably be tuned later. */
6866 static double computeObjectSwappability(robj
*o
) {
6867 time_t age
= server
.unixtime
- o
->vm
.atime
;
6871 struct dictEntry
*de
;
6874 if (age
<= 0) return 0;
6877 if (o
->encoding
!= REDIS_ENCODING_RAW
) {
6880 asize
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2;
6885 listNode
*ln
= listFirst(l
);
6887 asize
= sizeof(list
);
6889 robj
*ele
= ln
->value
;
6892 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
6893 (sizeof(*o
)+sdslen(ele
->ptr
)) :
6895 asize
+= (sizeof(listNode
)+elesize
)*listLength(l
);
6900 z
= (o
->type
== REDIS_ZSET
);
6901 d
= z
? ((zset
*)o
->ptr
)->dict
: o
->ptr
;
6903 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
6904 if (z
) asize
+= sizeof(zset
)-sizeof(dict
);
6909 de
= dictGetRandomKey(d
);
6910 ele
= dictGetEntryKey(de
);
6911 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
6912 (sizeof(*o
)+sdslen(ele
->ptr
)) :
6914 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
6915 if (z
) asize
+= sizeof(zskiplistNode
)*dictSize(d
);
6919 return (double)asize
*log(1+asize
);
6922 /* Try to swap an object that's a good candidate for swapping.
6923 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
6924 * to swap any object at all. */
6925 static int vmSwapOneObject(void) {
6927 struct dictEntry
*best
= NULL
;
6928 double best_swappability
= 0;
6931 for (j
= 0; j
< server
.dbnum
; j
++) {
6932 redisDb
*db
= server
.db
+j
;
6934 if (dictSize(db
->dict
) == 0) continue;
6935 for (i
= 0; i
< 5; i
++) {
6937 double swappability
;
6939 de
= dictGetRandomKey(db
->dict
);
6940 key
= dictGetEntryKey(de
);
6941 val
= dictGetEntryVal(de
);
6942 if (key
->storage
!= REDIS_VM_MEMORY
) continue;
6943 swappability
= computeObjectSwappability(val
);
6944 if (!best
|| swappability
> best_swappability
) {
6946 best_swappability
= swappability
;
6950 if (best
== NULL
) return REDIS_ERR
;
6951 key
= dictGetEntryKey(best
);
6952 val
= dictGetEntryVal(best
);
6954 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f\n",
6955 key
->ptr
, best_swappability
);
6957 /* Unshare the key if needed */
6958 if (key
->refcount
> 1) {
6959 robj
*newkey
= dupStringObject(key
);
6961 key
= dictGetEntryKey(best
) = newkey
;
6964 if (vmSwapObject(key
,val
) == REDIS_OK
) {
6965 dictGetEntryVal(best
) = NULL
;
6972 /* ================================= Debugging ============================== */
6974 static void debugCommand(redisClient
*c
) {
6975 if (!strcasecmp(c
->argv
[1]->ptr
,"segfault")) {
6977 } else if (!strcasecmp(c
->argv
[1]->ptr
,"reload")) {
6978 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
6979 addReply(c
,shared
.err
);
6983 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
6984 addReply(c
,shared
.err
);
6987 redisLog(REDIS_WARNING
,"DB reloaded by DEBUG RELOAD");
6988 addReply(c
,shared
.ok
);
6989 } else if (!strcasecmp(c
->argv
[1]->ptr
,"loadaof")) {
6991 if (loadAppendOnlyFile(server
.appendfilename
) != REDIS_OK
) {
6992 addReply(c
,shared
.err
);
6995 redisLog(REDIS_WARNING
,"Append Only File loaded by DEBUG LOADAOF");
6996 addReply(c
,shared
.ok
);
6997 } else if (!strcasecmp(c
->argv
[1]->ptr
,"object") && c
->argc
== 3) {
6998 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
7002 addReply(c
,shared
.nokeyerr
);
7005 key
= dictGetEntryKey(de
);
7006 val
= dictGetEntryVal(de
);
7007 addReplySds(c
,sdscatprintf(sdsempty(),
7008 "+Key at:%p refcount:%d, value at:%p refcount:%d encoding:%d serializedlength:%lld\r\n",
7009 (void*)key
, key
->refcount
, (void*)val
, val
->refcount
,
7010 val
->encoding
, rdbSavedObjectLen(val
)));
7011 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapout") && c
->argc
== 3) {
7012 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
7015 if (!server
.vm_enabled
) {
7016 addReplySds(c
,sdsnew("-ERR Virtual Memory is disabled\r\n"));
7020 addReply(c
,shared
.nokeyerr
);
7023 key
= dictGetEntryKey(de
);
7024 val
= dictGetEntryVal(de
);
7025 /* If the key is shared we want to create a copy */
7026 if (key
->refcount
> 1) {
7027 robj
*newkey
= dupStringObject(key
);
7029 key
= dictGetEntryKey(de
) = newkey
;
7032 if (key
->storage
!= REDIS_VM_MEMORY
) {
7033 addReplySds(c
,sdsnew("-ERR This key is not in memory\r\n"));
7034 } else if (vmSwapObject(key
,val
) == REDIS_OK
) {
7035 dictGetEntryVal(de
) = NULL
;
7036 addReply(c
,shared
.ok
);
7038 addReply(c
,shared
.err
);
7041 addReplySds(c
,sdsnew(
7042 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPOUT <key>|RELOAD]\r\n"));
7046 static void _redisAssert(char *estr
) {
7047 redisLog(REDIS_WARNING
,"=== ASSERTION FAILED ===");
7048 redisLog(REDIS_WARNING
,"==> %s\n",estr
);
7049 #ifdef HAVE_BACKTRACE
7050 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
7055 /* =================================== Main! ================================ */
7058 int linuxOvercommitMemoryValue(void) {
7059 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
7063 if (fgets(buf
,64,fp
) == NULL
) {
7072 void linuxOvercommitMemoryWarning(void) {
7073 if (linuxOvercommitMemoryValue() == 0) {
7074 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.");
7077 #endif /* __linux__ */
7079 static void daemonize(void) {
7083 if (fork() != 0) exit(0); /* parent exits */
7084 printf("New pid: %d\n", getpid());
7085 setsid(); /* create a new session */
7087 /* Every output goes to /dev/null. If Redis is daemonized but
7088 * the 'logfile' is set to 'stdout' in the configuration file
7089 * it will not log at all. */
7090 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
7091 dup2(fd
, STDIN_FILENO
);
7092 dup2(fd
, STDOUT_FILENO
);
7093 dup2(fd
, STDERR_FILENO
);
7094 if (fd
> STDERR_FILENO
) close(fd
);
7096 /* Try to write the pid file */
7097 fp
= fopen(server
.pidfile
,"w");
7099 fprintf(fp
,"%d\n",getpid());
7104 int main(int argc
, char **argv
) {
7107 resetServerSaveParams();
7108 loadServerConfig(argv
[1]);
7109 } else if (argc
> 2) {
7110 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
7113 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'");
7115 if (server
.daemonize
) daemonize();
7117 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
7119 linuxOvercommitMemoryWarning();
7121 if (server
.appendonly
) {
7122 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
7123 redisLog(REDIS_NOTICE
,"DB loaded from append only file");
7125 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
7126 redisLog(REDIS_NOTICE
,"DB loaded from disk");
7128 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
7129 acceptHandler
, NULL
) == AE_ERR
) oom("creating file event");
7130 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
7132 aeDeleteEventLoop(server
.el
);
7136 /* ============================= Backtrace support ========================= */
7138 #ifdef HAVE_BACKTRACE
7139 static char *findFuncName(void *pointer
, unsigned long *offset
);
7141 static void *getMcontextEip(ucontext_t
*uc
) {
7142 #if defined(__FreeBSD__)
7143 return (void*) uc
->uc_mcontext
.mc_eip
;
7144 #elif defined(__dietlibc__)
7145 return (void*) uc
->uc_mcontext
.eip
;
7146 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
7148 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
7150 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
7152 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
7153 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
7154 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
7156 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
7158 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
7159 return (void*) uc
->uc_mcontext
.gregs
[REG_EIP
]; /* Linux 32/64 bit */
7160 #elif defined(__ia64__) /* Linux IA64 */
7161 return (void*) uc
->uc_mcontext
.sc_ip
;
7167 static void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
7169 char **messages
= NULL
;
7170 int i
, trace_size
= 0;
7171 unsigned long offset
=0;
7172 ucontext_t
*uc
= (ucontext_t
*) secret
;
7174 REDIS_NOTUSED(info
);
7176 redisLog(REDIS_WARNING
,
7177 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
7178 infostring
= genRedisInfoString();
7179 redisLog(REDIS_WARNING
, "%s",infostring
);
7180 /* It's not safe to sdsfree() the returned string under memory
7181 * corruption conditions. Let it leak as we are going to abort */
7183 trace_size
= backtrace(trace
, 100);
7184 /* overwrite sigaction with caller's address */
7185 if (getMcontextEip(uc
) != NULL
) {
7186 trace
[1] = getMcontextEip(uc
);
7188 messages
= backtrace_symbols(trace
, trace_size
);
7190 for (i
=1; i
<trace_size
; ++i
) {
7191 char *fn
= findFuncName(trace
[i
], &offset
), *p
;
7193 p
= strchr(messages
[i
],'+');
7194 if (!fn
|| (p
&& ((unsigned long)strtol(p
+1,NULL
,10)) < offset
)) {
7195 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
7197 redisLog(REDIS_WARNING
,"%d redis-server %p %s + %d", i
, trace
[i
], fn
, (unsigned int)offset
);
7200 /* free(messages); Don't call free() with possibly corrupted memory. */
7204 static void setupSigSegvAction(void) {
7205 struct sigaction act
;
7207 sigemptyset (&act
.sa_mask
);
7208 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
7209 * is used. Otherwise, sa_handler is used */
7210 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
7211 act
.sa_sigaction
= segvHandler
;
7212 sigaction (SIGSEGV
, &act
, NULL
);
7213 sigaction (SIGBUS
, &act
, NULL
);
7214 sigaction (SIGFPE
, &act
, NULL
);
7215 sigaction (SIGILL
, &act
, NULL
);
7216 sigaction (SIGBUS
, &act
, NULL
);
7220 #include "staticsymbols.h"
7221 /* This function try to convert a pointer into a function name. It's used in
7222 * oreder to provide a backtrace under segmentation fault that's able to
7223 * display functions declared as static (otherwise the backtrace is useless). */
7224 static char *findFuncName(void *pointer
, unsigned long *offset
){
7226 unsigned long off
, minoff
= 0;
7228 /* Try to match against the Symbol with the smallest offset */
7229 for (i
=0; symsTable
[i
].pointer
; i
++) {
7230 unsigned long lp
= (unsigned long) pointer
;
7232 if (lp
!= (unsigned long)-1 && lp
>= symsTable
[i
].pointer
) {
7233 off
=lp
-symsTable
[i
].pointer
;
7234 if (ret
< 0 || off
< minoff
) {
7240 if (ret
== -1) return NULL
;
7242 return symsTable
[ret
].name
;
7244 #else /* HAVE_BACKTRACE */
7245 static void setupSigSegvAction(void) {
7247 #endif /* HAVE_BACKTRACE */