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 robj
*vmPreviewObject(robj
*key
);
496 static int vmSwapOneObject(void);
497 static int vmCanSwapOut(void);
499 static void authCommand(redisClient
*c
);
500 static void pingCommand(redisClient
*c
);
501 static void echoCommand(redisClient
*c
);
502 static void setCommand(redisClient
*c
);
503 static void setnxCommand(redisClient
*c
);
504 static void getCommand(redisClient
*c
);
505 static void delCommand(redisClient
*c
);
506 static void existsCommand(redisClient
*c
);
507 static void incrCommand(redisClient
*c
);
508 static void decrCommand(redisClient
*c
);
509 static void incrbyCommand(redisClient
*c
);
510 static void decrbyCommand(redisClient
*c
);
511 static void selectCommand(redisClient
*c
);
512 static void randomkeyCommand(redisClient
*c
);
513 static void keysCommand(redisClient
*c
);
514 static void dbsizeCommand(redisClient
*c
);
515 static void lastsaveCommand(redisClient
*c
);
516 static void saveCommand(redisClient
*c
);
517 static void bgsaveCommand(redisClient
*c
);
518 static void bgrewriteaofCommand(redisClient
*c
);
519 static void shutdownCommand(redisClient
*c
);
520 static void moveCommand(redisClient
*c
);
521 static void renameCommand(redisClient
*c
);
522 static void renamenxCommand(redisClient
*c
);
523 static void lpushCommand(redisClient
*c
);
524 static void rpushCommand(redisClient
*c
);
525 static void lpopCommand(redisClient
*c
);
526 static void rpopCommand(redisClient
*c
);
527 static void llenCommand(redisClient
*c
);
528 static void lindexCommand(redisClient
*c
);
529 static void lrangeCommand(redisClient
*c
);
530 static void ltrimCommand(redisClient
*c
);
531 static void typeCommand(redisClient
*c
);
532 static void lsetCommand(redisClient
*c
);
533 static void saddCommand(redisClient
*c
);
534 static void sremCommand(redisClient
*c
);
535 static void smoveCommand(redisClient
*c
);
536 static void sismemberCommand(redisClient
*c
);
537 static void scardCommand(redisClient
*c
);
538 static void spopCommand(redisClient
*c
);
539 static void srandmemberCommand(redisClient
*c
);
540 static void sinterCommand(redisClient
*c
);
541 static void sinterstoreCommand(redisClient
*c
);
542 static void sunionCommand(redisClient
*c
);
543 static void sunionstoreCommand(redisClient
*c
);
544 static void sdiffCommand(redisClient
*c
);
545 static void sdiffstoreCommand(redisClient
*c
);
546 static void syncCommand(redisClient
*c
);
547 static void flushdbCommand(redisClient
*c
);
548 static void flushallCommand(redisClient
*c
);
549 static void sortCommand(redisClient
*c
);
550 static void lremCommand(redisClient
*c
);
551 static void rpoplpushcommand(redisClient
*c
);
552 static void infoCommand(redisClient
*c
);
553 static void mgetCommand(redisClient
*c
);
554 static void monitorCommand(redisClient
*c
);
555 static void expireCommand(redisClient
*c
);
556 static void expireatCommand(redisClient
*c
);
557 static void getsetCommand(redisClient
*c
);
558 static void ttlCommand(redisClient
*c
);
559 static void slaveofCommand(redisClient
*c
);
560 static void debugCommand(redisClient
*c
);
561 static void msetCommand(redisClient
*c
);
562 static void msetnxCommand(redisClient
*c
);
563 static void zaddCommand(redisClient
*c
);
564 static void zincrbyCommand(redisClient
*c
);
565 static void zrangeCommand(redisClient
*c
);
566 static void zrangebyscoreCommand(redisClient
*c
);
567 static void zrevrangeCommand(redisClient
*c
);
568 static void zcardCommand(redisClient
*c
);
569 static void zremCommand(redisClient
*c
);
570 static void zscoreCommand(redisClient
*c
);
571 static void zremrangebyscoreCommand(redisClient
*c
);
572 static void multiCommand(redisClient
*c
);
573 static void execCommand(redisClient
*c
);
574 static void blpopCommand(redisClient
*c
);
575 static void brpopCommand(redisClient
*c
);
577 /*================================= Globals ================================= */
580 static struct redisServer server
; /* server global state */
581 static struct redisCommand cmdTable
[] = {
582 {"get",getCommand
,2,REDIS_CMD_INLINE
},
583 {"set",setCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
584 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
585 {"del",delCommand
,-2,REDIS_CMD_INLINE
},
586 {"exists",existsCommand
,2,REDIS_CMD_INLINE
},
587 {"incr",incrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
588 {"decr",decrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
589 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
},
590 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
591 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
592 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
},
593 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
},
594 {"brpop",brpopCommand
,-3,REDIS_CMD_INLINE
},
595 {"blpop",blpopCommand
,-3,REDIS_CMD_INLINE
},
596 {"llen",llenCommand
,2,REDIS_CMD_INLINE
},
597 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
},
598 {"lset",lsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
599 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
},
600 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
},
601 {"lrem",lremCommand
,4,REDIS_CMD_BULK
},
602 {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
603 {"sadd",saddCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
604 {"srem",sremCommand
,3,REDIS_CMD_BULK
},
605 {"smove",smoveCommand
,4,REDIS_CMD_BULK
},
606 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
},
607 {"scard",scardCommand
,2,REDIS_CMD_INLINE
},
608 {"spop",spopCommand
,2,REDIS_CMD_INLINE
},
609 {"srandmember",srandmemberCommand
,2,REDIS_CMD_INLINE
},
610 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
611 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
612 {"sunion",sunionCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
613 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
614 {"sdiff",sdiffCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
615 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
616 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
},
617 {"zadd",zaddCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
618 {"zincrby",zincrbyCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
619 {"zrem",zremCommand
,3,REDIS_CMD_BULK
},
620 {"zremrangebyscore",zremrangebyscoreCommand
,4,REDIS_CMD_INLINE
},
621 {"zrange",zrangeCommand
,-4,REDIS_CMD_INLINE
},
622 {"zrangebyscore",zrangebyscoreCommand
,-4,REDIS_CMD_INLINE
},
623 {"zrevrange",zrevrangeCommand
,-4,REDIS_CMD_INLINE
},
624 {"zcard",zcardCommand
,2,REDIS_CMD_INLINE
},
625 {"zscore",zscoreCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
626 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
627 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
628 {"getset",getsetCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
629 {"mset",msetCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
630 {"msetnx",msetnxCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
631 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
},
632 {"select",selectCommand
,2,REDIS_CMD_INLINE
},
633 {"move",moveCommand
,3,REDIS_CMD_INLINE
},
634 {"rename",renameCommand
,3,REDIS_CMD_INLINE
},
635 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
},
636 {"expire",expireCommand
,3,REDIS_CMD_INLINE
},
637 {"expireat",expireatCommand
,3,REDIS_CMD_INLINE
},
638 {"keys",keysCommand
,2,REDIS_CMD_INLINE
},
639 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
},
640 {"auth",authCommand
,2,REDIS_CMD_INLINE
},
641 {"ping",pingCommand
,1,REDIS_CMD_INLINE
},
642 {"echo",echoCommand
,2,REDIS_CMD_BULK
},
643 {"save",saveCommand
,1,REDIS_CMD_INLINE
},
644 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
},
645 {"bgrewriteaof",bgrewriteaofCommand
,1,REDIS_CMD_INLINE
},
646 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
},
647 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
},
648 {"type",typeCommand
,2,REDIS_CMD_INLINE
},
649 {"multi",multiCommand
,1,REDIS_CMD_INLINE
},
650 {"exec",execCommand
,1,REDIS_CMD_INLINE
},
651 {"sync",syncCommand
,1,REDIS_CMD_INLINE
},
652 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
},
653 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
},
654 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
655 {"info",infoCommand
,1,REDIS_CMD_INLINE
},
656 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
},
657 {"ttl",ttlCommand
,2,REDIS_CMD_INLINE
},
658 {"slaveof",slaveofCommand
,3,REDIS_CMD_INLINE
},
659 {"debug",debugCommand
,-2,REDIS_CMD_INLINE
},
663 /*============================ Utility functions ============================ */
665 /* Glob-style pattern matching. */
666 int stringmatchlen(const char *pattern
, int patternLen
,
667 const char *string
, int stringLen
, int nocase
)
672 while (pattern
[1] == '*') {
677 return 1; /* match */
679 if (stringmatchlen(pattern
+1, patternLen
-1,
680 string
, stringLen
, nocase
))
681 return 1; /* match */
685 return 0; /* no match */
689 return 0; /* no match */
699 not = pattern
[0] == '^';
706 if (pattern
[0] == '\\') {
709 if (pattern
[0] == string
[0])
711 } else if (pattern
[0] == ']') {
713 } else if (patternLen
== 0) {
717 } else if (pattern
[1] == '-' && patternLen
>= 3) {
718 int start
= pattern
[0];
719 int end
= pattern
[2];
727 start
= tolower(start
);
733 if (c
>= start
&& c
<= end
)
737 if (pattern
[0] == string
[0])
740 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
750 return 0; /* no match */
756 if (patternLen
>= 2) {
763 if (pattern
[0] != string
[0])
764 return 0; /* no match */
766 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
767 return 0; /* no match */
775 if (stringLen
== 0) {
776 while(*pattern
== '*') {
783 if (patternLen
== 0 && stringLen
== 0)
788 static void redisLog(int level
, const char *fmt
, ...) {
792 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
796 if (level
>= server
.verbosity
) {
802 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
803 fprintf(fp
,"%s %c ",buf
,c
[level
]);
804 vfprintf(fp
, fmt
, ap
);
810 if (server
.logfile
) fclose(fp
);
813 /*====================== Hash table type implementation ==================== */
815 /* This is an hash table type that uses the SDS dynamic strings libary as
816 * keys and radis objects as values (objects can hold SDS strings,
819 static void dictVanillaFree(void *privdata
, void *val
)
821 DICT_NOTUSED(privdata
);
825 static void dictListDestructor(void *privdata
, void *val
)
827 DICT_NOTUSED(privdata
);
828 listRelease((list
*)val
);
831 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
835 DICT_NOTUSED(privdata
);
837 l1
= sdslen((sds
)key1
);
838 l2
= sdslen((sds
)key2
);
839 if (l1
!= l2
) return 0;
840 return memcmp(key1
, key2
, l1
) == 0;
843 static void dictRedisObjectDestructor(void *privdata
, void *val
)
845 DICT_NOTUSED(privdata
);
847 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
851 static int dictObjKeyCompare(void *privdata
, const void *key1
,
854 const robj
*o1
= key1
, *o2
= key2
;
855 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
858 static unsigned int dictObjHash(const void *key
) {
860 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
863 static int dictEncObjKeyCompare(void *privdata
, const void *key1
,
866 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
869 o1
= getDecodedObject(o1
);
870 o2
= getDecodedObject(o2
);
871 cmp
= sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
877 static unsigned int dictEncObjHash(const void *key
) {
878 robj
*o
= (robj
*) key
;
880 o
= getDecodedObject(o
);
881 unsigned int hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
886 static dictType setDictType
= {
887 dictEncObjHash
, /* hash function */
890 dictEncObjKeyCompare
, /* key compare */
891 dictRedisObjectDestructor
, /* key destructor */
892 NULL
/* val destructor */
895 static dictType zsetDictType
= {
896 dictEncObjHash
, /* hash function */
899 dictEncObjKeyCompare
, /* key compare */
900 dictRedisObjectDestructor
, /* key destructor */
901 dictVanillaFree
/* val destructor of malloc(sizeof(double)) */
904 static dictType hashDictType
= {
905 dictObjHash
, /* hash function */
908 dictObjKeyCompare
, /* key compare */
909 dictRedisObjectDestructor
, /* key destructor */
910 dictRedisObjectDestructor
/* val destructor */
913 /* Keylist hash table type has unencoded redis objects as keys and
914 * lists as values. It's used for blocking operations (BLPOP) */
915 static dictType keylistDictType
= {
916 dictObjHash
, /* hash function */
919 dictObjKeyCompare
, /* key compare */
920 dictRedisObjectDestructor
, /* key destructor */
921 dictListDestructor
/* val destructor */
924 /* ========================= Random utility functions ======================= */
926 /* Redis generally does not try to recover from out of memory conditions
927 * when allocating objects or strings, it is not clear if it will be possible
928 * to report this condition to the client since the networking layer itself
929 * is based on heap allocation for send buffers, so we simply abort.
930 * At least the code will be simpler to read... */
931 static void oom(const char *msg
) {
932 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
937 /* ====================== Redis server networking stuff ===================== */
938 static void closeTimedoutClients(void) {
941 time_t now
= time(NULL
);
943 listRewind(server
.clients
);
944 while ((ln
= listYield(server
.clients
)) != NULL
) {
945 c
= listNodeValue(ln
);
946 if (server
.maxidletime
&&
947 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
948 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
949 (now
- c
->lastinteraction
> server
.maxidletime
))
951 redisLog(REDIS_DEBUG
,"Closing idle client");
953 } else if (c
->flags
& REDIS_BLOCKED
) {
954 if (c
->blockingto
!= 0 && c
->blockingto
< now
) {
955 addReply(c
,shared
.nullmultibulk
);
962 static int htNeedsResize(dict
*dict
) {
963 long long size
, used
;
965 size
= dictSlots(dict
);
966 used
= dictSize(dict
);
967 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
968 (used
*100/size
< REDIS_HT_MINFILL
));
971 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
972 * we resize the hash table to save memory */
973 static void tryResizeHashTables(void) {
976 for (j
= 0; j
< server
.dbnum
; j
++) {
977 if (htNeedsResize(server
.db
[j
].dict
)) {
978 redisLog(REDIS_DEBUG
,"The hash table %d is too sparse, resize it...",j
);
979 dictResize(server
.db
[j
].dict
);
980 redisLog(REDIS_DEBUG
,"Hash table %d resized.",j
);
982 if (htNeedsResize(server
.db
[j
].expires
))
983 dictResize(server
.db
[j
].expires
);
987 /* A background saving child (BGSAVE) terminated its work. Handle this. */
988 void backgroundSaveDoneHandler(int statloc
) {
989 int exitcode
= WEXITSTATUS(statloc
);
990 int bysignal
= WIFSIGNALED(statloc
);
992 if (!bysignal
&& exitcode
== 0) {
993 redisLog(REDIS_NOTICE
,
994 "Background saving terminated with success");
996 server
.lastsave
= time(NULL
);
997 } else if (!bysignal
&& exitcode
!= 0) {
998 redisLog(REDIS_WARNING
, "Background saving error");
1000 redisLog(REDIS_WARNING
,
1001 "Background saving terminated by signal");
1002 rdbRemoveTempFile(server
.bgsavechildpid
);
1004 server
.bgsavechildpid
= -1;
1005 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1006 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1007 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);
1010 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1012 void backgroundRewriteDoneHandler(int statloc
) {
1013 int exitcode
= WEXITSTATUS(statloc
);
1014 int bysignal
= WIFSIGNALED(statloc
);
1016 if (!bysignal
&& exitcode
== 0) {
1020 redisLog(REDIS_NOTICE
,
1021 "Background append only file rewriting terminated with success");
1022 /* Now it's time to flush the differences accumulated by the parent */
1023 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) server
.bgrewritechildpid
);
1024 fd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
1026 redisLog(REDIS_WARNING
, "Not able to open the temp append only file produced by the child: %s", strerror(errno
));
1029 /* Flush our data... */
1030 if (write(fd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
)) !=
1031 (signed) sdslen(server
.bgrewritebuf
)) {
1032 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
));
1036 redisLog(REDIS_NOTICE
,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server
.bgrewritebuf
));
1037 /* Now our work is to rename the temp file into the stable file. And
1038 * switch the file descriptor used by the server for append only. */
1039 if (rename(tmpfile
,server
.appendfilename
) == -1) {
1040 redisLog(REDIS_WARNING
,"Can't rename the temp append only file into the stable one: %s", strerror(errno
));
1044 /* Mission completed... almost */
1045 redisLog(REDIS_NOTICE
,"Append only file successfully rewritten.");
1046 if (server
.appendfd
!= -1) {
1047 /* If append only is actually enabled... */
1048 close(server
.appendfd
);
1049 server
.appendfd
= fd
;
1051 server
.appendseldb
= -1; /* Make sure it will issue SELECT */
1052 redisLog(REDIS_NOTICE
,"The new append only file was selected for future appends.");
1054 /* If append only is disabled we just generate a dump in this
1055 * format. Why not? */
1058 } else if (!bysignal
&& exitcode
!= 0) {
1059 redisLog(REDIS_WARNING
, "Background append only file rewriting error");
1061 redisLog(REDIS_WARNING
,
1062 "Background append only file rewriting terminated by signal");
1065 sdsfree(server
.bgrewritebuf
);
1066 server
.bgrewritebuf
= sdsempty();
1067 aofRemoveTempFile(server
.bgrewritechildpid
);
1068 server
.bgrewritechildpid
= -1;
1071 static int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
1072 int j
, loops
= server
.cronloops
++;
1073 REDIS_NOTUSED(eventLoop
);
1075 REDIS_NOTUSED(clientData
);
1077 /* We take a cached value of the unix time in the global state because
1078 * with virtual memory and aging there is to store the current time
1079 * in objects at every object access, and accuracy is not needed.
1080 * To access a global var is faster than calling time(NULL) */
1081 server
.unixtime
= time(NULL
);
1083 /* Update the global state with the amount of used memory */
1084 server
.usedmemory
= zmalloc_used_memory();
1086 /* Show some info about non-empty databases */
1087 for (j
= 0; j
< server
.dbnum
; j
++) {
1088 long long size
, used
, vkeys
;
1090 size
= dictSlots(server
.db
[j
].dict
);
1091 used
= dictSize(server
.db
[j
].dict
);
1092 vkeys
= dictSize(server
.db
[j
].expires
);
1093 if (!(loops
% 5) && (used
|| vkeys
)) {
1094 redisLog(REDIS_DEBUG
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
1095 /* dictPrintStats(server.dict); */
1099 /* We don't want to resize the hash tables while a bacground saving
1100 * is in progress: the saving child is created using fork() that is
1101 * implemented with a copy-on-write semantic in most modern systems, so
1102 * if we resize the HT while there is the saving child at work actually
1103 * a lot of memory movements in the parent will cause a lot of pages
1105 if (server
.bgsavechildpid
== -1) tryResizeHashTables();
1107 /* Show information about connected clients */
1109 redisLog(REDIS_DEBUG
,"%d clients connected (%d slaves), %zu bytes in use, %d shared objects",
1110 listLength(server
.clients
)-listLength(server
.slaves
),
1111 listLength(server
.slaves
),
1113 dictSize(server
.sharingpool
));
1116 /* Close connections of timedout clients */
1117 if ((server
.maxidletime
&& !(loops
% 10)) || server
.blockedclients
)
1118 closeTimedoutClients();
1120 /* Check if a background saving or AOF rewrite in progress terminated */
1121 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
1125 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
1126 if (pid
== server
.bgsavechildpid
) {
1127 backgroundSaveDoneHandler(statloc
);
1129 backgroundRewriteDoneHandler(statloc
);
1133 /* If there is not a background saving in progress check if
1134 * we have to save now */
1135 time_t now
= time(NULL
);
1136 for (j
= 0; j
< server
.saveparamslen
; j
++) {
1137 struct saveparam
*sp
= server
.saveparams
+j
;
1139 if (server
.dirty
>= sp
->changes
&&
1140 now
-server
.lastsave
> sp
->seconds
) {
1141 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
1142 sp
->changes
, sp
->seconds
);
1143 rdbSaveBackground(server
.dbfilename
);
1149 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1150 * will use few CPU cycles if there are few expiring keys, otherwise
1151 * it will get more aggressive to avoid that too much memory is used by
1152 * keys that can be removed from the keyspace. */
1153 for (j
= 0; j
< server
.dbnum
; j
++) {
1155 redisDb
*db
= server
.db
+j
;
1157 /* Continue to expire if at the end of the cycle more than 25%
1158 * of the keys were expired. */
1160 long num
= dictSize(db
->expires
);
1161 time_t now
= time(NULL
);
1164 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
1165 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
1170 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
1171 t
= (time_t) dictGetEntryVal(de
);
1173 deleteKey(db
,dictGetEntryKey(de
));
1177 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
1180 /* Swap a few keys on disk if we are over the memory limit and VM
1182 if (vmCanSwapOut()) {
1183 while (server
.vm_enabled
&& zmalloc_used_memory() >
1184 server
.vm_max_memory
) {
1185 if (vmSwapOneObject() == REDIS_ERR
) {
1186 if (zmalloc_used_memory() >
1187 (server
.vm_max_memory
+server
.vm_max_memory
/10)) {
1188 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
1195 /* Check if we should connect to a MASTER */
1196 if (server
.replstate
== REDIS_REPL_CONNECT
) {
1197 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
1198 if (syncWithMaster() == REDIS_OK
) {
1199 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
1205 static void createSharedObjects(void) {
1206 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
1207 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
1208 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
1209 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
1210 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
1211 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
1212 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
1213 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
1214 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
1215 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
1216 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
1217 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
1218 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1219 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
1220 "-ERR no such key\r\n"));
1221 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
1222 "-ERR syntax error\r\n"));
1223 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
1224 "-ERR source and destination objects are the same\r\n"));
1225 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
1226 "-ERR index out of range\r\n"));
1227 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
1228 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
1229 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
1230 shared
.select0
= createStringObject("select 0\r\n",10);
1231 shared
.select1
= createStringObject("select 1\r\n",10);
1232 shared
.select2
= createStringObject("select 2\r\n",10);
1233 shared
.select3
= createStringObject("select 3\r\n",10);
1234 shared
.select4
= createStringObject("select 4\r\n",10);
1235 shared
.select5
= createStringObject("select 5\r\n",10);
1236 shared
.select6
= createStringObject("select 6\r\n",10);
1237 shared
.select7
= createStringObject("select 7\r\n",10);
1238 shared
.select8
= createStringObject("select 8\r\n",10);
1239 shared
.select9
= createStringObject("select 9\r\n",10);
1242 static void appendServerSaveParams(time_t seconds
, int changes
) {
1243 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
1244 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
1245 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
1246 server
.saveparamslen
++;
1249 static void resetServerSaveParams() {
1250 zfree(server
.saveparams
);
1251 server
.saveparams
= NULL
;
1252 server
.saveparamslen
= 0;
1255 static void initServerConfig() {
1256 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
1257 server
.port
= REDIS_SERVERPORT
;
1258 server
.verbosity
= REDIS_DEBUG
;
1259 server
.maxidletime
= REDIS_MAXIDLETIME
;
1260 server
.saveparams
= NULL
;
1261 server
.logfile
= NULL
; /* NULL = log on standard output */
1262 server
.bindaddr
= NULL
;
1263 server
.glueoutputbuf
= 1;
1264 server
.daemonize
= 0;
1265 server
.appendonly
= 0;
1266 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1267 server
.lastfsync
= time(NULL
);
1268 server
.appendfd
= -1;
1269 server
.appendseldb
= -1; /* Make sure the first time will not match */
1270 server
.pidfile
= "/var/run/redis.pid";
1271 server
.dbfilename
= "dump.rdb";
1272 server
.appendfilename
= "appendonly.aof";
1273 server
.requirepass
= NULL
;
1274 server
.shareobjects
= 0;
1275 server
.rdbcompression
= 1;
1276 server
.sharingpoolsize
= 1024;
1277 server
.maxclients
= 0;
1278 server
.blockedclients
= 0;
1279 server
.maxmemory
= 0;
1280 server
.vm_enabled
= 0;
1281 server
.vm_page_size
= 256; /* 256 bytes per page */
1282 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
1283 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
1285 resetServerSaveParams();
1287 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1288 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1289 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1290 /* Replication related */
1292 server
.masterauth
= NULL
;
1293 server
.masterhost
= NULL
;
1294 server
.masterport
= 6379;
1295 server
.master
= NULL
;
1296 server
.replstate
= REDIS_REPL_NONE
;
1298 /* Double constants initialization */
1300 R_PosInf
= 1.0/R_Zero
;
1301 R_NegInf
= -1.0/R_Zero
;
1302 R_Nan
= R_Zero
/R_Zero
;
1305 static void initServer() {
1308 signal(SIGHUP
, SIG_IGN
);
1309 signal(SIGPIPE
, SIG_IGN
);
1310 setupSigSegvAction();
1312 server
.clients
= listCreate();
1313 server
.slaves
= listCreate();
1314 server
.monitors
= listCreate();
1315 server
.objfreelist
= listCreate();
1316 createSharedObjects();
1317 server
.el
= aeCreateEventLoop();
1318 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
1319 server
.sharingpool
= dictCreate(&setDictType
,NULL
);
1320 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
1321 if (server
.fd
== -1) {
1322 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
1325 for (j
= 0; j
< server
.dbnum
; j
++) {
1326 server
.db
[j
].dict
= dictCreate(&hashDictType
,NULL
);
1327 server
.db
[j
].expires
= dictCreate(&setDictType
,NULL
);
1328 server
.db
[j
].blockingkeys
= dictCreate(&keylistDictType
,NULL
);
1329 server
.db
[j
].id
= j
;
1331 server
.cronloops
= 0;
1332 server
.bgsavechildpid
= -1;
1333 server
.bgrewritechildpid
= -1;
1334 server
.bgrewritebuf
= sdsempty();
1335 server
.lastsave
= time(NULL
);
1337 server
.usedmemory
= 0;
1338 server
.stat_numcommands
= 0;
1339 server
.stat_numconnections
= 0;
1340 server
.stat_starttime
= time(NULL
);
1341 server
.unixtime
= time(NULL
);
1342 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
1344 if (server
.appendonly
) {
1345 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1346 if (server
.appendfd
== -1) {
1347 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1353 if (server
.vm_enabled
) vmInit();
1356 /* Empty the whole database */
1357 static long long emptyDb() {
1359 long long removed
= 0;
1361 for (j
= 0; j
< server
.dbnum
; j
++) {
1362 removed
+= dictSize(server
.db
[j
].dict
);
1363 dictEmpty(server
.db
[j
].dict
);
1364 dictEmpty(server
.db
[j
].expires
);
1369 static int yesnotoi(char *s
) {
1370 if (!strcasecmp(s
,"yes")) return 1;
1371 else if (!strcasecmp(s
,"no")) return 0;
1375 /* I agree, this is a very rudimental way to load a configuration...
1376 will improve later if the config gets more complex */
1377 static void loadServerConfig(char *filename
) {
1379 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
1383 if (filename
[0] == '-' && filename
[1] == '\0')
1386 if ((fp
= fopen(filename
,"r")) == NULL
) {
1387 redisLog(REDIS_WARNING
,"Fatal error, can't open config file");
1392 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
1398 line
= sdstrim(line
," \t\r\n");
1400 /* Skip comments and blank lines*/
1401 if (line
[0] == '#' || line
[0] == '\0') {
1406 /* Split into arguments */
1407 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
1408 sdstolower(argv
[0]);
1410 /* Execute config directives */
1411 if (!strcasecmp(argv
[0],"timeout") && argc
== 2) {
1412 server
.maxidletime
= atoi(argv
[1]);
1413 if (server
.maxidletime
< 0) {
1414 err
= "Invalid timeout value"; goto loaderr
;
1416 } else if (!strcasecmp(argv
[0],"port") && argc
== 2) {
1417 server
.port
= atoi(argv
[1]);
1418 if (server
.port
< 1 || server
.port
> 65535) {
1419 err
= "Invalid port"; goto loaderr
;
1421 } else if (!strcasecmp(argv
[0],"bind") && argc
== 2) {
1422 server
.bindaddr
= zstrdup(argv
[1]);
1423 } else if (!strcasecmp(argv
[0],"save") && argc
== 3) {
1424 int seconds
= atoi(argv
[1]);
1425 int changes
= atoi(argv
[2]);
1426 if (seconds
< 1 || changes
< 0) {
1427 err
= "Invalid save parameters"; goto loaderr
;
1429 appendServerSaveParams(seconds
,changes
);
1430 } else if (!strcasecmp(argv
[0],"dir") && argc
== 2) {
1431 if (chdir(argv
[1]) == -1) {
1432 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
1433 argv
[1], strerror(errno
));
1436 } else if (!strcasecmp(argv
[0],"loglevel") && argc
== 2) {
1437 if (!strcasecmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
1438 else if (!strcasecmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
1439 else if (!strcasecmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
1441 err
= "Invalid log level. Must be one of debug, notice, warning";
1444 } else if (!strcasecmp(argv
[0],"logfile") && argc
== 2) {
1447 server
.logfile
= zstrdup(argv
[1]);
1448 if (!strcasecmp(server
.logfile
,"stdout")) {
1449 zfree(server
.logfile
);
1450 server
.logfile
= NULL
;
1452 if (server
.logfile
) {
1453 /* Test if we are able to open the file. The server will not
1454 * be able to abort just for this problem later... */
1455 logfp
= fopen(server
.logfile
,"a");
1456 if (logfp
== NULL
) {
1457 err
= sdscatprintf(sdsempty(),
1458 "Can't open the log file: %s", strerror(errno
));
1463 } else if (!strcasecmp(argv
[0],"databases") && argc
== 2) {
1464 server
.dbnum
= atoi(argv
[1]);
1465 if (server
.dbnum
< 1) {
1466 err
= "Invalid number of databases"; goto loaderr
;
1468 } else if (!strcasecmp(argv
[0],"maxclients") && argc
== 2) {
1469 server
.maxclients
= atoi(argv
[1]);
1470 } else if (!strcasecmp(argv
[0],"maxmemory") && argc
== 2) {
1471 server
.maxmemory
= strtoll(argv
[1], NULL
, 10);
1472 } else if (!strcasecmp(argv
[0],"slaveof") && argc
== 3) {
1473 server
.masterhost
= sdsnew(argv
[1]);
1474 server
.masterport
= atoi(argv
[2]);
1475 server
.replstate
= REDIS_REPL_CONNECT
;
1476 } else if (!strcasecmp(argv
[0],"masterauth") && argc
== 2) {
1477 server
.masterauth
= zstrdup(argv
[1]);
1478 } else if (!strcasecmp(argv
[0],"glueoutputbuf") && argc
== 2) {
1479 if ((server
.glueoutputbuf
= yesnotoi(argv
[1])) == -1) {
1480 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1482 } else if (!strcasecmp(argv
[0],"shareobjects") && argc
== 2) {
1483 if ((server
.shareobjects
= yesnotoi(argv
[1])) == -1) {
1484 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1486 } else if (!strcasecmp(argv
[0],"rdbcompression") && argc
== 2) {
1487 if ((server
.rdbcompression
= yesnotoi(argv
[1])) == -1) {
1488 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1490 } else if (!strcasecmp(argv
[0],"shareobjectspoolsize") && argc
== 2) {
1491 server
.sharingpoolsize
= atoi(argv
[1]);
1492 if (server
.sharingpoolsize
< 1) {
1493 err
= "invalid object sharing pool size"; goto loaderr
;
1495 } else if (!strcasecmp(argv
[0],"daemonize") && argc
== 2) {
1496 if ((server
.daemonize
= yesnotoi(argv
[1])) == -1) {
1497 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1499 } else if (!strcasecmp(argv
[0],"appendonly") && argc
== 2) {
1500 if ((server
.appendonly
= yesnotoi(argv
[1])) == -1) {
1501 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1503 } else if (!strcasecmp(argv
[0],"appendfsync") && argc
== 2) {
1504 if (!strcasecmp(argv
[1],"no")) {
1505 server
.appendfsync
= APPENDFSYNC_NO
;
1506 } else if (!strcasecmp(argv
[1],"always")) {
1507 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1508 } else if (!strcasecmp(argv
[1],"everysec")) {
1509 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1511 err
= "argument must be 'no', 'always' or 'everysec'";
1514 } else if (!strcasecmp(argv
[0],"requirepass") && argc
== 2) {
1515 server
.requirepass
= zstrdup(argv
[1]);
1516 } else if (!strcasecmp(argv
[0],"pidfile") && argc
== 2) {
1517 server
.pidfile
= zstrdup(argv
[1]);
1518 } else if (!strcasecmp(argv
[0],"dbfilename") && argc
== 2) {
1519 server
.dbfilename
= zstrdup(argv
[1]);
1520 } else if (!strcasecmp(argv
[0],"vm-enabled") && argc
== 2) {
1521 if ((server
.vm_enabled
= yesnotoi(argv
[1])) == -1) {
1522 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1524 } else if (!strcasecmp(argv
[0],"vm-max-memory") && argc
== 2) {
1525 server
.vm_max_memory
= strtoll(argv
[1], NULL
, 10);
1526 } else if (!strcasecmp(argv
[0],"vm-page-size") && argc
== 2) {
1527 server
.vm_page_size
= strtoll(argv
[1], NULL
, 10);
1528 } else if (!strcasecmp(argv
[0],"vm-pages") && argc
== 2) {
1529 server
.vm_pages
= strtoll(argv
[1], NULL
, 10);
1531 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
1533 for (j
= 0; j
< argc
; j
++)
1538 if (fp
!= stdin
) fclose(fp
);
1542 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
1543 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
1544 fprintf(stderr
, ">>> '%s'\n", line
);
1545 fprintf(stderr
, "%s\n", err
);
1549 static void freeClientArgv(redisClient
*c
) {
1552 for (j
= 0; j
< c
->argc
; j
++)
1553 decrRefCount(c
->argv
[j
]);
1554 for (j
= 0; j
< c
->mbargc
; j
++)
1555 decrRefCount(c
->mbargv
[j
]);
1560 static void freeClient(redisClient
*c
) {
1563 /* Note that if the client we are freeing is blocked into a blocking
1564 * call, we have to set querybuf to NULL *before* to call unblockClient()
1565 * to avoid processInputBuffer() will get called. Also it is important
1566 * to remove the file events after this, because this call adds
1567 * the READABLE event. */
1568 sdsfree(c
->querybuf
);
1570 if (c
->flags
& REDIS_BLOCKED
)
1573 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
1574 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1575 listRelease(c
->reply
);
1578 ln
= listSearchKey(server
.clients
,c
);
1579 redisAssert(ln
!= NULL
);
1580 listDelNode(server
.clients
,ln
);
1581 if (c
->flags
& REDIS_SLAVE
) {
1582 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
1584 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
1585 ln
= listSearchKey(l
,c
);
1586 redisAssert(ln
!= NULL
);
1589 if (c
->flags
& REDIS_MASTER
) {
1590 server
.master
= NULL
;
1591 server
.replstate
= REDIS_REPL_CONNECT
;
1595 freeClientMultiState(c
);
1599 #define GLUEREPLY_UP_TO (1024)
1600 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
1602 char buf
[GLUEREPLY_UP_TO
];
1606 listRewind(c
->reply
);
1607 while((ln
= listYield(c
->reply
))) {
1611 objlen
= sdslen(o
->ptr
);
1612 if (copylen
+ objlen
<= GLUEREPLY_UP_TO
) {
1613 memcpy(buf
+copylen
,o
->ptr
,objlen
);
1615 listDelNode(c
->reply
,ln
);
1617 if (copylen
== 0) return;
1621 /* Now the output buffer is empty, add the new single element */
1622 o
= createObject(REDIS_STRING
,sdsnewlen(buf
,copylen
));
1623 listAddNodeHead(c
->reply
,o
);
1626 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1627 redisClient
*c
= privdata
;
1628 int nwritten
= 0, totwritten
= 0, objlen
;
1631 REDIS_NOTUSED(mask
);
1633 /* Use writev() if we have enough buffers to send */
1634 if (!server
.glueoutputbuf
&&
1635 listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD
&&
1636 !(c
->flags
& REDIS_MASTER
))
1638 sendReplyToClientWritev(el
, fd
, privdata
, mask
);
1642 while(listLength(c
->reply
)) {
1643 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
1644 glueReplyBuffersIfNeeded(c
);
1646 o
= listNodeValue(listFirst(c
->reply
));
1647 objlen
= sdslen(o
->ptr
);
1650 listDelNode(c
->reply
,listFirst(c
->reply
));
1654 if (c
->flags
& REDIS_MASTER
) {
1655 /* Don't reply to a master */
1656 nwritten
= objlen
- c
->sentlen
;
1658 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
1659 if (nwritten
<= 0) break;
1661 c
->sentlen
+= nwritten
;
1662 totwritten
+= nwritten
;
1663 /* If we fully sent the object on head go to the next one */
1664 if (c
->sentlen
== objlen
) {
1665 listDelNode(c
->reply
,listFirst(c
->reply
));
1668 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
1669 * bytes, in a single threaded server it's a good idea to serve
1670 * other clients as well, even if a very large request comes from
1671 * super fast link that is always able to accept data (in real world
1672 * scenario think about 'KEYS *' against the loopback interfae) */
1673 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
1675 if (nwritten
== -1) {
1676 if (errno
== EAGAIN
) {
1679 redisLog(REDIS_DEBUG
,
1680 "Error writing to client: %s", strerror(errno
));
1685 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
1686 if (listLength(c
->reply
) == 0) {
1688 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1692 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
)
1694 redisClient
*c
= privdata
;
1695 int nwritten
= 0, totwritten
= 0, objlen
, willwrite
;
1697 struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
];
1698 int offset
, ion
= 0;
1700 REDIS_NOTUSED(mask
);
1703 while (listLength(c
->reply
)) {
1704 offset
= c
->sentlen
;
1708 /* fill-in the iov[] array */
1709 for(node
= listFirst(c
->reply
); node
; node
= listNextNode(node
)) {
1710 o
= listNodeValue(node
);
1711 objlen
= sdslen(o
->ptr
);
1713 if (totwritten
+ objlen
- offset
> REDIS_MAX_WRITE_PER_EVENT
)
1716 if(ion
== REDIS_WRITEV_IOVEC_COUNT
)
1717 break; /* no more iovecs */
1719 iov
[ion
].iov_base
= ((char*)o
->ptr
) + offset
;
1720 iov
[ion
].iov_len
= objlen
- offset
;
1721 willwrite
+= objlen
- offset
;
1722 offset
= 0; /* just for the first item */
1729 /* write all collected blocks at once */
1730 if((nwritten
= writev(fd
, iov
, ion
)) < 0) {
1731 if (errno
!= EAGAIN
) {
1732 redisLog(REDIS_DEBUG
,
1733 "Error writing to client: %s", strerror(errno
));
1740 totwritten
+= nwritten
;
1741 offset
= c
->sentlen
;
1743 /* remove written robjs from c->reply */
1744 while (nwritten
&& listLength(c
->reply
)) {
1745 o
= listNodeValue(listFirst(c
->reply
));
1746 objlen
= sdslen(o
->ptr
);
1748 if(nwritten
>= objlen
- offset
) {
1749 listDelNode(c
->reply
, listFirst(c
->reply
));
1750 nwritten
-= objlen
- offset
;
1754 c
->sentlen
+= nwritten
;
1762 c
->lastinteraction
= time(NULL
);
1764 if (listLength(c
->reply
) == 0) {
1766 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1770 static struct redisCommand
*lookupCommand(char *name
) {
1772 while(cmdTable
[j
].name
!= NULL
) {
1773 if (!strcasecmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
1779 /* resetClient prepare the client to process the next command */
1780 static void resetClient(redisClient
*c
) {
1786 /* Call() is the core of Redis execution of a command */
1787 static void call(redisClient
*c
, struct redisCommand
*cmd
) {
1790 dirty
= server
.dirty
;
1792 if (server
.appendonly
&& server
.dirty
-dirty
)
1793 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1794 if (server
.dirty
-dirty
&& listLength(server
.slaves
))
1795 replicationFeedSlaves(server
.slaves
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1796 if (listLength(server
.monitors
))
1797 replicationFeedSlaves(server
.monitors
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1798 server
.stat_numcommands
++;
1801 /* If this function gets called we already read a whole
1802 * command, argments are in the client argv/argc fields.
1803 * processCommand() execute the command or prepare the
1804 * server for a bulk read from the client.
1806 * If 1 is returned the client is still alive and valid and
1807 * and other operations can be performed by the caller. Otherwise
1808 * if 0 is returned the client was destroied (i.e. after QUIT). */
1809 static int processCommand(redisClient
*c
) {
1810 struct redisCommand
*cmd
;
1812 /* Free some memory if needed (maxmemory setting) */
1813 if (server
.maxmemory
) freeMemoryIfNeeded();
1815 /* Handle the multi bulk command type. This is an alternative protocol
1816 * supported by Redis in order to receive commands that are composed of
1817 * multiple binary-safe "bulk" arguments. The latency of processing is
1818 * a bit higher but this allows things like multi-sets, so if this
1819 * protocol is used only for MSET and similar commands this is a big win. */
1820 if (c
->multibulk
== 0 && c
->argc
== 1 && ((char*)(c
->argv
[0]->ptr
))[0] == '*') {
1821 c
->multibulk
= atoi(((char*)c
->argv
[0]->ptr
)+1);
1822 if (c
->multibulk
<= 0) {
1826 decrRefCount(c
->argv
[c
->argc
-1]);
1830 } else if (c
->multibulk
) {
1831 if (c
->bulklen
== -1) {
1832 if (((char*)c
->argv
[0]->ptr
)[0] != '$') {
1833 addReplySds(c
,sdsnew("-ERR multi bulk protocol error\r\n"));
1837 int bulklen
= atoi(((char*)c
->argv
[0]->ptr
)+1);
1838 decrRefCount(c
->argv
[0]);
1839 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1841 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1846 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1850 c
->mbargv
= zrealloc(c
->mbargv
,(sizeof(robj
*))*(c
->mbargc
+1));
1851 c
->mbargv
[c
->mbargc
] = c
->argv
[0];
1855 if (c
->multibulk
== 0) {
1859 /* Here we need to swap the multi-bulk argc/argv with the
1860 * normal argc/argv of the client structure. */
1862 c
->argv
= c
->mbargv
;
1863 c
->mbargv
= auxargv
;
1866 c
->argc
= c
->mbargc
;
1867 c
->mbargc
= auxargc
;
1869 /* We need to set bulklen to something different than -1
1870 * in order for the code below to process the command without
1871 * to try to read the last argument of a bulk command as
1872 * a special argument. */
1874 /* continue below and process the command */
1881 /* -- end of multi bulk commands processing -- */
1883 /* The QUIT command is handled as a special case. Normal command
1884 * procs are unable to close the client connection safely */
1885 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
1889 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1892 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
1893 (char*)c
->argv
[0]->ptr
));
1896 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
1897 (c
->argc
< -cmd
->arity
)) {
1899 sdscatprintf(sdsempty(),
1900 "-ERR wrong number of arguments for '%s' command\r\n",
1904 } else if (server
.maxmemory
&& cmd
->flags
& REDIS_CMD_DENYOOM
&& zmalloc_used_memory() > server
.maxmemory
) {
1905 addReplySds(c
,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
1908 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
1909 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
1911 decrRefCount(c
->argv
[c
->argc
-1]);
1912 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1914 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1919 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1920 /* It is possible that the bulk read is already in the
1921 * buffer. Check this condition and handle it accordingly.
1922 * This is just a fast path, alternative to call processInputBuffer().
1923 * It's a good idea since the code is small and this condition
1924 * happens most of the times. */
1925 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
1926 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
1928 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
1933 /* Let's try to share objects on the command arguments vector */
1934 if (server
.shareobjects
) {
1936 for(j
= 1; j
< c
->argc
; j
++)
1937 c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]);
1939 /* Let's try to encode the bulk object to save space. */
1940 if (cmd
->flags
& REDIS_CMD_BULK
)
1941 tryObjectEncoding(c
->argv
[c
->argc
-1]);
1943 /* Check if the user is authenticated */
1944 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
1945 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
1950 /* Exec the command */
1951 if (c
->flags
& REDIS_MULTI
&& cmd
->proc
!= execCommand
) {
1952 queueMultiCommand(c
,cmd
);
1953 addReply(c
,shared
.queued
);
1958 /* Prepare the client for the next command */
1959 if (c
->flags
& REDIS_CLOSE
) {
1967 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
1971 /* (args*2)+1 is enough room for args, spaces, newlines */
1972 robj
*static_outv
[REDIS_STATIC_ARGS
*2+1];
1974 if (argc
<= REDIS_STATIC_ARGS
) {
1977 outv
= zmalloc(sizeof(robj
*)*(argc
*2+1));
1980 for (j
= 0; j
< argc
; j
++) {
1981 if (j
!= 0) outv
[outc
++] = shared
.space
;
1982 if ((cmd
->flags
& REDIS_CMD_BULK
) && j
== argc
-1) {
1985 lenobj
= createObject(REDIS_STRING
,
1986 sdscatprintf(sdsempty(),"%lu\r\n",
1987 (unsigned long) stringObjectLen(argv
[j
])));
1988 lenobj
->refcount
= 0;
1989 outv
[outc
++] = lenobj
;
1991 outv
[outc
++] = argv
[j
];
1993 outv
[outc
++] = shared
.crlf
;
1995 /* Increment all the refcounts at start and decrement at end in order to
1996 * be sure to free objects if there is no slave in a replication state
1997 * able to be feed with commands */
1998 for (j
= 0; j
< outc
; j
++) incrRefCount(outv
[j
]);
2000 while((ln
= listYield(slaves
))) {
2001 redisClient
*slave
= ln
->value
;
2003 /* Don't feed slaves that are still waiting for BGSAVE to start */
2004 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) continue;
2006 /* Feed all the other slaves, MONITORs and so on */
2007 if (slave
->slaveseldb
!= dictid
) {
2011 case 0: selectcmd
= shared
.select0
; break;
2012 case 1: selectcmd
= shared
.select1
; break;
2013 case 2: selectcmd
= shared
.select2
; break;
2014 case 3: selectcmd
= shared
.select3
; break;
2015 case 4: selectcmd
= shared
.select4
; break;
2016 case 5: selectcmd
= shared
.select5
; break;
2017 case 6: selectcmd
= shared
.select6
; break;
2018 case 7: selectcmd
= shared
.select7
; break;
2019 case 8: selectcmd
= shared
.select8
; break;
2020 case 9: selectcmd
= shared
.select9
; break;
2022 selectcmd
= createObject(REDIS_STRING
,
2023 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
2024 selectcmd
->refcount
= 0;
2027 addReply(slave
,selectcmd
);
2028 slave
->slaveseldb
= dictid
;
2030 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
2032 for (j
= 0; j
< outc
; j
++) decrRefCount(outv
[j
]);
2033 if (outv
!= static_outv
) zfree(outv
);
2036 static void processInputBuffer(redisClient
*c
) {
2038 /* Before to process the input buffer, make sure the client is not
2039 * waitig for a blocking operation such as BLPOP. Note that the first
2040 * iteration the client is never blocked, otherwise the processInputBuffer
2041 * would not be called at all, but after the execution of the first commands
2042 * in the input buffer the client may be blocked, and the "goto again"
2043 * will try to reiterate. The following line will make it return asap. */
2044 if (c
->flags
& REDIS_BLOCKED
) return;
2045 if (c
->bulklen
== -1) {
2046 /* Read the first line of the query */
2047 char *p
= strchr(c
->querybuf
,'\n');
2054 query
= c
->querybuf
;
2055 c
->querybuf
= sdsempty();
2056 querylen
= 1+(p
-(query
));
2057 if (sdslen(query
) > querylen
) {
2058 /* leave data after the first line of the query in the buffer */
2059 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
2061 *p
= '\0'; /* remove "\n" */
2062 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
2063 sdsupdatelen(query
);
2065 /* Now we can split the query in arguments */
2066 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
2069 if (c
->argv
) zfree(c
->argv
);
2070 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
2072 for (j
= 0; j
< argc
; j
++) {
2073 if (sdslen(argv
[j
])) {
2074 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
2082 /* Execute the command. If the client is still valid
2083 * after processCommand() return and there is something
2084 * on the query buffer try to process the next command. */
2085 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2087 /* Nothing to process, argc == 0. Just process the query
2088 * buffer if it's not empty or return to the caller */
2089 if (sdslen(c
->querybuf
)) goto again
;
2092 } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) {
2093 redisLog(REDIS_DEBUG
, "Client protocol error");
2098 /* Bulk read handling. Note that if we are at this point
2099 the client already sent a command terminated with a newline,
2100 we are reading the bulk data that is actually the last
2101 argument of the command. */
2102 int qbl
= sdslen(c
->querybuf
);
2104 if (c
->bulklen
<= qbl
) {
2105 /* Copy everything but the final CRLF as final argument */
2106 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2108 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2109 /* Process the command. If the client is still valid after
2110 * the processing and there is more data in the buffer
2111 * try to parse it. */
2112 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2118 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2119 redisClient
*c
= (redisClient
*) privdata
;
2120 char buf
[REDIS_IOBUF_LEN
];
2123 REDIS_NOTUSED(mask
);
2125 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
2127 if (errno
== EAGAIN
) {
2130 redisLog(REDIS_DEBUG
, "Reading from client: %s",strerror(errno
));
2134 } else if (nread
== 0) {
2135 redisLog(REDIS_DEBUG
, "Client closed connection");
2140 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
2141 c
->lastinteraction
= time(NULL
);
2145 processInputBuffer(c
);
2148 static int selectDb(redisClient
*c
, int id
) {
2149 if (id
< 0 || id
>= server
.dbnum
)
2151 c
->db
= &server
.db
[id
];
2155 static void *dupClientReplyValue(void *o
) {
2156 incrRefCount((robj
*)o
);
2160 static redisClient
*createClient(int fd
) {
2161 redisClient
*c
= zmalloc(sizeof(*c
));
2163 anetNonBlock(NULL
,fd
);
2164 anetTcpNoDelay(NULL
,fd
);
2165 if (!c
) return NULL
;
2168 c
->querybuf
= sdsempty();
2177 c
->lastinteraction
= time(NULL
);
2178 c
->authenticated
= 0;
2179 c
->replstate
= REDIS_REPL_NONE
;
2180 c
->reply
= listCreate();
2181 c
->blockingkeys
= NULL
;
2182 c
->blockingkeysnum
= 0;
2183 listSetFreeMethod(c
->reply
,decrRefCount
);
2184 listSetDupMethod(c
->reply
,dupClientReplyValue
);
2185 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
2186 readQueryFromClient
, c
) == AE_ERR
) {
2190 listAddNodeTail(server
.clients
,c
);
2191 initClientMultiState(c
);
2195 static void addReply(redisClient
*c
, robj
*obj
) {
2196 if (listLength(c
->reply
) == 0 &&
2197 (c
->replstate
== REDIS_REPL_NONE
||
2198 c
->replstate
== REDIS_REPL_ONLINE
) &&
2199 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
2200 sendReplyToClient
, c
) == AE_ERR
) return;
2202 if (server
.vm_enabled
&& obj
->storage
!= REDIS_VM_MEMORY
) {
2203 obj
= dupStringObject(obj
);
2204 obj
->refcount
= 0; /* getDecodedObject() will increment the refcount */
2206 listAddNodeTail(c
->reply
,getDecodedObject(obj
));
2209 static void addReplySds(redisClient
*c
, sds s
) {
2210 robj
*o
= createObject(REDIS_STRING
,s
);
2215 static void addReplyDouble(redisClient
*c
, double d
) {
2218 snprintf(buf
,sizeof(buf
),"%.17g",d
);
2219 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2220 (unsigned long) strlen(buf
),buf
));
2223 static void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
2226 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
2227 len
= sdslen(obj
->ptr
);
2229 long n
= (long)obj
->ptr
;
2231 /* Compute how many bytes will take this integer as a radix 10 string */
2237 while((n
= n
/10) != 0) {
2241 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",(unsigned long)len
));
2244 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2249 REDIS_NOTUSED(mask
);
2250 REDIS_NOTUSED(privdata
);
2252 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
2253 if (cfd
== AE_ERR
) {
2254 redisLog(REDIS_DEBUG
,"Accepting client connection: %s", server
.neterr
);
2257 redisLog(REDIS_DEBUG
,"Accepted %s:%d", cip
, cport
);
2258 if ((c
= createClient(cfd
)) == NULL
) {
2259 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
2260 close(cfd
); /* May be already closed, just ingore errors */
2263 /* If maxclient directive is set and this is one client more... close the
2264 * connection. Note that we create the client instead to check before
2265 * for this condition, since now the socket is already set in nonblocking
2266 * mode and we can send an error for free using the Kernel I/O */
2267 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
2268 char *err
= "-ERR max number of clients reached\r\n";
2270 /* That's a best effort error message, don't check write errors */
2271 if (write(c
->fd
,err
,strlen(err
)) == -1) {
2272 /* Nothing to do, Just to avoid the warning... */
2277 server
.stat_numconnections
++;
2280 /* ======================= Redis objects implementation ===================== */
2282 static robj
*createObject(int type
, void *ptr
) {
2285 if (listLength(server
.objfreelist
)) {
2286 listNode
*head
= listFirst(server
.objfreelist
);
2287 o
= listNodeValue(head
);
2288 listDelNode(server
.objfreelist
,head
);
2290 if (server
.vm_enabled
) {
2291 o
= zmalloc(sizeof(*o
));
2293 o
= zmalloc(sizeof(*o
)-sizeof(struct redisObjectVM
));
2297 o
->encoding
= REDIS_ENCODING_RAW
;
2300 if (server
.vm_enabled
) {
2301 o
->vm
.atime
= server
.unixtime
;
2302 o
->storage
= REDIS_VM_MEMORY
;
2307 static robj
*createStringObject(char *ptr
, size_t len
) {
2308 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
2311 static robj
*dupStringObject(robj
*o
) {
2312 return createStringObject(o
->ptr
,sdslen(o
->ptr
));
2315 static robj
*createListObject(void) {
2316 list
*l
= listCreate();
2318 listSetFreeMethod(l
,decrRefCount
);
2319 return createObject(REDIS_LIST
,l
);
2322 static robj
*createSetObject(void) {
2323 dict
*d
= dictCreate(&setDictType
,NULL
);
2324 return createObject(REDIS_SET
,d
);
2327 static robj
*createZsetObject(void) {
2328 zset
*zs
= zmalloc(sizeof(*zs
));
2330 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
2331 zs
->zsl
= zslCreate();
2332 return createObject(REDIS_ZSET
,zs
);
2335 static void freeStringObject(robj
*o
) {
2336 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2341 static void freeListObject(robj
*o
) {
2342 listRelease((list
*) o
->ptr
);
2345 static void freeSetObject(robj
*o
) {
2346 dictRelease((dict
*) o
->ptr
);
2349 static void freeZsetObject(robj
*o
) {
2352 dictRelease(zs
->dict
);
2357 static void freeHashObject(robj
*o
) {
2358 dictRelease((dict
*) o
->ptr
);
2361 static void incrRefCount(robj
*o
) {
2362 assert(!server
.vm_enabled
|| o
->storage
== REDIS_VM_MEMORY
);
2366 static void decrRefCount(void *obj
) {
2369 /* REDIS_VM_SWAPPED */
2370 if (server
.vm_enabled
&& o
->storage
== REDIS_VM_SWAPPED
) {
2371 assert(o
->refcount
== 1);
2372 assert(o
->type
== REDIS_STRING
);
2373 freeStringObject(o
);
2374 vmMarkPagesFree(o
->vm
.page
,o
->vm
.usedpages
);
2375 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2376 !listAddNodeHead(server
.objfreelist
,o
))
2380 /* REDIS_VM_MEMORY */
2381 if (--(o
->refcount
) == 0) {
2383 case REDIS_STRING
: freeStringObject(o
); break;
2384 case REDIS_LIST
: freeListObject(o
); break;
2385 case REDIS_SET
: freeSetObject(o
); break;
2386 case REDIS_ZSET
: freeZsetObject(o
); break;
2387 case REDIS_HASH
: freeHashObject(o
); break;
2388 default: redisAssert(0 != 0); break;
2390 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2391 !listAddNodeHead(server
.objfreelist
,o
))
2396 static robj
*lookupKey(redisDb
*db
, robj
*key
) {
2397 dictEntry
*de
= dictFind(db
->dict
,key
);
2399 robj
*key
= dictGetEntryKey(de
);
2400 robj
*val
= dictGetEntryVal(de
);
2402 if (server
.vm_enabled
) {
2403 if (key
->storage
== REDIS_VM_MEMORY
) {
2404 /* Update the access time of the key for the aging algorithm. */
2405 key
->vm
.atime
= server
.unixtime
;
2407 /* Our value was swapped on disk. Bring it at home. */
2408 assert(val
== NULL
);
2409 val
= vmLoadObject(key
);
2410 dictGetEntryVal(de
) = val
;
2419 static robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
2420 expireIfNeeded(db
,key
);
2421 return lookupKey(db
,key
);
2424 static robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
2425 deleteIfVolatile(db
,key
);
2426 return lookupKey(db
,key
);
2429 static int deleteKey(redisDb
*db
, robj
*key
) {
2432 /* We need to protect key from destruction: after the first dictDelete()
2433 * it may happen that 'key' is no longer valid if we don't increment
2434 * it's count. This may happen when we get the object reference directly
2435 * from the hash table with dictRandomKey() or dict iterators */
2437 if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
);
2438 retval
= dictDelete(db
->dict
,key
);
2441 return retval
== DICT_OK
;
2444 /* Try to share an object against the shared objects pool */
2445 static robj
*tryObjectSharing(robj
*o
) {
2446 struct dictEntry
*de
;
2449 if (o
== NULL
|| server
.shareobjects
== 0) return o
;
2451 redisAssert(o
->type
== REDIS_STRING
);
2452 de
= dictFind(server
.sharingpool
,o
);
2454 robj
*shared
= dictGetEntryKey(de
);
2456 c
= ((unsigned long) dictGetEntryVal(de
))+1;
2457 dictGetEntryVal(de
) = (void*) c
;
2458 incrRefCount(shared
);
2462 /* Here we are using a stream algorihtm: Every time an object is
2463 * shared we increment its count, everytime there is a miss we
2464 * recrement the counter of a random object. If this object reaches
2465 * zero we remove the object and put the current object instead. */
2466 if (dictSize(server
.sharingpool
) >=
2467 server
.sharingpoolsize
) {
2468 de
= dictGetRandomKey(server
.sharingpool
);
2469 redisAssert(de
!= NULL
);
2470 c
= ((unsigned long) dictGetEntryVal(de
))-1;
2471 dictGetEntryVal(de
) = (void*) c
;
2473 dictDelete(server
.sharingpool
,de
->key
);
2476 c
= 0; /* If the pool is empty we want to add this object */
2481 retval
= dictAdd(server
.sharingpool
,o
,(void*)1);
2482 redisAssert(retval
== DICT_OK
);
2489 /* Check if the nul-terminated string 's' can be represented by a long
2490 * (that is, is a number that fits into long without any other space or
2491 * character before or after the digits).
2493 * If so, the function returns REDIS_OK and *longval is set to the value
2494 * of the number. Otherwise REDIS_ERR is returned */
2495 static int isStringRepresentableAsLong(sds s
, long *longval
) {
2496 char buf
[32], *endptr
;
2500 value
= strtol(s
, &endptr
, 10);
2501 if (endptr
[0] != '\0') return REDIS_ERR
;
2502 slen
= snprintf(buf
,32,"%ld",value
);
2504 /* If the number converted back into a string is not identical
2505 * then it's not possible to encode the string as integer */
2506 if (sdslen(s
) != (unsigned)slen
|| memcmp(buf
,s
,slen
)) return REDIS_ERR
;
2507 if (longval
) *longval
= value
;
2511 /* Try to encode a string object in order to save space */
2512 static int tryObjectEncoding(robj
*o
) {
2516 if (o
->encoding
!= REDIS_ENCODING_RAW
)
2517 return REDIS_ERR
; /* Already encoded */
2519 /* It's not save to encode shared objects: shared objects can be shared
2520 * everywhere in the "object space" of Redis. Encoded objects can only
2521 * appear as "values" (and not, for instance, as keys) */
2522 if (o
->refcount
> 1) return REDIS_ERR
;
2524 /* Currently we try to encode only strings */
2525 redisAssert(o
->type
== REDIS_STRING
);
2527 /* Check if we can represent this string as a long integer */
2528 if (isStringRepresentableAsLong(s
,&value
) == REDIS_ERR
) return REDIS_ERR
;
2530 /* Ok, this object can be encoded */
2531 o
->encoding
= REDIS_ENCODING_INT
;
2533 o
->ptr
= (void*) value
;
2537 /* Get a decoded version of an encoded object (returned as a new object).
2538 * If the object is already raw-encoded just increment the ref count. */
2539 static robj
*getDecodedObject(robj
*o
) {
2542 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2546 if (o
->type
== REDIS_STRING
&& o
->encoding
== REDIS_ENCODING_INT
) {
2549 snprintf(buf
,32,"%ld",(long)o
->ptr
);
2550 dec
= createStringObject(buf
,strlen(buf
));
2553 redisAssert(1 != 1);
2557 /* Compare two string objects via strcmp() or alike.
2558 * Note that the objects may be integer-encoded. In such a case we
2559 * use snprintf() to get a string representation of the numbers on the stack
2560 * and compare the strings, it's much faster than calling getDecodedObject().
2562 * Important note: if objects are not integer encoded, but binary-safe strings,
2563 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
2565 static int compareStringObjects(robj
*a
, robj
*b
) {
2566 redisAssert(a
->type
== REDIS_STRING
&& b
->type
== REDIS_STRING
);
2567 char bufa
[128], bufb
[128], *astr
, *bstr
;
2570 if (a
== b
) return 0;
2571 if (a
->encoding
!= REDIS_ENCODING_RAW
) {
2572 snprintf(bufa
,sizeof(bufa
),"%ld",(long) a
->ptr
);
2578 if (b
->encoding
!= REDIS_ENCODING_RAW
) {
2579 snprintf(bufb
,sizeof(bufb
),"%ld",(long) b
->ptr
);
2585 return bothsds
? sdscmp(astr
,bstr
) : strcmp(astr
,bstr
);
2588 static size_t stringObjectLen(robj
*o
) {
2589 redisAssert(o
->type
== REDIS_STRING
);
2590 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2591 return sdslen(o
->ptr
);
2595 return snprintf(buf
,32,"%ld",(long)o
->ptr
);
2599 /*============================ RDB saving/loading =========================== */
2601 static int rdbSaveType(FILE *fp
, unsigned char type
) {
2602 if (fwrite(&type
,1,1,fp
) == 0) return -1;
2606 static int rdbSaveTime(FILE *fp
, time_t t
) {
2607 int32_t t32
= (int32_t) t
;
2608 if (fwrite(&t32
,4,1,fp
) == 0) return -1;
2612 /* check rdbLoadLen() comments for more info */
2613 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
2614 unsigned char buf
[2];
2617 /* Save a 6 bit len */
2618 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
2619 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2620 } else if (len
< (1<<14)) {
2621 /* Save a 14 bit len */
2622 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
2624 if (fwrite(buf
,2,1,fp
) == 0) return -1;
2626 /* Save a 32 bit len */
2627 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
2628 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2630 if (fwrite(&len
,4,1,fp
) == 0) return -1;
2635 /* String objects in the form "2391" "-100" without any space and with a
2636 * range of values that can fit in an 8, 16 or 32 bit signed value can be
2637 * encoded as integers to save space */
2638 static int rdbTryIntegerEncoding(sds s
, unsigned char *enc
) {
2640 char *endptr
, buf
[32];
2642 /* Check if it's possible to encode this value as a number */
2643 value
= strtoll(s
, &endptr
, 10);
2644 if (endptr
[0] != '\0') return 0;
2645 snprintf(buf
,32,"%lld",value
);
2647 /* If the number converted back into a string is not identical
2648 * then it's not possible to encode the string as integer */
2649 if (strlen(buf
) != sdslen(s
) || memcmp(buf
,s
,sdslen(s
))) return 0;
2651 /* Finally check if it fits in our ranges */
2652 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
2653 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
2654 enc
[1] = value
&0xFF;
2656 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
2657 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
2658 enc
[1] = value
&0xFF;
2659 enc
[2] = (value
>>8)&0xFF;
2661 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
2662 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
2663 enc
[1] = value
&0xFF;
2664 enc
[2] = (value
>>8)&0xFF;
2665 enc
[3] = (value
>>16)&0xFF;
2666 enc
[4] = (value
>>24)&0xFF;
2673 static int rdbSaveLzfStringObject(FILE *fp
, robj
*obj
) {
2674 unsigned int comprlen
, outlen
;
2678 /* We require at least four bytes compression for this to be worth it */
2679 outlen
= sdslen(obj
->ptr
)-4;
2680 if (outlen
<= 0) return 0;
2681 if ((out
= zmalloc(outlen
+1)) == NULL
) return 0;
2682 comprlen
= lzf_compress(obj
->ptr
, sdslen(obj
->ptr
), out
, outlen
);
2683 if (comprlen
== 0) {
2687 /* Data compressed! Let's save it on disk */
2688 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
2689 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
2690 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
2691 if (rdbSaveLen(fp
,sdslen(obj
->ptr
)) == -1) goto writeerr
;
2692 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
2701 /* Save a string objet as [len][data] on disk. If the object is a string
2702 * representation of an integer value we try to safe it in a special form */
2703 static int rdbSaveStringObjectRaw(FILE *fp
, robj
*obj
) {
2707 len
= sdslen(obj
->ptr
);
2709 /* Try integer encoding */
2711 unsigned char buf
[5];
2712 if ((enclen
= rdbTryIntegerEncoding(obj
->ptr
,buf
)) > 0) {
2713 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
2718 /* Try LZF compression - under 20 bytes it's unable to compress even
2719 * aaaaaaaaaaaaaaaaaa so skip it */
2720 if (server
.rdbcompression
&& len
> 20) {
2723 retval
= rdbSaveLzfStringObject(fp
,obj
);
2724 if (retval
== -1) return -1;
2725 if (retval
> 0) return 0;
2726 /* retval == 0 means data can't be compressed, save the old way */
2729 /* Store verbatim */
2730 if (rdbSaveLen(fp
,len
) == -1) return -1;
2731 if (len
&& fwrite(obj
->ptr
,len
,1,fp
) == 0) return -1;
2735 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
2736 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
2739 obj
= getDecodedObject(obj
);
2740 retval
= rdbSaveStringObjectRaw(fp
,obj
);
2745 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
2746 * 8 bit integer specifing the length of the representation.
2747 * This 8 bit integer has special values in order to specify the following
2753 static int rdbSaveDoubleValue(FILE *fp
, double val
) {
2754 unsigned char buf
[128];
2760 } else if (!isfinite(val
)) {
2762 buf
[0] = (val
< 0) ? 255 : 254;
2764 snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
);
2765 buf
[0] = strlen((char*)buf
+1);
2768 if (fwrite(buf
,len
,1,fp
) == 0) return -1;
2772 /* Save a Redis object. */
2773 static int rdbSaveObject(FILE *fp
, robj
*o
) {
2774 if (o
->type
== REDIS_STRING
) {
2775 /* Save a string value */
2776 if (rdbSaveStringObject(fp
,o
) == -1) return -1;
2777 } else if (o
->type
== REDIS_LIST
) {
2778 /* Save a list value */
2779 list
*list
= o
->ptr
;
2783 if (rdbSaveLen(fp
,listLength(list
)) == -1) return -1;
2784 while((ln
= listYield(list
))) {
2785 robj
*eleobj
= listNodeValue(ln
);
2787 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2789 } else if (o
->type
== REDIS_SET
) {
2790 /* Save a set value */
2792 dictIterator
*di
= dictGetIterator(set
);
2795 if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1;
2796 while((de
= dictNext(di
)) != NULL
) {
2797 robj
*eleobj
= dictGetEntryKey(de
);
2799 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2801 dictReleaseIterator(di
);
2802 } else if (o
->type
== REDIS_ZSET
) {
2803 /* Save a set value */
2805 dictIterator
*di
= dictGetIterator(zs
->dict
);
2808 if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1;
2809 while((de
= dictNext(di
)) != NULL
) {
2810 robj
*eleobj
= dictGetEntryKey(de
);
2811 double *score
= dictGetEntryVal(de
);
2813 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2814 if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1;
2816 dictReleaseIterator(di
);
2818 redisAssert(0 != 0);
2823 /* Return the length the object will have on disk if saved with
2824 * the rdbSaveObject() function. Currently we use a trick to get
2825 * this length with very little changes to the code. In the future
2826 * we could switch to a faster solution. */
2827 static off_t
rdbSavedObjectLen(robj
*o
) {
2828 static FILE *fp
= NULL
;
2830 if (fp
== NULL
) fp
= fopen("/dev/null","w");
2834 assert(rdbSaveObject(fp
,o
) != 1);
2838 /* Return the number of pages required to save this object in the swap file */
2839 static off_t
rdbSavedObjectPages(robj
*o
) {
2840 off_t bytes
= rdbSavedObjectLen(o
);
2842 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
2845 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
2846 static int rdbSave(char *filename
) {
2847 dictIterator
*di
= NULL
;
2852 time_t now
= time(NULL
);
2854 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
2855 fp
= fopen(tmpfile
,"w");
2857 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
2860 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
2861 for (j
= 0; j
< server
.dbnum
; j
++) {
2862 redisDb
*db
= server
.db
+j
;
2864 if (dictSize(d
) == 0) continue;
2865 di
= dictGetIterator(d
);
2871 /* Write the SELECT DB opcode */
2872 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
2873 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
2875 /* Iterate this DB writing every entry */
2876 while((de
= dictNext(di
)) != NULL
) {
2877 robj
*key
= dictGetEntryKey(de
);
2878 robj
*o
= dictGetEntryVal(de
);
2879 time_t expiretime
= getExpire(db
,key
);
2881 /* Save the expire time */
2882 if (expiretime
!= -1) {
2883 /* If this key is already expired skip it */
2884 if (expiretime
< now
) continue;
2885 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
2886 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
2888 /* Save the key and associated value. This requires special
2889 * handling if the value is swapped out. */
2890 if (key
->storage
== REDIS_VM_MEMORY
) {
2891 /* Save type, key, value */
2892 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
2893 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
2894 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
2897 /* Get a preview of the object in memory */
2898 po
= vmPreviewObject(key
);
2899 /* Also duplicate the key object, to pass around a standard
2901 newkey
= dupStringObject(key
);
2902 /* Save type, key, value */
2903 if (rdbSaveType(fp
,key
->vtype
) == -1) goto werr
;
2904 if (rdbSaveStringObject(fp
,newkey
) == -1) goto werr
;
2905 if (rdbSaveObject(fp
,po
) == -1) goto werr
;
2906 /* Remove the loaded object from memory */
2908 decrRefCount(newkey
);
2911 dictReleaseIterator(di
);
2914 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
2916 /* Make sure data will not remain on the OS's output buffers */
2921 /* Use RENAME to make sure the DB file is changed atomically only
2922 * if the generate DB file is ok. */
2923 if (rename(tmpfile
,filename
) == -1) {
2924 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
2928 redisLog(REDIS_NOTICE
,"DB saved on disk");
2930 server
.lastsave
= time(NULL
);
2936 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
2937 if (di
) dictReleaseIterator(di
);
2941 static int rdbSaveBackground(char *filename
) {
2944 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
2945 if ((childpid
= fork()) == 0) {
2948 if (rdbSave(filename
) == REDIS_OK
) {
2955 if (childpid
== -1) {
2956 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
2960 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
2961 server
.bgsavechildpid
= childpid
;
2964 return REDIS_OK
; /* unreached */
2967 static void rdbRemoveTempFile(pid_t childpid
) {
2970 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
2974 static int rdbLoadType(FILE *fp
) {
2976 if (fread(&type
,1,1,fp
) == 0) return -1;
2980 static time_t rdbLoadTime(FILE *fp
) {
2982 if (fread(&t32
,4,1,fp
) == 0) return -1;
2983 return (time_t) t32
;
2986 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
2987 * of this file for a description of how this are stored on disk.
2989 * isencoded is set to 1 if the readed length is not actually a length but
2990 * an "encoding type", check the above comments for more info */
2991 static uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
2992 unsigned char buf
[2];
2996 if (isencoded
) *isencoded
= 0;
2997 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
2998 type
= (buf
[0]&0xC0)>>6;
2999 if (type
== REDIS_RDB_6BITLEN
) {
3000 /* Read a 6 bit len */
3002 } else if (type
== REDIS_RDB_ENCVAL
) {
3003 /* Read a 6 bit len encoding type */
3004 if (isencoded
) *isencoded
= 1;
3006 } else if (type
== REDIS_RDB_14BITLEN
) {
3007 /* Read a 14 bit len */
3008 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3009 return ((buf
[0]&0x3F)<<8)|buf
[1];
3011 /* Read a 32 bit len */
3012 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
3017 static robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
) {
3018 unsigned char enc
[4];
3021 if (enctype
== REDIS_RDB_ENC_INT8
) {
3022 if (fread(enc
,1,1,fp
) == 0) return NULL
;
3023 val
= (signed char)enc
[0];
3024 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
3026 if (fread(enc
,2,1,fp
) == 0) return NULL
;
3027 v
= enc
[0]|(enc
[1]<<8);
3029 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
3031 if (fread(enc
,4,1,fp
) == 0) return NULL
;
3032 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
3035 val
= 0; /* anti-warning */
3038 return createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",val
));
3041 static robj
*rdbLoadLzfStringObject(FILE*fp
) {
3042 unsigned int len
, clen
;
3043 unsigned char *c
= NULL
;
3046 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3047 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3048 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
3049 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
3050 if (fread(c
,clen
,1,fp
) == 0) goto err
;
3051 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
3053 return createObject(REDIS_STRING
,val
);
3060 static robj
*rdbLoadStringObject(FILE*fp
) {
3065 len
= rdbLoadLen(fp
,&isencoded
);
3068 case REDIS_RDB_ENC_INT8
:
3069 case REDIS_RDB_ENC_INT16
:
3070 case REDIS_RDB_ENC_INT32
:
3071 return tryObjectSharing(rdbLoadIntegerObject(fp
,len
));
3072 case REDIS_RDB_ENC_LZF
:
3073 return tryObjectSharing(rdbLoadLzfStringObject(fp
));
3079 if (len
== REDIS_RDB_LENERR
) return NULL
;
3080 val
= sdsnewlen(NULL
,len
);
3081 if (len
&& fread(val
,len
,1,fp
) == 0) {
3085 return tryObjectSharing(createObject(REDIS_STRING
,val
));
3088 /* For information about double serialization check rdbSaveDoubleValue() */
3089 static int rdbLoadDoubleValue(FILE *fp
, double *val
) {
3093 if (fread(&len
,1,1,fp
) == 0) return -1;
3095 case 255: *val
= R_NegInf
; return 0;
3096 case 254: *val
= R_PosInf
; return 0;
3097 case 253: *val
= R_Nan
; return 0;
3099 if (fread(buf
,len
,1,fp
) == 0) return -1;
3101 sscanf(buf
, "%lg", val
);
3106 /* Load a Redis object of the specified type from the specified file.
3107 * On success a newly allocated object is returned, otherwise NULL. */
3108 static robj
*rdbLoadObject(int type
, FILE *fp
) {
3111 if (type
== REDIS_STRING
) {
3112 /* Read string value */
3113 if ((o
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3114 tryObjectEncoding(o
);
3115 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
3116 /* Read list/set value */
3119 if ((listlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3120 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
3121 /* Load every single element of the list/set */
3125 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3126 tryObjectEncoding(ele
);
3127 if (type
== REDIS_LIST
) {
3128 listAddNodeTail((list
*)o
->ptr
,ele
);
3130 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
3133 } else if (type
== REDIS_ZSET
) {
3134 /* Read list/set value */
3138 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3139 o
= createZsetObject();
3141 /* Load every single element of the list/set */
3144 double *score
= zmalloc(sizeof(double));
3146 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3147 tryObjectEncoding(ele
);
3148 if (rdbLoadDoubleValue(fp
,score
) == -1) return NULL
;
3149 dictAdd(zs
->dict
,ele
,score
);
3150 zslInsert(zs
->zsl
,*score
,ele
);
3151 incrRefCount(ele
); /* added to skiplist */
3154 redisAssert(0 != 0);
3159 static int rdbLoad(char *filename
) {
3161 robj
*keyobj
= NULL
;
3163 int type
, retval
, rdbver
;
3164 dict
*d
= server
.db
[0].dict
;
3165 redisDb
*db
= server
.db
+0;
3167 time_t expiretime
= -1, now
= time(NULL
);
3169 fp
= fopen(filename
,"r");
3170 if (!fp
) return REDIS_ERR
;
3171 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
3173 if (memcmp(buf
,"REDIS",5) != 0) {
3175 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
3178 rdbver
= atoi(buf
+5);
3181 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
3188 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3189 if (type
== REDIS_EXPIRETIME
) {
3190 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
3191 /* We read the time so we need to read the object type again */
3192 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3194 if (type
== REDIS_EOF
) break;
3195 /* Handle SELECT DB opcode as a special case */
3196 if (type
== REDIS_SELECTDB
) {
3197 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
3199 if (dbid
>= (unsigned)server
.dbnum
) {
3200 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
3203 db
= server
.db
+dbid
;
3208 if ((keyobj
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
3210 if ((o
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
3211 /* Add the new object in the hash table */
3212 retval
= dictAdd(d
,keyobj
,o
);
3213 if (retval
== DICT_ERR
) {
3214 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
3217 /* Set the expire time if needed */
3218 if (expiretime
!= -1) {
3219 setExpire(db
,keyobj
,expiretime
);
3220 /* Delete this key if already expired */
3221 if (expiretime
< now
) deleteKey(db
,keyobj
);
3229 eoferr
: /* unexpected end of file is handled here with a fatal exit */
3230 if (keyobj
) decrRefCount(keyobj
);
3231 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
3233 return REDIS_ERR
; /* Just to avoid warning */
3236 /*================================== Commands =============================== */
3238 static void authCommand(redisClient
*c
) {
3239 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
3240 c
->authenticated
= 1;
3241 addReply(c
,shared
.ok
);
3243 c
->authenticated
= 0;
3244 addReplySds(c
,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
3248 static void pingCommand(redisClient
*c
) {
3249 addReply(c
,shared
.pong
);
3252 static void echoCommand(redisClient
*c
) {
3253 addReplyBulkLen(c
,c
->argv
[1]);
3254 addReply(c
,c
->argv
[1]);
3255 addReply(c
,shared
.crlf
);
3258 /*=================================== Strings =============================== */
3260 static void setGenericCommand(redisClient
*c
, int nx
) {
3263 if (nx
) deleteIfVolatile(c
->db
,c
->argv
[1]);
3264 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3265 if (retval
== DICT_ERR
) {
3267 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3268 incrRefCount(c
->argv
[2]);
3270 addReply(c
,shared
.czero
);
3274 incrRefCount(c
->argv
[1]);
3275 incrRefCount(c
->argv
[2]);
3278 removeExpire(c
->db
,c
->argv
[1]);
3279 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3282 static void setCommand(redisClient
*c
) {
3283 setGenericCommand(c
,0);
3286 static void setnxCommand(redisClient
*c
) {
3287 setGenericCommand(c
,1);
3290 static int getGenericCommand(redisClient
*c
) {
3291 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3294 addReply(c
,shared
.nullbulk
);
3297 if (o
->type
!= REDIS_STRING
) {
3298 addReply(c
,shared
.wrongtypeerr
);
3301 addReplyBulkLen(c
,o
);
3303 addReply(c
,shared
.crlf
);
3309 static void getCommand(redisClient
*c
) {
3310 getGenericCommand(c
);
3313 static void getsetCommand(redisClient
*c
) {
3314 if (getGenericCommand(c
) == REDIS_ERR
) return;
3315 if (dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]) == DICT_ERR
) {
3316 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3318 incrRefCount(c
->argv
[1]);
3320 incrRefCount(c
->argv
[2]);
3322 removeExpire(c
->db
,c
->argv
[1]);
3325 static void mgetCommand(redisClient
*c
) {
3328 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
3329 for (j
= 1; j
< c
->argc
; j
++) {
3330 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[j
]);
3332 addReply(c
,shared
.nullbulk
);
3334 if (o
->type
!= REDIS_STRING
) {
3335 addReply(c
,shared
.nullbulk
);
3337 addReplyBulkLen(c
,o
);
3339 addReply(c
,shared
.crlf
);
3345 static void msetGenericCommand(redisClient
*c
, int nx
) {
3346 int j
, busykeys
= 0;
3348 if ((c
->argc
% 2) == 0) {
3349 addReplySds(c
,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
3352 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
3353 * set nothing at all if at least one already key exists. */
3355 for (j
= 1; j
< c
->argc
; j
+= 2) {
3356 if (lookupKeyWrite(c
->db
,c
->argv
[j
]) != NULL
) {
3362 addReply(c
, shared
.czero
);
3366 for (j
= 1; j
< c
->argc
; j
+= 2) {
3369 tryObjectEncoding(c
->argv
[j
+1]);
3370 retval
= dictAdd(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3371 if (retval
== DICT_ERR
) {
3372 dictReplace(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3373 incrRefCount(c
->argv
[j
+1]);
3375 incrRefCount(c
->argv
[j
]);
3376 incrRefCount(c
->argv
[j
+1]);
3378 removeExpire(c
->db
,c
->argv
[j
]);
3380 server
.dirty
+= (c
->argc
-1)/2;
3381 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3384 static void msetCommand(redisClient
*c
) {
3385 msetGenericCommand(c
,0);
3388 static void msetnxCommand(redisClient
*c
) {
3389 msetGenericCommand(c
,1);
3392 static void incrDecrCommand(redisClient
*c
, long long incr
) {
3397 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3401 if (o
->type
!= REDIS_STRING
) {
3406 if (o
->encoding
== REDIS_ENCODING_RAW
)
3407 value
= strtoll(o
->ptr
, &eptr
, 10);
3408 else if (o
->encoding
== REDIS_ENCODING_INT
)
3409 value
= (long)o
->ptr
;
3411 redisAssert(1 != 1);
3416 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
3417 tryObjectEncoding(o
);
3418 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],o
);
3419 if (retval
== DICT_ERR
) {
3420 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
3421 removeExpire(c
->db
,c
->argv
[1]);
3423 incrRefCount(c
->argv
[1]);
3426 addReply(c
,shared
.colon
);
3428 addReply(c
,shared
.crlf
);
3431 static void incrCommand(redisClient
*c
) {
3432 incrDecrCommand(c
,1);
3435 static void decrCommand(redisClient
*c
) {
3436 incrDecrCommand(c
,-1);
3439 static void incrbyCommand(redisClient
*c
) {
3440 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3441 incrDecrCommand(c
,incr
);
3444 static void decrbyCommand(redisClient
*c
) {
3445 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3446 incrDecrCommand(c
,-incr
);
3449 /* ========================= Type agnostic commands ========================= */
3451 static void delCommand(redisClient
*c
) {
3454 for (j
= 1; j
< c
->argc
; j
++) {
3455 if (deleteKey(c
->db
,c
->argv
[j
])) {
3462 addReply(c
,shared
.czero
);
3465 addReply(c
,shared
.cone
);
3468 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",deleted
));
3473 static void existsCommand(redisClient
*c
) {
3474 addReply(c
,lookupKeyRead(c
->db
,c
->argv
[1]) ? shared
.cone
: shared
.czero
);
3477 static void selectCommand(redisClient
*c
) {
3478 int id
= atoi(c
->argv
[1]->ptr
);
3480 if (selectDb(c
,id
) == REDIS_ERR
) {
3481 addReplySds(c
,sdsnew("-ERR invalid DB index\r\n"));
3483 addReply(c
,shared
.ok
);
3487 static void randomkeyCommand(redisClient
*c
) {
3491 de
= dictGetRandomKey(c
->db
->dict
);
3492 if (!de
|| expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break;
3495 addReply(c
,shared
.plus
);
3496 addReply(c
,shared
.crlf
);
3498 addReply(c
,shared
.plus
);
3499 addReply(c
,dictGetEntryKey(de
));
3500 addReply(c
,shared
.crlf
);
3504 static void keysCommand(redisClient
*c
) {
3507 sds pattern
= c
->argv
[1]->ptr
;
3508 int plen
= sdslen(pattern
);
3509 unsigned long numkeys
= 0, keyslen
= 0;
3510 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
3512 di
= dictGetIterator(c
->db
->dict
);
3514 decrRefCount(lenobj
);
3515 while((de
= dictNext(di
)) != NULL
) {
3516 robj
*keyobj
= dictGetEntryKey(de
);
3518 sds key
= keyobj
->ptr
;
3519 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
3520 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
3521 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
3523 addReply(c
,shared
.space
);
3526 keyslen
+= sdslen(key
);
3530 dictReleaseIterator(di
);
3531 lenobj
->ptr
= sdscatprintf(sdsempty(),"$%lu\r\n",keyslen
+(numkeys
? (numkeys
-1) : 0));
3532 addReply(c
,shared
.crlf
);
3535 static void dbsizeCommand(redisClient
*c
) {
3537 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
)));
3540 static void lastsaveCommand(redisClient
*c
) {
3542 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
3545 static void typeCommand(redisClient
*c
) {
3549 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3554 case REDIS_STRING
: type
= "+string"; break;
3555 case REDIS_LIST
: type
= "+list"; break;
3556 case REDIS_SET
: type
= "+set"; break;
3557 case REDIS_ZSET
: type
= "+zset"; break;
3558 default: type
= "unknown"; break;
3561 addReplySds(c
,sdsnew(type
));
3562 addReply(c
,shared
.crlf
);
3565 static void saveCommand(redisClient
*c
) {
3566 if (server
.bgsavechildpid
!= -1) {
3567 addReplySds(c
,sdsnew("-ERR background save in progress\r\n"));
3570 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
3571 addReply(c
,shared
.ok
);
3573 addReply(c
,shared
.err
);
3577 static void bgsaveCommand(redisClient
*c
) {
3578 if (server
.bgsavechildpid
!= -1) {
3579 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
3582 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
3583 char *status
= "+Background saving started\r\n";
3584 addReplySds(c
,sdsnew(status
));
3586 addReply(c
,shared
.err
);
3590 static void shutdownCommand(redisClient
*c
) {
3591 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
3592 /* Kill the saving child if there is a background saving in progress.
3593 We want to avoid race conditions, for instance our saving child may
3594 overwrite the synchronous saving did by SHUTDOWN. */
3595 if (server
.bgsavechildpid
!= -1) {
3596 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
3597 kill(server
.bgsavechildpid
,SIGKILL
);
3598 rdbRemoveTempFile(server
.bgsavechildpid
);
3600 if (server
.appendonly
) {
3601 /* Append only file: fsync() the AOF and exit */
3602 fsync(server
.appendfd
);
3605 /* Snapshotting. Perform a SYNC SAVE and exit */
3606 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
3607 if (server
.daemonize
)
3608 unlink(server
.pidfile
);
3609 redisLog(REDIS_WARNING
,"%zu bytes used at exit",zmalloc_used_memory());
3610 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
3613 /* Ooops.. error saving! The best we can do is to continue operating.
3614 * Note that if there was a background saving process, in the next
3615 * cron() Redis will be notified that the background saving aborted,
3616 * handling special stuff like slaves pending for synchronization... */
3617 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
3618 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
3623 static void renameGenericCommand(redisClient
*c
, int nx
) {
3626 /* To use the same key as src and dst is probably an error */
3627 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
3628 addReply(c
,shared
.sameobjecterr
);
3632 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3634 addReply(c
,shared
.nokeyerr
);
3638 deleteIfVolatile(c
->db
,c
->argv
[2]);
3639 if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
3642 addReply(c
,shared
.czero
);
3645 dictReplace(c
->db
->dict
,c
->argv
[2],o
);
3647 incrRefCount(c
->argv
[2]);
3649 deleteKey(c
->db
,c
->argv
[1]);
3651 addReply(c
,nx
? shared
.cone
: shared
.ok
);
3654 static void renameCommand(redisClient
*c
) {
3655 renameGenericCommand(c
,0);
3658 static void renamenxCommand(redisClient
*c
) {
3659 renameGenericCommand(c
,1);
3662 static void moveCommand(redisClient
*c
) {
3667 /* Obtain source and target DB pointers */
3670 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
3671 addReply(c
,shared
.outofrangeerr
);
3675 selectDb(c
,srcid
); /* Back to the source DB */
3677 /* If the user is moving using as target the same
3678 * DB as the source DB it is probably an error. */
3680 addReply(c
,shared
.sameobjecterr
);
3684 /* Check if the element exists and get a reference */
3685 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3687 addReply(c
,shared
.czero
);
3691 /* Try to add the element to the target DB */
3692 deleteIfVolatile(dst
,c
->argv
[1]);
3693 if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) {
3694 addReply(c
,shared
.czero
);
3697 incrRefCount(c
->argv
[1]);
3700 /* OK! key moved, free the entry in the source DB */
3701 deleteKey(src
,c
->argv
[1]);
3703 addReply(c
,shared
.cone
);
3706 /* =================================== Lists ================================ */
3707 static void pushGenericCommand(redisClient
*c
, int where
) {
3711 lobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3713 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
3714 addReply(c
,shared
.ok
);
3717 lobj
= createListObject();
3719 if (where
== REDIS_HEAD
) {
3720 listAddNodeHead(list
,c
->argv
[2]);
3722 listAddNodeTail(list
,c
->argv
[2]);
3724 dictAdd(c
->db
->dict
,c
->argv
[1],lobj
);
3725 incrRefCount(c
->argv
[1]);
3726 incrRefCount(c
->argv
[2]);
3728 if (lobj
->type
!= REDIS_LIST
) {
3729 addReply(c
,shared
.wrongtypeerr
);
3732 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
3733 addReply(c
,shared
.ok
);
3737 if (where
== REDIS_HEAD
) {
3738 listAddNodeHead(list
,c
->argv
[2]);
3740 listAddNodeTail(list
,c
->argv
[2]);
3742 incrRefCount(c
->argv
[2]);
3745 addReply(c
,shared
.ok
);
3748 static void lpushCommand(redisClient
*c
) {
3749 pushGenericCommand(c
,REDIS_HEAD
);
3752 static void rpushCommand(redisClient
*c
) {
3753 pushGenericCommand(c
,REDIS_TAIL
);
3756 static void llenCommand(redisClient
*c
) {
3760 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3762 addReply(c
,shared
.czero
);
3765 if (o
->type
!= REDIS_LIST
) {
3766 addReply(c
,shared
.wrongtypeerr
);
3769 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
)));
3774 static void lindexCommand(redisClient
*c
) {
3776 int index
= atoi(c
->argv
[2]->ptr
);
3778 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3780 addReply(c
,shared
.nullbulk
);
3782 if (o
->type
!= REDIS_LIST
) {
3783 addReply(c
,shared
.wrongtypeerr
);
3785 list
*list
= o
->ptr
;
3788 ln
= listIndex(list
, index
);
3790 addReply(c
,shared
.nullbulk
);
3792 robj
*ele
= listNodeValue(ln
);
3793 addReplyBulkLen(c
,ele
);
3795 addReply(c
,shared
.crlf
);
3801 static void lsetCommand(redisClient
*c
) {
3803 int index
= atoi(c
->argv
[2]->ptr
);
3805 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3807 addReply(c
,shared
.nokeyerr
);
3809 if (o
->type
!= REDIS_LIST
) {
3810 addReply(c
,shared
.wrongtypeerr
);
3812 list
*list
= o
->ptr
;
3815 ln
= listIndex(list
, index
);
3817 addReply(c
,shared
.outofrangeerr
);
3819 robj
*ele
= listNodeValue(ln
);
3822 listNodeValue(ln
) = c
->argv
[3];
3823 incrRefCount(c
->argv
[3]);
3824 addReply(c
,shared
.ok
);
3831 static void popGenericCommand(redisClient
*c
, int where
) {
3834 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3836 addReply(c
,shared
.nullbulk
);
3838 if (o
->type
!= REDIS_LIST
) {
3839 addReply(c
,shared
.wrongtypeerr
);
3841 list
*list
= o
->ptr
;
3844 if (where
== REDIS_HEAD
)
3845 ln
= listFirst(list
);
3847 ln
= listLast(list
);
3850 addReply(c
,shared
.nullbulk
);
3852 robj
*ele
= listNodeValue(ln
);
3853 addReplyBulkLen(c
,ele
);
3855 addReply(c
,shared
.crlf
);
3856 listDelNode(list
,ln
);
3863 static void lpopCommand(redisClient
*c
) {
3864 popGenericCommand(c
,REDIS_HEAD
);
3867 static void rpopCommand(redisClient
*c
) {
3868 popGenericCommand(c
,REDIS_TAIL
);
3871 static void lrangeCommand(redisClient
*c
) {
3873 int start
= atoi(c
->argv
[2]->ptr
);
3874 int end
= atoi(c
->argv
[3]->ptr
);
3876 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3878 addReply(c
,shared
.nullmultibulk
);
3880 if (o
->type
!= REDIS_LIST
) {
3881 addReply(c
,shared
.wrongtypeerr
);
3883 list
*list
= o
->ptr
;
3885 int llen
= listLength(list
);
3889 /* convert negative indexes */
3890 if (start
< 0) start
= llen
+start
;
3891 if (end
< 0) end
= llen
+end
;
3892 if (start
< 0) start
= 0;
3893 if (end
< 0) end
= 0;
3895 /* indexes sanity checks */
3896 if (start
> end
|| start
>= llen
) {
3897 /* Out of range start or start > end result in empty list */
3898 addReply(c
,shared
.emptymultibulk
);
3901 if (end
>= llen
) end
= llen
-1;
3902 rangelen
= (end
-start
)+1;
3904 /* Return the result in form of a multi-bulk reply */
3905 ln
= listIndex(list
, start
);
3906 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
3907 for (j
= 0; j
< rangelen
; j
++) {
3908 ele
= listNodeValue(ln
);
3909 addReplyBulkLen(c
,ele
);
3911 addReply(c
,shared
.crlf
);
3918 static void ltrimCommand(redisClient
*c
) {
3920 int start
= atoi(c
->argv
[2]->ptr
);
3921 int end
= atoi(c
->argv
[3]->ptr
);
3923 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3925 addReply(c
,shared
.ok
);
3927 if (o
->type
!= REDIS_LIST
) {
3928 addReply(c
,shared
.wrongtypeerr
);
3930 list
*list
= o
->ptr
;
3932 int llen
= listLength(list
);
3933 int j
, ltrim
, rtrim
;
3935 /* convert negative indexes */
3936 if (start
< 0) start
= llen
+start
;
3937 if (end
< 0) end
= llen
+end
;
3938 if (start
< 0) start
= 0;
3939 if (end
< 0) end
= 0;
3941 /* indexes sanity checks */
3942 if (start
> end
|| start
>= llen
) {
3943 /* Out of range start or start > end result in empty list */
3947 if (end
>= llen
) end
= llen
-1;
3952 /* Remove list elements to perform the trim */
3953 for (j
= 0; j
< ltrim
; j
++) {
3954 ln
= listFirst(list
);
3955 listDelNode(list
,ln
);
3957 for (j
= 0; j
< rtrim
; j
++) {
3958 ln
= listLast(list
);
3959 listDelNode(list
,ln
);
3962 addReply(c
,shared
.ok
);
3967 static void lremCommand(redisClient
*c
) {
3970 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3972 addReply(c
,shared
.czero
);
3974 if (o
->type
!= REDIS_LIST
) {
3975 addReply(c
,shared
.wrongtypeerr
);
3977 list
*list
= o
->ptr
;
3978 listNode
*ln
, *next
;
3979 int toremove
= atoi(c
->argv
[2]->ptr
);
3984 toremove
= -toremove
;
3987 ln
= fromtail
? list
->tail
: list
->head
;
3989 robj
*ele
= listNodeValue(ln
);
3991 next
= fromtail
? ln
->prev
: ln
->next
;
3992 if (compareStringObjects(ele
,c
->argv
[3]) == 0) {
3993 listDelNode(list
,ln
);
3996 if (toremove
&& removed
== toremove
) break;
4000 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
4005 /* This is the semantic of this command:
4006 * RPOPLPUSH srclist dstlist:
4007 * IF LLEN(srclist) > 0
4008 * element = RPOP srclist
4009 * LPUSH dstlist element
4016 * The idea is to be able to get an element from a list in a reliable way
4017 * since the element is not just returned but pushed against another list
4018 * as well. This command was originally proposed by Ezra Zygmuntowicz.
4020 static void rpoplpushcommand(redisClient
*c
) {
4023 sobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4025 addReply(c
,shared
.nullbulk
);
4027 if (sobj
->type
!= REDIS_LIST
) {
4028 addReply(c
,shared
.wrongtypeerr
);
4030 list
*srclist
= sobj
->ptr
;
4031 listNode
*ln
= listLast(srclist
);
4034 addReply(c
,shared
.nullbulk
);
4036 robj
*dobj
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4037 robj
*ele
= listNodeValue(ln
);
4040 if (dobj
&& dobj
->type
!= REDIS_LIST
) {
4041 addReply(c
,shared
.wrongtypeerr
);
4045 /* Add the element to the target list (unless it's directly
4046 * passed to some BLPOP-ing client */
4047 if (!handleClientsWaitingListPush(c
,c
->argv
[2],ele
)) {
4049 /* Create the list if the key does not exist */
4050 dobj
= createListObject();
4051 dictAdd(c
->db
->dict
,c
->argv
[2],dobj
);
4052 incrRefCount(c
->argv
[2]);
4054 dstlist
= dobj
->ptr
;
4055 listAddNodeHead(dstlist
,ele
);
4059 /* Send the element to the client as reply as well */
4060 addReplyBulkLen(c
,ele
);
4062 addReply(c
,shared
.crlf
);
4064 /* Finally remove the element from the source list */
4065 listDelNode(srclist
,ln
);
4073 /* ==================================== Sets ================================ */
4075 static void saddCommand(redisClient
*c
) {
4078 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4080 set
= createSetObject();
4081 dictAdd(c
->db
->dict
,c
->argv
[1],set
);
4082 incrRefCount(c
->argv
[1]);
4084 if (set
->type
!= REDIS_SET
) {
4085 addReply(c
,shared
.wrongtypeerr
);
4089 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
4090 incrRefCount(c
->argv
[2]);
4092 addReply(c
,shared
.cone
);
4094 addReply(c
,shared
.czero
);
4098 static void sremCommand(redisClient
*c
) {
4101 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4103 addReply(c
,shared
.czero
);
4105 if (set
->type
!= REDIS_SET
) {
4106 addReply(c
,shared
.wrongtypeerr
);
4109 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
4111 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4112 addReply(c
,shared
.cone
);
4114 addReply(c
,shared
.czero
);
4119 static void smoveCommand(redisClient
*c
) {
4120 robj
*srcset
, *dstset
;
4122 srcset
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4123 dstset
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4125 /* If the source key does not exist return 0, if it's of the wrong type
4127 if (srcset
== NULL
|| srcset
->type
!= REDIS_SET
) {
4128 addReply(c
, srcset
? shared
.wrongtypeerr
: shared
.czero
);
4131 /* Error if the destination key is not a set as well */
4132 if (dstset
&& dstset
->type
!= REDIS_SET
) {
4133 addReply(c
,shared
.wrongtypeerr
);
4136 /* Remove the element from the source set */
4137 if (dictDelete(srcset
->ptr
,c
->argv
[3]) == DICT_ERR
) {
4138 /* Key not found in the src set! return zero */
4139 addReply(c
,shared
.czero
);
4143 /* Add the element to the destination set */
4145 dstset
= createSetObject();
4146 dictAdd(c
->db
->dict
,c
->argv
[2],dstset
);
4147 incrRefCount(c
->argv
[2]);
4149 if (dictAdd(dstset
->ptr
,c
->argv
[3],NULL
) == DICT_OK
)
4150 incrRefCount(c
->argv
[3]);
4151 addReply(c
,shared
.cone
);
4154 static void sismemberCommand(redisClient
*c
) {
4157 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4159 addReply(c
,shared
.czero
);
4161 if (set
->type
!= REDIS_SET
) {
4162 addReply(c
,shared
.wrongtypeerr
);
4165 if (dictFind(set
->ptr
,c
->argv
[2]))
4166 addReply(c
,shared
.cone
);
4168 addReply(c
,shared
.czero
);
4172 static void scardCommand(redisClient
*c
) {
4176 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4178 addReply(c
,shared
.czero
);
4181 if (o
->type
!= REDIS_SET
) {
4182 addReply(c
,shared
.wrongtypeerr
);
4185 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4191 static void spopCommand(redisClient
*c
) {
4195 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4197 addReply(c
,shared
.nullbulk
);
4199 if (set
->type
!= REDIS_SET
) {
4200 addReply(c
,shared
.wrongtypeerr
);
4203 de
= dictGetRandomKey(set
->ptr
);
4205 addReply(c
,shared
.nullbulk
);
4207 robj
*ele
= dictGetEntryKey(de
);
4209 addReplyBulkLen(c
,ele
);
4211 addReply(c
,shared
.crlf
);
4212 dictDelete(set
->ptr
,ele
);
4213 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4219 static void srandmemberCommand(redisClient
*c
) {
4223 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4225 addReply(c
,shared
.nullbulk
);
4227 if (set
->type
!= REDIS_SET
) {
4228 addReply(c
,shared
.wrongtypeerr
);
4231 de
= dictGetRandomKey(set
->ptr
);
4233 addReply(c
,shared
.nullbulk
);
4235 robj
*ele
= dictGetEntryKey(de
);
4237 addReplyBulkLen(c
,ele
);
4239 addReply(c
,shared
.crlf
);
4244 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
4245 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
4247 return dictSize(*d1
)-dictSize(*d2
);
4250 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, unsigned long setsnum
, robj
*dstkey
) {
4251 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4254 robj
*lenobj
= NULL
, *dstset
= NULL
;
4255 unsigned long j
, cardinality
= 0;
4257 for (j
= 0; j
< setsnum
; j
++) {
4261 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4262 lookupKeyRead(c
->db
,setskeys
[j
]);
4266 if (deleteKey(c
->db
,dstkey
))
4268 addReply(c
,shared
.czero
);
4270 addReply(c
,shared
.nullmultibulk
);
4274 if (setobj
->type
!= REDIS_SET
) {
4276 addReply(c
,shared
.wrongtypeerr
);
4279 dv
[j
] = setobj
->ptr
;
4281 /* Sort sets from the smallest to largest, this will improve our
4282 * algorithm's performace */
4283 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
4285 /* The first thing we should output is the total number of elements...
4286 * since this is a multi-bulk write, but at this stage we don't know
4287 * the intersection set size, so we use a trick, append an empty object
4288 * to the output list and save the pointer to later modify it with the
4291 lenobj
= createObject(REDIS_STRING
,NULL
);
4293 decrRefCount(lenobj
);
4295 /* If we have a target key where to store the resulting set
4296 * create this key with an empty set inside */
4297 dstset
= createSetObject();
4300 /* Iterate all the elements of the first (smallest) set, and test
4301 * the element against all the other sets, if at least one set does
4302 * not include the element it is discarded */
4303 di
= dictGetIterator(dv
[0]);
4305 while((de
= dictNext(di
)) != NULL
) {
4308 for (j
= 1; j
< setsnum
; j
++)
4309 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
4311 continue; /* at least one set does not contain the member */
4312 ele
= dictGetEntryKey(de
);
4314 addReplyBulkLen(c
,ele
);
4316 addReply(c
,shared
.crlf
);
4319 dictAdd(dstset
->ptr
,ele
,NULL
);
4323 dictReleaseIterator(di
);
4326 /* Store the resulting set into the target */
4327 deleteKey(c
->db
,dstkey
);
4328 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4329 incrRefCount(dstkey
);
4333 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",cardinality
);
4335 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4336 dictSize((dict
*)dstset
->ptr
)));
4342 static void sinterCommand(redisClient
*c
) {
4343 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
4346 static void sinterstoreCommand(redisClient
*c
) {
4347 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
4350 #define REDIS_OP_UNION 0
4351 #define REDIS_OP_DIFF 1
4353 static void sunionDiffGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
, int op
) {
4354 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4357 robj
*dstset
= NULL
;
4358 int j
, cardinality
= 0;
4360 for (j
= 0; j
< setsnum
; j
++) {
4364 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4365 lookupKeyRead(c
->db
,setskeys
[j
]);
4370 if (setobj
->type
!= REDIS_SET
) {
4372 addReply(c
,shared
.wrongtypeerr
);
4375 dv
[j
] = setobj
->ptr
;
4378 /* We need a temp set object to store our union. If the dstkey
4379 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
4380 * this set object will be the resulting object to set into the target key*/
4381 dstset
= createSetObject();
4383 /* Iterate all the elements of all the sets, add every element a single
4384 * time to the result set */
4385 for (j
= 0; j
< setsnum
; j
++) {
4386 if (op
== REDIS_OP_DIFF
&& j
== 0 && !dv
[j
]) break; /* result set is empty */
4387 if (!dv
[j
]) continue; /* non existing keys are like empty sets */
4389 di
= dictGetIterator(dv
[j
]);
4391 while((de
= dictNext(di
)) != NULL
) {
4394 /* dictAdd will not add the same element multiple times */
4395 ele
= dictGetEntryKey(de
);
4396 if (op
== REDIS_OP_UNION
|| j
== 0) {
4397 if (dictAdd(dstset
->ptr
,ele
,NULL
) == DICT_OK
) {
4401 } else if (op
== REDIS_OP_DIFF
) {
4402 if (dictDelete(dstset
->ptr
,ele
) == DICT_OK
) {
4407 dictReleaseIterator(di
);
4409 if (op
== REDIS_OP_DIFF
&& cardinality
== 0) break; /* result set is empty */
4412 /* Output the content of the resulting set, if not in STORE mode */
4414 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",cardinality
));
4415 di
= dictGetIterator(dstset
->ptr
);
4416 while((de
= dictNext(di
)) != NULL
) {
4419 ele
= dictGetEntryKey(de
);
4420 addReplyBulkLen(c
,ele
);
4422 addReply(c
,shared
.crlf
);
4424 dictReleaseIterator(di
);
4426 /* If we have a target key where to store the resulting set
4427 * create this key with the result set inside */
4428 deleteKey(c
->db
,dstkey
);
4429 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4430 incrRefCount(dstkey
);
4435 decrRefCount(dstset
);
4437 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4438 dictSize((dict
*)dstset
->ptr
)));
4444 static void sunionCommand(redisClient
*c
) {
4445 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_UNION
);
4448 static void sunionstoreCommand(redisClient
*c
) {
4449 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_UNION
);
4452 static void sdiffCommand(redisClient
*c
) {
4453 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_DIFF
);
4456 static void sdiffstoreCommand(redisClient
*c
) {
4457 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_DIFF
);
4460 /* ==================================== ZSets =============================== */
4462 /* ZSETs are ordered sets using two data structures to hold the same elements
4463 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
4466 * The elements are added to an hash table mapping Redis objects to scores.
4467 * At the same time the elements are added to a skip list mapping scores
4468 * to Redis objects (so objects are sorted by scores in this "view"). */
4470 /* This skiplist implementation is almost a C translation of the original
4471 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
4472 * Alternative to Balanced Trees", modified in three ways:
4473 * a) this implementation allows for repeated values.
4474 * b) the comparison is not just by key (our 'score') but by satellite data.
4475 * c) there is a back pointer, so it's a doubly linked list with the back
4476 * pointers being only at "level 1". This allows to traverse the list
4477 * from tail to head, useful for ZREVRANGE. */
4479 static zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
4480 zskiplistNode
*zn
= zmalloc(sizeof(*zn
));
4482 zn
->forward
= zmalloc(sizeof(zskiplistNode
*) * level
);
4488 static zskiplist
*zslCreate(void) {
4492 zsl
= zmalloc(sizeof(*zsl
));
4495 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
4496 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++)
4497 zsl
->header
->forward
[j
] = NULL
;
4498 zsl
->header
->backward
= NULL
;
4503 static void zslFreeNode(zskiplistNode
*node
) {
4504 decrRefCount(node
->obj
);
4505 zfree(node
->forward
);
4509 static void zslFree(zskiplist
*zsl
) {
4510 zskiplistNode
*node
= zsl
->header
->forward
[0], *next
;
4512 zfree(zsl
->header
->forward
);
4515 next
= node
->forward
[0];
4522 static int zslRandomLevel(void) {
4524 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
4529 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
4530 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4534 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4535 while (x
->forward
[i
] &&
4536 (x
->forward
[i
]->score
< score
||
4537 (x
->forward
[i
]->score
== score
&&
4538 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
4542 /* we assume the key is not already inside, since we allow duplicated
4543 * scores, and the re-insertion of score and redis object should never
4544 * happpen since the caller of zslInsert() should test in the hash table
4545 * if the element is already inside or not. */
4546 level
= zslRandomLevel();
4547 if (level
> zsl
->level
) {
4548 for (i
= zsl
->level
; i
< level
; i
++)
4549 update
[i
] = zsl
->header
;
4552 x
= zslCreateNode(level
,score
,obj
);
4553 for (i
= 0; i
< level
; i
++) {
4554 x
->forward
[i
] = update
[i
]->forward
[i
];
4555 update
[i
]->forward
[i
] = x
;
4557 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
4559 x
->forward
[0]->backward
= x
;
4565 /* Delete an element with matching score/object from the skiplist. */
4566 static int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
4567 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4571 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4572 while (x
->forward
[i
] &&
4573 (x
->forward
[i
]->score
< score
||
4574 (x
->forward
[i
]->score
== score
&&
4575 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
4579 /* We may have multiple elements with the same score, what we need
4580 * is to find the element with both the right score and object. */
4582 if (x
&& score
== x
->score
&& compareStringObjects(x
->obj
,obj
) == 0) {
4583 for (i
= 0; i
< zsl
->level
; i
++) {
4584 if (update
[i
]->forward
[i
] != x
) break;
4585 update
[i
]->forward
[i
] = x
->forward
[i
];
4587 if (x
->forward
[0]) {
4588 x
->forward
[0]->backward
= (x
->backward
== zsl
->header
) ?
4591 zsl
->tail
= x
->backward
;
4594 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
4599 return 0; /* not found */
4601 return 0; /* not found */
4604 /* Delete all the elements with score between min and max from the skiplist.
4605 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
4606 * Note that this function takes the reference to the hash table view of the
4607 * sorted set, in order to remove the elements from the hash table too. */
4608 static unsigned long zslDeleteRange(zskiplist
*zsl
, double min
, double max
, dict
*dict
) {
4609 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4610 unsigned long removed
= 0;
4614 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4615 while (x
->forward
[i
] && x
->forward
[i
]->score
< min
)
4619 /* We may have multiple elements with the same score, what we need
4620 * is to find the element with both the right score and object. */
4622 while (x
&& x
->score
<= max
) {
4623 zskiplistNode
*next
;
4625 for (i
= 0; i
< zsl
->level
; i
++) {
4626 if (update
[i
]->forward
[i
] != x
) break;
4627 update
[i
]->forward
[i
] = x
->forward
[i
];
4629 if (x
->forward
[0]) {
4630 x
->forward
[0]->backward
= (x
->backward
== zsl
->header
) ?
4633 zsl
->tail
= x
->backward
;
4635 next
= x
->forward
[0];
4636 dictDelete(dict
,x
->obj
);
4638 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
4644 return removed
; /* not found */
4647 /* Find the first node having a score equal or greater than the specified one.
4648 * Returns NULL if there is no match. */
4649 static zskiplistNode
*zslFirstWithScore(zskiplist
*zsl
, double score
) {
4654 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4655 while (x
->forward
[i
] && x
->forward
[i
]->score
< score
)
4658 /* We may have multiple elements with the same score, what we need
4659 * is to find the element with both the right score and object. */
4660 return x
->forward
[0];
4663 /* The actual Z-commands implementations */
4665 /* This generic command implements both ZADD and ZINCRBY.
4666 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
4667 * the increment if the operation is a ZINCRBY (doincrement == 1). */
4668 static void zaddGenericCommand(redisClient
*c
, robj
*key
, robj
*ele
, double scoreval
, int doincrement
) {
4673 zsetobj
= lookupKeyWrite(c
->db
,key
);
4674 if (zsetobj
== NULL
) {
4675 zsetobj
= createZsetObject();
4676 dictAdd(c
->db
->dict
,key
,zsetobj
);
4679 if (zsetobj
->type
!= REDIS_ZSET
) {
4680 addReply(c
,shared
.wrongtypeerr
);
4686 /* Ok now since we implement both ZADD and ZINCRBY here the code
4687 * needs to handle the two different conditions. It's all about setting
4688 * '*score', that is, the new score to set, to the right value. */
4689 score
= zmalloc(sizeof(double));
4693 /* Read the old score. If the element was not present starts from 0 */
4694 de
= dictFind(zs
->dict
,ele
);
4696 double *oldscore
= dictGetEntryVal(de
);
4697 *score
= *oldscore
+ scoreval
;
4705 /* What follows is a simple remove and re-insert operation that is common
4706 * to both ZADD and ZINCRBY... */
4707 if (dictAdd(zs
->dict
,ele
,score
) == DICT_OK
) {
4708 /* case 1: New element */
4709 incrRefCount(ele
); /* added to hash */
4710 zslInsert(zs
->zsl
,*score
,ele
);
4711 incrRefCount(ele
); /* added to skiplist */
4714 addReplyDouble(c
,*score
);
4716 addReply(c
,shared
.cone
);
4721 /* case 2: Score update operation */
4722 de
= dictFind(zs
->dict
,ele
);
4723 redisAssert(de
!= NULL
);
4724 oldscore
= dictGetEntryVal(de
);
4725 if (*score
!= *oldscore
) {
4728 /* Remove and insert the element in the skip list with new score */
4729 deleted
= zslDelete(zs
->zsl
,*oldscore
,ele
);
4730 redisAssert(deleted
!= 0);
4731 zslInsert(zs
->zsl
,*score
,ele
);
4733 /* Update the score in the hash table */
4734 dictReplace(zs
->dict
,ele
,score
);
4740 addReplyDouble(c
,*score
);
4742 addReply(c
,shared
.czero
);
4746 static void zaddCommand(redisClient
*c
) {
4749 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
4750 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0);
4753 static void zincrbyCommand(redisClient
*c
) {
4756 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
4757 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1);
4760 static void zremCommand(redisClient
*c
) {
4764 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4765 if (zsetobj
== NULL
) {
4766 addReply(c
,shared
.czero
);
4772 if (zsetobj
->type
!= REDIS_ZSET
) {
4773 addReply(c
,shared
.wrongtypeerr
);
4777 de
= dictFind(zs
->dict
,c
->argv
[2]);
4779 addReply(c
,shared
.czero
);
4782 /* Delete from the skiplist */
4783 oldscore
= dictGetEntryVal(de
);
4784 deleted
= zslDelete(zs
->zsl
,*oldscore
,c
->argv
[2]);
4785 redisAssert(deleted
!= 0);
4787 /* Delete from the hash table */
4788 dictDelete(zs
->dict
,c
->argv
[2]);
4789 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
4791 addReply(c
,shared
.cone
);
4795 static void zremrangebyscoreCommand(redisClient
*c
) {
4796 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
4797 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
4801 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4802 if (zsetobj
== NULL
) {
4803 addReply(c
,shared
.czero
);
4807 if (zsetobj
->type
!= REDIS_ZSET
) {
4808 addReply(c
,shared
.wrongtypeerr
);
4812 deleted
= zslDeleteRange(zs
->zsl
,min
,max
,zs
->dict
);
4813 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
4814 server
.dirty
+= deleted
;
4815 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",deleted
));
4819 static void zrangeGenericCommand(redisClient
*c
, int reverse
) {
4821 int start
= atoi(c
->argv
[2]->ptr
);
4822 int end
= atoi(c
->argv
[3]->ptr
);
4825 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
4827 } else if (c
->argc
>= 5) {
4828 addReply(c
,shared
.syntaxerr
);
4832 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4834 addReply(c
,shared
.nullmultibulk
);
4836 if (o
->type
!= REDIS_ZSET
) {
4837 addReply(c
,shared
.wrongtypeerr
);
4839 zset
*zsetobj
= o
->ptr
;
4840 zskiplist
*zsl
= zsetobj
->zsl
;
4843 int llen
= zsl
->length
;
4847 /* convert negative indexes */
4848 if (start
< 0) start
= llen
+start
;
4849 if (end
< 0) end
= llen
+end
;
4850 if (start
< 0) start
= 0;
4851 if (end
< 0) end
= 0;
4853 /* indexes sanity checks */
4854 if (start
> end
|| start
>= llen
) {
4855 /* Out of range start or start > end result in empty list */
4856 addReply(c
,shared
.emptymultibulk
);
4859 if (end
>= llen
) end
= llen
-1;
4860 rangelen
= (end
-start
)+1;
4862 /* Return the result in form of a multi-bulk reply */
4868 ln
= zsl
->header
->forward
[0];
4870 ln
= ln
->forward
[0];
4873 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",
4874 withscores
? (rangelen
*2) : rangelen
));
4875 for (j
= 0; j
< rangelen
; j
++) {
4877 addReplyBulkLen(c
,ele
);
4879 addReply(c
,shared
.crlf
);
4881 addReplyDouble(c
,ln
->score
);
4882 ln
= reverse
? ln
->backward
: ln
->forward
[0];
4888 static void zrangeCommand(redisClient
*c
) {
4889 zrangeGenericCommand(c
,0);
4892 static void zrevrangeCommand(redisClient
*c
) {
4893 zrangeGenericCommand(c
,1);
4896 static void zrangebyscoreCommand(redisClient
*c
) {
4898 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
4899 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
4900 int offset
= 0, limit
= -1;
4902 if (c
->argc
!= 4 && c
->argc
!= 7) {
4904 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
4906 } else if (c
->argc
== 7 && strcasecmp(c
->argv
[4]->ptr
,"limit")) {
4907 addReply(c
,shared
.syntaxerr
);
4909 } else if (c
->argc
== 7) {
4910 offset
= atoi(c
->argv
[5]->ptr
);
4911 limit
= atoi(c
->argv
[6]->ptr
);
4912 if (offset
< 0) offset
= 0;
4915 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4917 addReply(c
,shared
.nullmultibulk
);
4919 if (o
->type
!= REDIS_ZSET
) {
4920 addReply(c
,shared
.wrongtypeerr
);
4922 zset
*zsetobj
= o
->ptr
;
4923 zskiplist
*zsl
= zsetobj
->zsl
;
4926 unsigned int rangelen
= 0;
4928 /* Get the first node with the score >= min */
4929 ln
= zslFirstWithScore(zsl
,min
);
4931 /* No element matching the speciifed interval */
4932 addReply(c
,shared
.emptymultibulk
);
4936 /* We don't know in advance how many matching elements there
4937 * are in the list, so we push this object that will represent
4938 * the multi-bulk length in the output buffer, and will "fix"
4940 lenobj
= createObject(REDIS_STRING
,NULL
);
4942 decrRefCount(lenobj
);
4944 while(ln
&& ln
->score
<= max
) {
4947 ln
= ln
->forward
[0];
4950 if (limit
== 0) break;
4952 addReplyBulkLen(c
,ele
);
4954 addReply(c
,shared
.crlf
);
4955 ln
= ln
->forward
[0];
4957 if (limit
> 0) limit
--;
4959 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",rangelen
);
4964 static void zcardCommand(redisClient
*c
) {
4968 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4970 addReply(c
,shared
.czero
);
4973 if (o
->type
!= REDIS_ZSET
) {
4974 addReply(c
,shared
.wrongtypeerr
);
4977 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",zs
->zsl
->length
));
4982 static void zscoreCommand(redisClient
*c
) {
4986 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4988 addReply(c
,shared
.nullbulk
);
4991 if (o
->type
!= REDIS_ZSET
) {
4992 addReply(c
,shared
.wrongtypeerr
);
4997 de
= dictFind(zs
->dict
,c
->argv
[2]);
4999 addReply(c
,shared
.nullbulk
);
5001 double *score
= dictGetEntryVal(de
);
5003 addReplyDouble(c
,*score
);
5009 /* ========================= Non type-specific commands ==================== */
5011 static void flushdbCommand(redisClient
*c
) {
5012 server
.dirty
+= dictSize(c
->db
->dict
);
5013 dictEmpty(c
->db
->dict
);
5014 dictEmpty(c
->db
->expires
);
5015 addReply(c
,shared
.ok
);
5018 static void flushallCommand(redisClient
*c
) {
5019 server
.dirty
+= emptyDb();
5020 addReply(c
,shared
.ok
);
5021 rdbSave(server
.dbfilename
);
5025 static redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
5026 redisSortOperation
*so
= zmalloc(sizeof(*so
));
5028 so
->pattern
= pattern
;
5032 /* Return the value associated to the key with a name obtained
5033 * substituting the first occurence of '*' in 'pattern' with 'subst' */
5034 static robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
5038 int prefixlen
, sublen
, postfixlen
;
5039 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
5043 char buf
[REDIS_SORTKEY_MAX
+1];
5046 /* If the pattern is "#" return the substitution object itself in order
5047 * to implement the "SORT ... GET #" feature. */
5048 spat
= pattern
->ptr
;
5049 if (spat
[0] == '#' && spat
[1] == '\0') {
5053 /* The substitution object may be specially encoded. If so we create
5054 * a decoded object on the fly. Otherwise getDecodedObject will just
5055 * increment the ref count, that we'll decrement later. */
5056 subst
= getDecodedObject(subst
);
5059 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
5060 p
= strchr(spat
,'*');
5062 decrRefCount(subst
);
5067 sublen
= sdslen(ssub
);
5068 postfixlen
= sdslen(spat
)-(prefixlen
+1);
5069 memcpy(keyname
.buf
,spat
,prefixlen
);
5070 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
5071 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
5072 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
5073 keyname
.len
= prefixlen
+sublen
+postfixlen
;
5075 initStaticStringObject(keyobj
,((char*)&keyname
)+(sizeof(long)*2))
5076 decrRefCount(subst
);
5078 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
5079 return lookupKeyRead(db
,&keyobj
);
5082 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
5083 * the additional parameter is not standard but a BSD-specific we have to
5084 * pass sorting parameters via the global 'server' structure */
5085 static int sortCompare(const void *s1
, const void *s2
) {
5086 const redisSortObject
*so1
= s1
, *so2
= s2
;
5089 if (!server
.sort_alpha
) {
5090 /* Numeric sorting. Here it's trivial as we precomputed scores */
5091 if (so1
->u
.score
> so2
->u
.score
) {
5093 } else if (so1
->u
.score
< so2
->u
.score
) {
5099 /* Alphanumeric sorting */
5100 if (server
.sort_bypattern
) {
5101 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
5102 /* At least one compare object is NULL */
5103 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
5105 else if (so1
->u
.cmpobj
== NULL
)
5110 /* We have both the objects, use strcoll */
5111 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
5114 /* Compare elements directly */
5117 dec1
= getDecodedObject(so1
->obj
);
5118 dec2
= getDecodedObject(so2
->obj
);
5119 cmp
= strcoll(dec1
->ptr
,dec2
->ptr
);
5124 return server
.sort_desc
? -cmp
: cmp
;
5127 /* The SORT command is the most complex command in Redis. Warning: this code
5128 * is optimized for speed and a bit less for readability */
5129 static void sortCommand(redisClient
*c
) {
5132 int desc
= 0, alpha
= 0;
5133 int limit_start
= 0, limit_count
= -1, start
, end
;
5134 int j
, dontsort
= 0, vectorlen
;
5135 int getop
= 0; /* GET operation counter */
5136 robj
*sortval
, *sortby
= NULL
, *storekey
= NULL
;
5137 redisSortObject
*vector
; /* Resulting vector to sort */
5139 /* Lookup the key to sort. It must be of the right types */
5140 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
5141 if (sortval
== NULL
) {
5142 addReply(c
,shared
.nullmultibulk
);
5145 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
&&
5146 sortval
->type
!= REDIS_ZSET
)
5148 addReply(c
,shared
.wrongtypeerr
);
5152 /* Create a list of operations to perform for every sorted element.
5153 * Operations can be GET/DEL/INCR/DECR */
5154 operations
= listCreate();
5155 listSetFreeMethod(operations
,zfree
);
5158 /* Now we need to protect sortval incrementing its count, in the future
5159 * SORT may have options able to overwrite/delete keys during the sorting
5160 * and the sorted key itself may get destroied */
5161 incrRefCount(sortval
);
5163 /* The SORT command has an SQL-alike syntax, parse it */
5164 while(j
< c
->argc
) {
5165 int leftargs
= c
->argc
-j
-1;
5166 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
5168 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
5170 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
5172 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
5173 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
5174 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
5176 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"store") && leftargs
>= 1) {
5177 storekey
= c
->argv
[j
+1];
5179 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
5180 sortby
= c
->argv
[j
+1];
5181 /* If the BY pattern does not contain '*', i.e. it is constant,
5182 * we don't need to sort nor to lookup the weight keys. */
5183 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
5185 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
5186 listAddNodeTail(operations
,createSortOperation(
5187 REDIS_SORT_GET
,c
->argv
[j
+1]));
5191 decrRefCount(sortval
);
5192 listRelease(operations
);
5193 addReply(c
,shared
.syntaxerr
);
5199 /* Load the sorting vector with all the objects to sort */
5200 switch(sortval
->type
) {
5201 case REDIS_LIST
: vectorlen
= listLength((list
*)sortval
->ptr
); break;
5202 case REDIS_SET
: vectorlen
= dictSize((dict
*)sortval
->ptr
); break;
5203 case REDIS_ZSET
: vectorlen
= dictSize(((zset
*)sortval
->ptr
)->dict
); break;
5204 default: vectorlen
= 0; redisAssert(0); /* Avoid GCC warning */
5206 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
5209 if (sortval
->type
== REDIS_LIST
) {
5210 list
*list
= sortval
->ptr
;
5214 while((ln
= listYield(list
))) {
5215 robj
*ele
= ln
->value
;
5216 vector
[j
].obj
= ele
;
5217 vector
[j
].u
.score
= 0;
5218 vector
[j
].u
.cmpobj
= NULL
;
5226 if (sortval
->type
== REDIS_SET
) {
5229 zset
*zs
= sortval
->ptr
;
5233 di
= dictGetIterator(set
);
5234 while((setele
= dictNext(di
)) != NULL
) {
5235 vector
[j
].obj
= dictGetEntryKey(setele
);
5236 vector
[j
].u
.score
= 0;
5237 vector
[j
].u
.cmpobj
= NULL
;
5240 dictReleaseIterator(di
);
5242 redisAssert(j
== vectorlen
);
5244 /* Now it's time to load the right scores in the sorting vector */
5245 if (dontsort
== 0) {
5246 for (j
= 0; j
< vectorlen
; j
++) {
5250 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
5251 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
5253 vector
[j
].u
.cmpobj
= getDecodedObject(byval
);
5255 if (byval
->encoding
== REDIS_ENCODING_RAW
) {
5256 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
5258 /* Don't need to decode the object if it's
5259 * integer-encoded (the only encoding supported) so
5260 * far. We can just cast it */
5261 if (byval
->encoding
== REDIS_ENCODING_INT
) {
5262 vector
[j
].u
.score
= (long)byval
->ptr
;
5264 redisAssert(1 != 1);
5269 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_RAW
)
5270 vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
5272 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_INT
)
5273 vector
[j
].u
.score
= (long) vector
[j
].obj
->ptr
;
5275 redisAssert(1 != 1);
5282 /* We are ready to sort the vector... perform a bit of sanity check
5283 * on the LIMIT option too. We'll use a partial version of quicksort. */
5284 start
= (limit_start
< 0) ? 0 : limit_start
;
5285 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
5286 if (start
>= vectorlen
) {
5287 start
= vectorlen
-1;
5290 if (end
>= vectorlen
) end
= vectorlen
-1;
5292 if (dontsort
== 0) {
5293 server
.sort_desc
= desc
;
5294 server
.sort_alpha
= alpha
;
5295 server
.sort_bypattern
= sortby
? 1 : 0;
5296 if (sortby
&& (start
!= 0 || end
!= vectorlen
-1))
5297 pqsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
, start
,end
);
5299 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
5302 /* Send command output to the output buffer, performing the specified
5303 * GET/DEL/INCR/DECR operations if any. */
5304 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
5305 if (storekey
== NULL
) {
5306 /* STORE option not specified, sent the sorting result to client */
5307 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
5308 for (j
= start
; j
<= end
; j
++) {
5311 addReplyBulkLen(c
,vector
[j
].obj
);
5312 addReply(c
,vector
[j
].obj
);
5313 addReply(c
,shared
.crlf
);
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 addReply(c
,shared
.nullbulk
);
5325 addReplyBulkLen(c
,val
);
5327 addReply(c
,shared
.crlf
);
5330 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
5335 robj
*listObject
= createListObject();
5336 list
*listPtr
= (list
*) listObject
->ptr
;
5338 /* STORE option specified, set the sorting result as a List object */
5339 for (j
= start
; j
<= end
; j
++) {
5342 listAddNodeTail(listPtr
,vector
[j
].obj
);
5343 incrRefCount(vector
[j
].obj
);
5345 listRewind(operations
);
5346 while((ln
= listYield(operations
))) {
5347 redisSortOperation
*sop
= ln
->value
;
5348 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
5351 if (sop
->type
== REDIS_SORT_GET
) {
5352 if (!val
|| val
->type
!= REDIS_STRING
) {
5353 listAddNodeTail(listPtr
,createStringObject("",0));
5355 listAddNodeTail(listPtr
,val
);
5359 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
5363 if (dictReplace(c
->db
->dict
,storekey
,listObject
)) {
5364 incrRefCount(storekey
);
5366 /* Note: we add 1 because the DB is dirty anyway since even if the
5367 * SORT result is empty a new key is set and maybe the old content
5369 server
.dirty
+= 1+outputlen
;
5370 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",outputlen
));
5374 decrRefCount(sortval
);
5375 listRelease(operations
);
5376 for (j
= 0; j
< vectorlen
; j
++) {
5377 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
5378 decrRefCount(vector
[j
].u
.cmpobj
);
5383 /* Create the string returned by the INFO command. This is decoupled
5384 * by the INFO command itself as we need to report the same information
5385 * on memory corruption problems. */
5386 static sds
genRedisInfoString(void) {
5388 time_t uptime
= time(NULL
)-server
.stat_starttime
;
5391 info
= sdscatprintf(sdsempty(),
5392 "redis_version:%s\r\n"
5394 "multiplexing_api:%s\r\n"
5395 "uptime_in_seconds:%ld\r\n"
5396 "uptime_in_days:%ld\r\n"
5397 "connected_clients:%d\r\n"
5398 "connected_slaves:%d\r\n"
5399 "blocked_clients:%d\r\n"
5400 "used_memory:%zu\r\n"
5401 "changes_since_last_save:%lld\r\n"
5402 "bgsave_in_progress:%d\r\n"
5403 "last_save_time:%ld\r\n"
5404 "bgrewriteaof_in_progress:%d\r\n"
5405 "total_connections_received:%lld\r\n"
5406 "total_commands_processed:%lld\r\n"
5409 (sizeof(long) == 8) ? "64" : "32",
5413 listLength(server
.clients
)-listLength(server
.slaves
),
5414 listLength(server
.slaves
),
5415 server
.blockedclients
,
5418 server
.bgsavechildpid
!= -1,
5420 server
.bgrewritechildpid
!= -1,
5421 server
.stat_numconnections
,
5422 server
.stat_numcommands
,
5423 server
.masterhost
== NULL
? "master" : "slave"
5425 if (server
.masterhost
) {
5426 info
= sdscatprintf(info
,
5427 "master_host:%s\r\n"
5428 "master_port:%d\r\n"
5429 "master_link_status:%s\r\n"
5430 "master_last_io_seconds_ago:%d\r\n"
5433 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
5435 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1
5438 for (j
= 0; j
< server
.dbnum
; j
++) {
5439 long long keys
, vkeys
;
5441 keys
= dictSize(server
.db
[j
].dict
);
5442 vkeys
= dictSize(server
.db
[j
].expires
);
5443 if (keys
|| vkeys
) {
5444 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
5451 static void infoCommand(redisClient
*c
) {
5452 sds info
= genRedisInfoString();
5453 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
5454 (unsigned long)sdslen(info
)));
5455 addReplySds(c
,info
);
5456 addReply(c
,shared
.crlf
);
5459 static void monitorCommand(redisClient
*c
) {
5460 /* ignore MONITOR if aleady slave or in monitor mode */
5461 if (c
->flags
& REDIS_SLAVE
) return;
5463 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
5465 listAddNodeTail(server
.monitors
,c
);
5466 addReply(c
,shared
.ok
);
5469 /* ================================= Expire ================================= */
5470 static int removeExpire(redisDb
*db
, robj
*key
) {
5471 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
5478 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
5479 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
5487 /* Return the expire time of the specified key, or -1 if no expire
5488 * is associated with this key (i.e. the key is non volatile) */
5489 static time_t getExpire(redisDb
*db
, robj
*key
) {
5492 /* No expire? return ASAP */
5493 if (dictSize(db
->expires
) == 0 ||
5494 (de
= dictFind(db
->expires
,key
)) == NULL
) return -1;
5496 return (time_t) dictGetEntryVal(de
);
5499 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
5503 /* No expire? return ASAP */
5504 if (dictSize(db
->expires
) == 0 ||
5505 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
5507 /* Lookup the expire */
5508 when
= (time_t) dictGetEntryVal(de
);
5509 if (time(NULL
) <= when
) return 0;
5511 /* Delete the key */
5512 dictDelete(db
->expires
,key
);
5513 return dictDelete(db
->dict
,key
) == DICT_OK
;
5516 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
5519 /* No expire? return ASAP */
5520 if (dictSize(db
->expires
) == 0 ||
5521 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
5523 /* Delete the key */
5525 dictDelete(db
->expires
,key
);
5526 return dictDelete(db
->dict
,key
) == DICT_OK
;
5529 static void expireGenericCommand(redisClient
*c
, robj
*key
, time_t seconds
) {
5532 de
= dictFind(c
->db
->dict
,key
);
5534 addReply(c
,shared
.czero
);
5538 if (deleteKey(c
->db
,key
)) server
.dirty
++;
5539 addReply(c
, shared
.cone
);
5542 time_t when
= time(NULL
)+seconds
;
5543 if (setExpire(c
->db
,key
,when
)) {
5544 addReply(c
,shared
.cone
);
5547 addReply(c
,shared
.czero
);
5553 static void expireCommand(redisClient
*c
) {
5554 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10));
5557 static void expireatCommand(redisClient
*c
) {
5558 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10)-time(NULL
));
5561 static void ttlCommand(redisClient
*c
) {
5565 expire
= getExpire(c
->db
,c
->argv
[1]);
5567 ttl
= (int) (expire
-time(NULL
));
5568 if (ttl
< 0) ttl
= -1;
5570 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",ttl
));
5573 /* ================================ MULTI/EXEC ============================== */
5575 /* Client state initialization for MULTI/EXEC */
5576 static void initClientMultiState(redisClient
*c
) {
5577 c
->mstate
.commands
= NULL
;
5578 c
->mstate
.count
= 0;
5581 /* Release all the resources associated with MULTI/EXEC state */
5582 static void freeClientMultiState(redisClient
*c
) {
5585 for (j
= 0; j
< c
->mstate
.count
; j
++) {
5587 multiCmd
*mc
= c
->mstate
.commands
+j
;
5589 for (i
= 0; i
< mc
->argc
; i
++)
5590 decrRefCount(mc
->argv
[i
]);
5593 zfree(c
->mstate
.commands
);
5596 /* Add a new command into the MULTI commands queue */
5597 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
) {
5601 c
->mstate
.commands
= zrealloc(c
->mstate
.commands
,
5602 sizeof(multiCmd
)*(c
->mstate
.count
+1));
5603 mc
= c
->mstate
.commands
+c
->mstate
.count
;
5606 mc
->argv
= zmalloc(sizeof(robj
*)*c
->argc
);
5607 memcpy(mc
->argv
,c
->argv
,sizeof(robj
*)*c
->argc
);
5608 for (j
= 0; j
< c
->argc
; j
++)
5609 incrRefCount(mc
->argv
[j
]);
5613 static void multiCommand(redisClient
*c
) {
5614 c
->flags
|= REDIS_MULTI
;
5615 addReply(c
,shared
.ok
);
5618 static void execCommand(redisClient
*c
) {
5623 if (!(c
->flags
& REDIS_MULTI
)) {
5624 addReplySds(c
,sdsnew("-ERR EXEC without MULTI\r\n"));
5628 orig_argv
= c
->argv
;
5629 orig_argc
= c
->argc
;
5630 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->mstate
.count
));
5631 for (j
= 0; j
< c
->mstate
.count
; j
++) {
5632 c
->argc
= c
->mstate
.commands
[j
].argc
;
5633 c
->argv
= c
->mstate
.commands
[j
].argv
;
5634 call(c
,c
->mstate
.commands
[j
].cmd
);
5636 c
->argv
= orig_argv
;
5637 c
->argc
= orig_argc
;
5638 freeClientMultiState(c
);
5639 initClientMultiState(c
);
5640 c
->flags
&= (~REDIS_MULTI
);
5643 /* =========================== Blocking Operations ========================= */
5645 /* Currently Redis blocking operations support is limited to list POP ops,
5646 * so the current implementation is not fully generic, but it is also not
5647 * completely specific so it will not require a rewrite to support new
5648 * kind of blocking operations in the future.
5650 * Still it's important to note that list blocking operations can be already
5651 * used as a notification mechanism in order to implement other blocking
5652 * operations at application level, so there must be a very strong evidence
5653 * of usefulness and generality before new blocking operations are implemented.
5655 * This is how the current blocking POP works, we use BLPOP as example:
5656 * - If the user calls BLPOP and the key exists and contains a non empty list
5657 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
5658 * if there is not to block.
5659 * - If instead BLPOP is called and the key does not exists or the list is
5660 * empty we need to block. In order to do so we remove the notification for
5661 * new data to read in the client socket (so that we'll not serve new
5662 * requests if the blocking request is not served). Also we put the client
5663 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
5664 * blocking for this keys.
5665 * - If a PUSH operation against a key with blocked clients waiting is
5666 * performed, we serve the first in the list: basically instead to push
5667 * the new element inside the list we return it to the (first / oldest)
5668 * blocking client, unblock the client, and remove it form the list.
5670 * The above comment and the source code should be enough in order to understand
5671 * the implementation and modify / fix it later.
5674 /* Set a client in blocking mode for the specified key, with the specified
5676 static void blockForKeys(redisClient
*c
, robj
**keys
, int numkeys
, time_t timeout
) {
5681 c
->blockingkeys
= zmalloc(sizeof(robj
*)*numkeys
);
5682 c
->blockingkeysnum
= numkeys
;
5683 c
->blockingto
= timeout
;
5684 for (j
= 0; j
< numkeys
; j
++) {
5685 /* Add the key in the client structure, to map clients -> keys */
5686 c
->blockingkeys
[j
] = keys
[j
];
5687 incrRefCount(keys
[j
]);
5689 /* And in the other "side", to map keys -> clients */
5690 de
= dictFind(c
->db
->blockingkeys
,keys
[j
]);
5694 /* For every key we take a list of clients blocked for it */
5696 retval
= dictAdd(c
->db
->blockingkeys
,keys
[j
],l
);
5697 incrRefCount(keys
[j
]);
5698 assert(retval
== DICT_OK
);
5700 l
= dictGetEntryVal(de
);
5702 listAddNodeTail(l
,c
);
5704 /* Mark the client as a blocked client */
5705 c
->flags
|= REDIS_BLOCKED
;
5706 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
5707 server
.blockedclients
++;
5710 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
5711 static void unblockClient(redisClient
*c
) {
5716 assert(c
->blockingkeys
!= NULL
);
5717 /* The client may wait for multiple keys, so unblock it for every key. */
5718 for (j
= 0; j
< c
->blockingkeysnum
; j
++) {
5719 /* Remove this client from the list of clients waiting for this key. */
5720 de
= dictFind(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
5722 l
= dictGetEntryVal(de
);
5723 listDelNode(l
,listSearchKey(l
,c
));
5724 /* If the list is empty we need to remove it to avoid wasting memory */
5725 if (listLength(l
) == 0)
5726 dictDelete(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
5727 decrRefCount(c
->blockingkeys
[j
]);
5729 /* Cleanup the client structure */
5730 zfree(c
->blockingkeys
);
5731 c
->blockingkeys
= NULL
;
5732 c
->flags
&= (~REDIS_BLOCKED
);
5733 server
.blockedclients
--;
5734 /* Ok now we are ready to get read events from socket, note that we
5735 * can't trap errors here as it's possible that unblockClients() is
5736 * called from freeClient() itself, and the only thing we can do
5737 * if we failed to register the READABLE event is to kill the client.
5738 * Still the following function should never fail in the real world as
5739 * we are sure the file descriptor is sane, and we exit on out of mem. */
5740 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
, readQueryFromClient
, c
);
5741 /* As a final step we want to process data if there is some command waiting
5742 * in the input buffer. Note that this is safe even if unblockClient()
5743 * gets called from freeClient() because freeClient() will be smart
5744 * enough to call this function *after* c->querybuf was set to NULL. */
5745 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0) processInputBuffer(c
);
5748 /* This should be called from any function PUSHing into lists.
5749 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
5750 * 'ele' is the element pushed.
5752 * If the function returns 0 there was no client waiting for a list push
5755 * If the function returns 1 there was a client waiting for a list push
5756 * against this key, the element was passed to this client thus it's not
5757 * needed to actually add it to the list and the caller should return asap. */
5758 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
) {
5759 struct dictEntry
*de
;
5760 redisClient
*receiver
;
5764 de
= dictFind(c
->db
->blockingkeys
,key
);
5765 if (de
== NULL
) return 0;
5766 l
= dictGetEntryVal(de
);
5769 receiver
= ln
->value
;
5771 addReplySds(receiver
,sdsnew("*2\r\n"));
5772 addReplyBulkLen(receiver
,key
);
5773 addReply(receiver
,key
);
5774 addReply(receiver
,shared
.crlf
);
5775 addReplyBulkLen(receiver
,ele
);
5776 addReply(receiver
,ele
);
5777 addReply(receiver
,shared
.crlf
);
5778 unblockClient(receiver
);
5782 /* Blocking RPOP/LPOP */
5783 static void blockingPopGenericCommand(redisClient
*c
, int where
) {
5788 for (j
= 1; j
< c
->argc
-1; j
++) {
5789 o
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
5791 if (o
->type
!= REDIS_LIST
) {
5792 addReply(c
,shared
.wrongtypeerr
);
5795 list
*list
= o
->ptr
;
5796 if (listLength(list
) != 0) {
5797 /* If the list contains elements fall back to the usual
5798 * non-blocking POP operation */
5799 robj
*argv
[2], **orig_argv
;
5802 /* We need to alter the command arguments before to call
5803 * popGenericCommand() as the command takes a single key. */
5804 orig_argv
= c
->argv
;
5805 orig_argc
= c
->argc
;
5806 argv
[1] = c
->argv
[j
];
5810 /* Also the return value is different, we need to output
5811 * the multi bulk reply header and the key name. The
5812 * "real" command will add the last element (the value)
5813 * for us. If this souds like an hack to you it's just
5814 * because it is... */
5815 addReplySds(c
,sdsnew("*2\r\n"));
5816 addReplyBulkLen(c
,argv
[1]);
5817 addReply(c
,argv
[1]);
5818 addReply(c
,shared
.crlf
);
5819 popGenericCommand(c
,where
);
5821 /* Fix the client structure with the original stuff */
5822 c
->argv
= orig_argv
;
5823 c
->argc
= orig_argc
;
5829 /* If the list is empty or the key does not exists we must block */
5830 timeout
= strtol(c
->argv
[c
->argc
-1]->ptr
,NULL
,10);
5831 if (timeout
> 0) timeout
+= time(NULL
);
5832 blockForKeys(c
,c
->argv
+1,c
->argc
-2,timeout
);
5835 static void blpopCommand(redisClient
*c
) {
5836 blockingPopGenericCommand(c
,REDIS_HEAD
);
5839 static void brpopCommand(redisClient
*c
) {
5840 blockingPopGenericCommand(c
,REDIS_TAIL
);
5843 /* =============================== Replication ============================= */
5845 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
5846 ssize_t nwritten
, ret
= size
;
5847 time_t start
= time(NULL
);
5851 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
5852 nwritten
= write(fd
,ptr
,size
);
5853 if (nwritten
== -1) return -1;
5857 if ((time(NULL
)-start
) > timeout
) {
5865 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
5866 ssize_t nread
, totread
= 0;
5867 time_t start
= time(NULL
);
5871 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
5872 nread
= read(fd
,ptr
,size
);
5873 if (nread
== -1) return -1;
5878 if ((time(NULL
)-start
) > timeout
) {
5886 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
5893 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
5896 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
5907 static void syncCommand(redisClient
*c
) {
5908 /* ignore SYNC if aleady slave or in monitor mode */
5909 if (c
->flags
& REDIS_SLAVE
) return;
5911 /* SYNC can't be issued when the server has pending data to send to
5912 * the client about already issued commands. We need a fresh reply
5913 * buffer registering the differences between the BGSAVE and the current
5914 * dataset, so that we can copy to other slaves if needed. */
5915 if (listLength(c
->reply
) != 0) {
5916 addReplySds(c
,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
5920 redisLog(REDIS_NOTICE
,"Slave ask for synchronization");
5921 /* Here we need to check if there is a background saving operation
5922 * in progress, or if it is required to start one */
5923 if (server
.bgsavechildpid
!= -1) {
5924 /* Ok a background save is in progress. Let's check if it is a good
5925 * one for replication, i.e. if there is another slave that is
5926 * registering differences since the server forked to save */
5930 listRewind(server
.slaves
);
5931 while((ln
= listYield(server
.slaves
))) {
5933 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) break;
5936 /* Perfect, the server is already registering differences for
5937 * another slave. Set the right state, and copy the buffer. */
5938 listRelease(c
->reply
);
5939 c
->reply
= listDup(slave
->reply
);
5940 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
5941 redisLog(REDIS_NOTICE
,"Waiting for end of BGSAVE for SYNC");
5943 /* No way, we need to wait for the next BGSAVE in order to
5944 * register differences */
5945 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
5946 redisLog(REDIS_NOTICE
,"Waiting for next BGSAVE for SYNC");
5949 /* Ok we don't have a BGSAVE in progress, let's start one */
5950 redisLog(REDIS_NOTICE
,"Starting BGSAVE for SYNC");
5951 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
5952 redisLog(REDIS_NOTICE
,"Replication failed, can't BGSAVE");
5953 addReplySds(c
,sdsnew("-ERR Unalbe to perform background save\r\n"));
5956 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
5959 c
->flags
|= REDIS_SLAVE
;
5961 listAddNodeTail(server
.slaves
,c
);
5965 static void sendBulkToSlave(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
5966 redisClient
*slave
= privdata
;
5968 REDIS_NOTUSED(mask
);
5969 char buf
[REDIS_IOBUF_LEN
];
5970 ssize_t nwritten
, buflen
;
5972 if (slave
->repldboff
== 0) {
5973 /* Write the bulk write count before to transfer the DB. In theory here
5974 * we don't know how much room there is in the output buffer of the
5975 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
5976 * operations) will never be smaller than the few bytes we need. */
5979 bulkcount
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
5981 if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
))
5989 lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
);
5990 buflen
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
);
5992 redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s",
5993 (buflen
== 0) ? "premature EOF" : strerror(errno
));
5997 if ((nwritten
= write(fd
,buf
,buflen
)) == -1) {
5998 redisLog(REDIS_DEBUG
,"Write error sending DB to slave: %s",
6003 slave
->repldboff
+= nwritten
;
6004 if (slave
->repldboff
== slave
->repldbsize
) {
6005 close(slave
->repldbfd
);
6006 slave
->repldbfd
= -1;
6007 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
6008 slave
->replstate
= REDIS_REPL_ONLINE
;
6009 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
,
6010 sendReplyToClient
, slave
) == AE_ERR
) {
6014 addReplySds(slave
,sdsempty());
6015 redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded");
6019 /* This function is called at the end of every backgrond saving.
6020 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
6021 * otherwise REDIS_ERR is passed to the function.
6023 * The goal of this function is to handle slaves waiting for a successful
6024 * background saving in order to perform non-blocking synchronization. */
6025 static void updateSlavesWaitingBgsave(int bgsaveerr
) {
6027 int startbgsave
= 0;
6029 listRewind(server
.slaves
);
6030 while((ln
= listYield(server
.slaves
))) {
6031 redisClient
*slave
= ln
->value
;
6033 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) {
6035 slave
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6036 } else if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) {
6037 struct redis_stat buf
;
6039 if (bgsaveerr
!= REDIS_OK
) {
6041 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error");
6044 if ((slave
->repldbfd
= open(server
.dbfilename
,O_RDONLY
)) == -1 ||
6045 redis_fstat(slave
->repldbfd
,&buf
) == -1) {
6047 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
));
6050 slave
->repldboff
= 0;
6051 slave
->repldbsize
= buf
.st_size
;
6052 slave
->replstate
= REDIS_REPL_SEND_BULK
;
6053 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
6054 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, sendBulkToSlave
, slave
) == AE_ERR
) {
6061 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
6062 listRewind(server
.slaves
);
6063 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed");
6064 while((ln
= listYield(server
.slaves
))) {
6065 redisClient
*slave
= ln
->value
;
6067 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
)
6074 static int syncWithMaster(void) {
6075 char buf
[1024], tmpfile
[256], authcmd
[1024];
6077 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
6081 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
6086 /* AUTH with the master if required. */
6087 if(server
.masterauth
) {
6088 snprintf(authcmd
, 1024, "AUTH %s\r\n", server
.masterauth
);
6089 if (syncWrite(fd
, authcmd
, strlen(server
.masterauth
)+7, 5) == -1) {
6091 redisLog(REDIS_WARNING
,"Unable to AUTH to MASTER: %s",
6095 /* Read the AUTH result. */
6096 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6098 redisLog(REDIS_WARNING
,"I/O error reading auth result from MASTER: %s",
6102 if (buf
[0] != '+') {
6104 redisLog(REDIS_WARNING
,"Cannot AUTH to MASTER, is the masterauth password correct?");
6109 /* Issue the SYNC command */
6110 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
6112 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
6116 /* Read the bulk write count */
6117 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6119 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
6123 if (buf
[0] != '$') {
6125 redisLog(REDIS_WARNING
,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
6128 dumpsize
= atoi(buf
+1);
6129 redisLog(REDIS_NOTICE
,"Receiving %d bytes data dump from MASTER",dumpsize
);
6130 /* Read the bulk write data on a temp file */
6131 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
6132 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644);
6135 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
6139 int nread
, nwritten
;
6141 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
6143 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
6149 nwritten
= write(dfd
,buf
,nread
);
6150 if (nwritten
== -1) {
6151 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
6159 if (rename(tmpfile
,server
.dbfilename
) == -1) {
6160 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
6166 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
6167 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
6171 server
.master
= createClient(fd
);
6172 server
.master
->flags
|= REDIS_MASTER
;
6173 server
.master
->authenticated
= 1;
6174 server
.replstate
= REDIS_REPL_CONNECTED
;
6178 static void slaveofCommand(redisClient
*c
) {
6179 if (!strcasecmp(c
->argv
[1]->ptr
,"no") &&
6180 !strcasecmp(c
->argv
[2]->ptr
,"one")) {
6181 if (server
.masterhost
) {
6182 sdsfree(server
.masterhost
);
6183 server
.masterhost
= NULL
;
6184 if (server
.master
) freeClient(server
.master
);
6185 server
.replstate
= REDIS_REPL_NONE
;
6186 redisLog(REDIS_NOTICE
,"MASTER MODE enabled (user request)");
6189 sdsfree(server
.masterhost
);
6190 server
.masterhost
= sdsdup(c
->argv
[1]->ptr
);
6191 server
.masterport
= atoi(c
->argv
[2]->ptr
);
6192 if (server
.master
) freeClient(server
.master
);
6193 server
.replstate
= REDIS_REPL_CONNECT
;
6194 redisLog(REDIS_NOTICE
,"SLAVE OF %s:%d enabled (user request)",
6195 server
.masterhost
, server
.masterport
);
6197 addReply(c
,shared
.ok
);
6200 /* ============================ Maxmemory directive ======================== */
6202 /* This function gets called when 'maxmemory' is set on the config file to limit
6203 * the max memory used by the server, and we are out of memory.
6204 * This function will try to, in order:
6206 * - Free objects from the free list
6207 * - Try to remove keys with an EXPIRE set
6209 * It is not possible to free enough memory to reach used-memory < maxmemory
6210 * the server will start refusing commands that will enlarge even more the
6213 static void freeMemoryIfNeeded(void) {
6214 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
6215 if (listLength(server
.objfreelist
)) {
6218 listNode
*head
= listFirst(server
.objfreelist
);
6219 o
= listNodeValue(head
);
6220 listDelNode(server
.objfreelist
,head
);
6223 int j
, k
, freed
= 0;
6225 for (j
= 0; j
< server
.dbnum
; j
++) {
6227 robj
*minkey
= NULL
;
6228 struct dictEntry
*de
;
6230 if (dictSize(server
.db
[j
].expires
)) {
6232 /* From a sample of three keys drop the one nearest to
6233 * the natural expire */
6234 for (k
= 0; k
< 3; k
++) {
6237 de
= dictGetRandomKey(server
.db
[j
].expires
);
6238 t
= (time_t) dictGetEntryVal(de
);
6239 if (minttl
== -1 || t
< minttl
) {
6240 minkey
= dictGetEntryKey(de
);
6244 deleteKey(server
.db
+j
,minkey
);
6247 if (!freed
) return; /* nothing to free... */
6252 /* ============================== Append Only file ========================== */
6254 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
6255 sds buf
= sdsempty();
6261 /* The DB this command was targetting is not the same as the last command
6262 * we appendend. To issue a SELECT command is needed. */
6263 if (dictid
!= server
.appendseldb
) {
6266 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
6267 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
6268 (unsigned long)strlen(seldb
),seldb
);
6269 server
.appendseldb
= dictid
;
6272 /* "Fix" the argv vector if the command is EXPIRE. We want to translate
6273 * EXPIREs into EXPIREATs calls */
6274 if (cmd
->proc
== expireCommand
) {
6277 tmpargv
[0] = createStringObject("EXPIREAT",8);
6278 tmpargv
[1] = argv
[1];
6279 incrRefCount(argv
[1]);
6280 when
= time(NULL
)+strtol(argv
[2]->ptr
,NULL
,10);
6281 tmpargv
[2] = createObject(REDIS_STRING
,
6282 sdscatprintf(sdsempty(),"%ld",when
));
6286 /* Append the actual command */
6287 buf
= sdscatprintf(buf
,"*%d\r\n",argc
);
6288 for (j
= 0; j
< argc
; j
++) {
6291 o
= getDecodedObject(o
);
6292 buf
= sdscatprintf(buf
,"$%lu\r\n",(unsigned long)sdslen(o
->ptr
));
6293 buf
= sdscatlen(buf
,o
->ptr
,sdslen(o
->ptr
));
6294 buf
= sdscatlen(buf
,"\r\n",2);
6298 /* Free the objects from the modified argv for EXPIREAT */
6299 if (cmd
->proc
== expireCommand
) {
6300 for (j
= 0; j
< 3; j
++)
6301 decrRefCount(argv
[j
]);
6304 /* We want to perform a single write. This should be guaranteed atomic
6305 * at least if the filesystem we are writing is a real physical one.
6306 * While this will save us against the server being killed I don't think
6307 * there is much to do about the whole server stopping for power problems
6309 nwritten
= write(server
.appendfd
,buf
,sdslen(buf
));
6310 if (nwritten
!= (signed)sdslen(buf
)) {
6311 /* Ooops, we are in troubles. The best thing to do for now is
6312 * to simply exit instead to give the illusion that everything is
6313 * working as expected. */
6314 if (nwritten
== -1) {
6315 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
6317 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
6321 /* If a background append only file rewriting is in progress we want to
6322 * accumulate the differences between the child DB and the current one
6323 * in a buffer, so that when the child process will do its work we
6324 * can append the differences to the new append only file. */
6325 if (server
.bgrewritechildpid
!= -1)
6326 server
.bgrewritebuf
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
));
6330 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
||
6331 (server
.appendfsync
== APPENDFSYNC_EVERYSEC
&&
6332 now
-server
.lastfsync
> 1))
6334 fsync(server
.appendfd
); /* Let's try to get this data on the disk */
6335 server
.lastfsync
= now
;
6339 /* In Redis commands are always executed in the context of a client, so in
6340 * order to load the append only file we need to create a fake client. */
6341 static struct redisClient
*createFakeClient(void) {
6342 struct redisClient
*c
= zmalloc(sizeof(*c
));
6346 c
->querybuf
= sdsempty();
6350 /* We set the fake client as a slave waiting for the synchronization
6351 * so that Redis will not try to send replies to this client. */
6352 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
6353 c
->reply
= listCreate();
6354 listSetFreeMethod(c
->reply
,decrRefCount
);
6355 listSetDupMethod(c
->reply
,dupClientReplyValue
);
6359 static void freeFakeClient(struct redisClient
*c
) {
6360 sdsfree(c
->querybuf
);
6361 listRelease(c
->reply
);
6365 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
6366 * error (the append only file is zero-length) REDIS_ERR is returned. On
6367 * fatal error an error message is logged and the program exists. */
6368 int loadAppendOnlyFile(char *filename
) {
6369 struct redisClient
*fakeClient
;
6370 FILE *fp
= fopen(filename
,"r");
6371 struct redis_stat sb
;
6373 if (redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0)
6377 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
6381 fakeClient
= createFakeClient();
6388 struct redisCommand
*cmd
;
6390 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
6396 if (buf
[0] != '*') goto fmterr
;
6398 argv
= zmalloc(sizeof(robj
*)*argc
);
6399 for (j
= 0; j
< argc
; j
++) {
6400 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
6401 if (buf
[0] != '$') goto fmterr
;
6402 len
= strtol(buf
+1,NULL
,10);
6403 argsds
= sdsnewlen(NULL
,len
);
6404 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
6405 argv
[j
] = createObject(REDIS_STRING
,argsds
);
6406 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
6409 /* Command lookup */
6410 cmd
= lookupCommand(argv
[0]->ptr
);
6412 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
6415 /* Try object sharing and encoding */
6416 if (server
.shareobjects
) {
6418 for(j
= 1; j
< argc
; j
++)
6419 argv
[j
] = tryObjectSharing(argv
[j
]);
6421 if (cmd
->flags
& REDIS_CMD_BULK
)
6422 tryObjectEncoding(argv
[argc
-1]);
6423 /* Run the command in the context of a fake client */
6424 fakeClient
->argc
= argc
;
6425 fakeClient
->argv
= argv
;
6426 cmd
->proc(fakeClient
);
6427 /* Discard the reply objects list from the fake client */
6428 while(listLength(fakeClient
->reply
))
6429 listDelNode(fakeClient
->reply
,listFirst(fakeClient
->reply
));
6430 /* Clean up, ready for the next command */
6431 for (j
= 0; j
< argc
; j
++) decrRefCount(argv
[j
]);
6435 freeFakeClient(fakeClient
);
6440 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
6442 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
6446 redisLog(REDIS_WARNING
,"Bad file format reading the append only file");
6450 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
6451 static int fwriteBulk(FILE *fp
, robj
*obj
) {
6453 obj
= getDecodedObject(obj
);
6454 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(long)sdslen(obj
->ptr
));
6455 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) goto err
;
6456 if (sdslen(obj
->ptr
) && fwrite(obj
->ptr
,sdslen(obj
->ptr
),1,fp
) == 0)
6458 if (fwrite("\r\n",2,1,fp
) == 0) goto err
;
6466 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
6467 static int fwriteBulkDouble(FILE *fp
, double d
) {
6468 char buf
[128], dbuf
[128];
6470 snprintf(dbuf
,sizeof(dbuf
),"%.17g\r\n",d
);
6471 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(dbuf
)-2);
6472 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
6473 if (fwrite(dbuf
,strlen(dbuf
),1,fp
) == 0) return 0;
6477 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
6478 static int fwriteBulkLong(FILE *fp
, long l
) {
6479 char buf
[128], lbuf
[128];
6481 snprintf(lbuf
,sizeof(lbuf
),"%ld\r\n",l
);
6482 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(lbuf
)-2);
6483 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
6484 if (fwrite(lbuf
,strlen(lbuf
),1,fp
) == 0) return 0;
6488 /* Write a sequence of commands able to fully rebuild the dataset into
6489 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
6490 static int rewriteAppendOnlyFile(char *filename
) {
6491 dictIterator
*di
= NULL
;
6496 time_t now
= time(NULL
);
6498 /* Note that we have to use a different temp name here compared to the
6499 * one used by rewriteAppendOnlyFileBackground() function. */
6500 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
6501 fp
= fopen(tmpfile
,"w");
6503 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
6506 for (j
= 0; j
< server
.dbnum
; j
++) {
6507 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
6508 redisDb
*db
= server
.db
+j
;
6510 if (dictSize(d
) == 0) continue;
6511 di
= dictGetIterator(d
);
6517 /* SELECT the new DB */
6518 if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
;
6519 if (fwriteBulkLong(fp
,j
) == 0) goto werr
;
6521 /* Iterate this DB writing every entry */
6522 while((de
= dictNext(di
)) != NULL
) {
6523 robj
*key
= dictGetEntryKey(de
);
6524 robj
*o
= dictGetEntryVal(de
);
6525 time_t expiretime
= getExpire(db
,key
);
6527 /* Save the key and associated value */
6528 if (o
->type
== REDIS_STRING
) {
6529 /* Emit a SET command */
6530 char cmd
[]="*3\r\n$3\r\nSET\r\n";
6531 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6533 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6534 if (fwriteBulk(fp
,o
) == 0) goto werr
;
6535 } else if (o
->type
== REDIS_LIST
) {
6536 /* Emit the RPUSHes needed to rebuild the list */
6537 list
*list
= o
->ptr
;
6541 while((ln
= listYield(list
))) {
6542 char cmd
[]="*3\r\n$5\r\nRPUSH\r\n";
6543 robj
*eleobj
= listNodeValue(ln
);
6545 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6546 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6547 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6549 } else if (o
->type
== REDIS_SET
) {
6550 /* Emit the SADDs needed to rebuild the set */
6552 dictIterator
*di
= dictGetIterator(set
);
6555 while((de
= dictNext(di
)) != NULL
) {
6556 char cmd
[]="*3\r\n$4\r\nSADD\r\n";
6557 robj
*eleobj
= dictGetEntryKey(de
);
6559 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6560 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6561 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6563 dictReleaseIterator(di
);
6564 } else if (o
->type
== REDIS_ZSET
) {
6565 /* Emit the ZADDs needed to rebuild the sorted set */
6567 dictIterator
*di
= dictGetIterator(zs
->dict
);
6570 while((de
= dictNext(di
)) != NULL
) {
6571 char cmd
[]="*4\r\n$4\r\nZADD\r\n";
6572 robj
*eleobj
= dictGetEntryKey(de
);
6573 double *score
= dictGetEntryVal(de
);
6575 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6576 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6577 if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
;
6578 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6580 dictReleaseIterator(di
);
6582 redisAssert(0 != 0);
6584 /* Save the expire time */
6585 if (expiretime
!= -1) {
6586 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n";
6587 /* If this key is already expired skip it */
6588 if (expiretime
< now
) continue;
6589 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6590 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6591 if (fwriteBulkLong(fp
,expiretime
) == 0) goto werr
;
6594 dictReleaseIterator(di
);
6597 /* Make sure data will not remain on the OS's output buffers */
6602 /* Use RENAME to make sure the DB file is changed atomically only
6603 * if the generate DB file is ok. */
6604 if (rename(tmpfile
,filename
) == -1) {
6605 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
6609 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
6615 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
6616 if (di
) dictReleaseIterator(di
);
6620 /* This is how rewriting of the append only file in background works:
6622 * 1) The user calls BGREWRITEAOF
6623 * 2) Redis calls this function, that forks():
6624 * 2a) the child rewrite the append only file in a temp file.
6625 * 2b) the parent accumulates differences in server.bgrewritebuf.
6626 * 3) When the child finished '2a' exists.
6627 * 4) The parent will trap the exit code, if it's OK, will append the
6628 * data accumulated into server.bgrewritebuf into the temp file, and
6629 * finally will rename(2) the temp file in the actual file name.
6630 * The the new file is reopened as the new append only file. Profit!
6632 static int rewriteAppendOnlyFileBackground(void) {
6635 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
6636 if ((childpid
= fork()) == 0) {
6641 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
6642 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
6649 if (childpid
== -1) {
6650 redisLog(REDIS_WARNING
,
6651 "Can't rewrite append only file in background: fork: %s",
6655 redisLog(REDIS_NOTICE
,
6656 "Background append only file rewriting started by pid %d",childpid
);
6657 server
.bgrewritechildpid
= childpid
;
6658 /* We set appendseldb to -1 in order to force the next call to the
6659 * feedAppendOnlyFile() to issue a SELECT command, so the differences
6660 * accumulated by the parent into server.bgrewritebuf will start
6661 * with a SELECT statement and it will be safe to merge. */
6662 server
.appendseldb
= -1;
6665 return REDIS_OK
; /* unreached */
6668 static void bgrewriteaofCommand(redisClient
*c
) {
6669 if (server
.bgrewritechildpid
!= -1) {
6670 addReplySds(c
,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
6673 if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
6674 char *status
= "+Background append only file rewriting started\r\n";
6675 addReplySds(c
,sdsnew(status
));
6677 addReply(c
,shared
.err
);
6681 static void aofRemoveTempFile(pid_t childpid
) {
6684 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
6688 /* =============================== Virtual Memory =========================== */
6689 static void vmInit(void) {
6692 server
.vm_fp
= fopen("/tmp/redisvm","w+b");
6693 if (server
.vm_fp
== NULL
) {
6694 redisLog(REDIS_WARNING
,"Impossible to open the swap file. Exiting.");
6697 server
.vm_fd
= fileno(server
.vm_fp
);
6698 server
.vm_next_page
= 0;
6699 server
.vm_near_pages
= 0;
6700 totsize
= server
.vm_pages
*server
.vm_page_size
;
6701 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
6702 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
6703 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
6707 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
6709 server
.vm_bitmap
= zmalloc((server
.vm_pages
+7)/8);
6710 redisLog(REDIS_DEBUG
,"Allocated %lld bytes page table for %lld pages",
6711 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
6712 memset(server
.vm_bitmap
,0,(server
.vm_pages
+7)/8);
6713 /* Try to remove the swap file, so the OS will really delete it from the
6714 * file system when Redis exists. */
6715 unlink("/tmp/redisvm");
6718 /* Mark the page as used */
6719 static void vmMarkPageUsed(off_t page
) {
6720 off_t byte
= page
/8;
6722 server
.vm_bitmap
[byte
] |= 1<<bit
;
6723 printf("Mark used: %lld (byte:%lld bit:%d)\n", (long long)page
,
6724 (long long)byte
, bit
);
6727 /* Mark N contiguous pages as used, with 'page' being the first. */
6728 static void vmMarkPagesUsed(off_t page
, off_t count
) {
6731 for (j
= 0; j
< count
; j
++)
6732 vmMarkPageUsed(page
+j
);
6735 /* Mark the page as free */
6736 static void vmMarkPageFree(off_t page
) {
6737 off_t byte
= page
/8;
6739 server
.vm_bitmap
[byte
] &= ~(1<<bit
);
6742 /* Mark N contiguous pages as free, with 'page' being the first. */
6743 static void vmMarkPagesFree(off_t page
, off_t count
) {
6746 for (j
= 0; j
< count
; j
++)
6747 vmMarkPageFree(page
+j
);
6750 /* Test if the page is free */
6751 static int vmFreePage(off_t page
) {
6752 off_t byte
= page
/8;
6754 return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0;
6757 /* Find N contiguous free pages storing the first page of the cluster in *first.
6758 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
6759 * REDIS_ERR is returned.
6761 * This function uses a simple algorithm: we try to allocate
6762 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
6763 * again from the start of the swap file searching for free spaces.
6765 * If it looks pretty clear that there are no free pages near our offset
6766 * we try to find less populated places doing a forward jump of
6767 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
6768 * without hurry, and then we jump again and so forth...
6770 * This function can be improved using a free list to avoid to guess
6771 * too much, since we could collect data about freed pages.
6773 * note: I implemented this function just after watching an episode of
6774 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
6776 static int vmFindContiguousPages(off_t
*first
, int n
) {
6777 off_t base
, offset
= 0, since_jump
= 0, numfree
= 0;
6779 if (server
.vm_near_pages
== REDIS_VM_MAX_NEAR_PAGES
) {
6780 server
.vm_near_pages
= 0;
6781 server
.vm_next_page
= 0;
6783 server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */
6784 base
= server
.vm_next_page
;
6786 while(offset
< server
.vm_pages
) {
6787 off_t
this = base
+offset
;
6789 printf("THIS: %lld (%c)\n", (long long) this, vmFreePage(this) ? 'F' : 'X');
6790 /* If we overflow, restart from page zero */
6791 if (this >= server
.vm_pages
) {
6792 this -= server
.vm_pages
;
6794 /* Just overflowed, what we found on tail is no longer
6795 * interesting, as it's no longer contiguous. */
6799 if (vmFreePage(this)) {
6800 /* This is a free page */
6802 /* Already got N free pages? Return to the caller, with success */
6804 *first
= this-(n
-1);
6805 server
.vm_next_page
= this+1;
6809 /* The current one is not a free page */
6813 /* Fast-forward if the current page is not free and we already
6814 * searched enough near this place. */
6816 if (!numfree
&& since_jump
>= REDIS_VM_MAX_RANDOM_JUMP
/4) {
6817 offset
+= random() % REDIS_VM_MAX_RANDOM_JUMP
;
6819 /* Note that even if we rewind after the jump, we are don't need
6820 * to make sure numfree is set to zero as we only jump *if* it
6821 * is set to zero. */
6823 /* Otherwise just check the next page */
6830 /* Swap the 'val' object relative to 'key' into disk. Store all the information
6831 * needed to later retrieve the object into the key object.
6832 * If we can't find enough contiguous empty pages to swap the object on disk
6833 * REDIS_ERR is returned. */
6834 static int vmSwapObject(robj
*key
, robj
*val
) {
6835 off_t pages
= rdbSavedObjectPages(val
);
6838 assert(key
->storage
== REDIS_VM_MEMORY
);
6839 assert(key
->refcount
== 1);
6840 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return REDIS_ERR
;
6841 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
6842 redisLog(REDIS_WARNING
,
6843 "Critical VM problem in vmSwapObject(): can't seek: %s",
6847 rdbSaveObject(server
.vm_fp
,val
);
6848 key
->vm
.page
= page
;
6849 key
->vm
.usedpages
= pages
;
6850 key
->storage
= REDIS_VM_SWAPPED
;
6851 key
->vtype
= val
->type
;
6852 decrRefCount(val
); /* Deallocate the object from memory. */
6853 vmMarkPagesUsed(page
,pages
);
6854 redisLog(REDIS_DEBUG
,"VM: object %s swapped out at %lld (%lld pages)",
6855 (unsigned char*) key
->ptr
,
6856 (unsigned long long) page
, (unsigned long long) pages
);
6860 /* Load the value object relative to the 'key' object from swap to memory.
6861 * The newly allocated object is returned.
6863 * If preview is true the unserialized object is returned to the caller but
6864 * no changes are made to the key object, nor the pages are marked as freed */
6865 static robj
*vmGenericLoadObject(robj
*key
, int preview
) {
6868 assert(key
->storage
== REDIS_VM_SWAPPED
);
6869 if (fseeko(server
.vm_fp
,key
->vm
.page
*server
.vm_page_size
,SEEK_SET
) == -1) {
6870 redisLog(REDIS_WARNING
,
6871 "Unrecoverable VM problem in vmLoadObject(): can't seek: %s",
6875 val
= rdbLoadObject(key
->vtype
,server
.vm_fp
);
6877 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmLoadObject(): can't load object from swap file: %s", strerror(errno
));
6881 key
->storage
= REDIS_VM_MEMORY
;
6882 key
->vm
.atime
= server
.unixtime
;
6883 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
6884 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk",
6885 (unsigned char*) key
->ptr
);
6890 /* Plain object loading, from swap to memory */
6891 static robj
*vmLoadObject(robj
*key
) {
6892 return vmGenericLoadObject(key
,0);
6895 /* Just load the value on disk, without to modify the key.
6896 * This is useful when we want to perform some operation on the value
6897 * without to really bring it from swap to memory, like while saving the
6898 * dataset or rewriting the append only log. */
6899 static robj
*vmPreviewObject(robj
*key
) {
6900 return vmGenericLoadObject(key
,1);
6903 /* How a good candidate is this object for swapping?
6904 * The better candidate it is, the greater the returned value.
6906 * Currently we try to perform a fast estimation of the object size in
6907 * memory, and combine it with aging informations.
6909 * Basically swappability = idle-time * log(estimated size)
6911 * Bigger objects are preferred over smaller objects, but not
6912 * proportionally, this is why we use the logarithm. This algorithm is
6913 * just a first try and will probably be tuned later. */
6914 static double computeObjectSwappability(robj
*o
) {
6915 time_t age
= server
.unixtime
- o
->vm
.atime
;
6919 struct dictEntry
*de
;
6922 if (age
<= 0) return 0;
6925 if (o
->encoding
!= REDIS_ENCODING_RAW
) {
6928 asize
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2;
6933 listNode
*ln
= listFirst(l
);
6935 asize
= sizeof(list
);
6937 robj
*ele
= ln
->value
;
6940 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
6941 (sizeof(*o
)+sdslen(ele
->ptr
)) :
6943 asize
+= (sizeof(listNode
)+elesize
)*listLength(l
);
6948 z
= (o
->type
== REDIS_ZSET
);
6949 d
= z
? ((zset
*)o
->ptr
)->dict
: o
->ptr
;
6951 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
6952 if (z
) asize
+= sizeof(zset
)-sizeof(dict
);
6957 de
= dictGetRandomKey(d
);
6958 ele
= dictGetEntryKey(de
);
6959 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
6960 (sizeof(*o
)+sdslen(ele
->ptr
)) :
6962 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
6963 if (z
) asize
+= sizeof(zskiplistNode
)*dictSize(d
);
6967 return (double)asize
*log(1+asize
);
6970 /* Try to swap an object that's a good candidate for swapping.
6971 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
6972 * to swap any object at all. */
6973 static int vmSwapOneObject(void) {
6975 struct dictEntry
*best
= NULL
;
6976 double best_swappability
= 0;
6979 for (j
= 0; j
< server
.dbnum
; j
++) {
6980 redisDb
*db
= server
.db
+j
;
6981 int maxtries
= 1000;
6983 if (dictSize(db
->dict
) == 0) continue;
6984 for (i
= 0; i
< 5; i
++) {
6986 double swappability
;
6988 if (maxtries
) maxtries
--;
6989 de
= dictGetRandomKey(db
->dict
);
6990 key
= dictGetEntryKey(de
);
6991 val
= dictGetEntryVal(de
);
6992 if (key
->storage
!= REDIS_VM_MEMORY
) {
6993 if (maxtries
) i
--; /* don't count this try */
6996 swappability
= computeObjectSwappability(val
);
6997 if (!best
|| swappability
> best_swappability
) {
6999 best_swappability
= swappability
;
7004 redisLog(REDIS_DEBUG
,"No swappable key found!");
7007 key
= dictGetEntryKey(best
);
7008 val
= dictGetEntryVal(best
);
7010 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f",
7011 key
->ptr
, best_swappability
);
7013 /* Unshare the key if needed */
7014 if (key
->refcount
> 1) {
7015 robj
*newkey
= dupStringObject(key
);
7017 key
= dictGetEntryKey(best
) = newkey
;
7020 if (vmSwapObject(key
,val
) == REDIS_OK
) {
7021 dictGetEntryVal(best
) = NULL
;
7028 /* Return true if it's safe to swap out objects in a given moment.
7029 * Basically we don't want to swap objects out while there is a BGSAVE
7030 * or a BGAEOREWRITE running in backgroud. */
7031 static int vmCanSwapOut(void) {
7032 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
7035 /* ================================= Debugging ============================== */
7037 static void debugCommand(redisClient
*c
) {
7038 if (!strcasecmp(c
->argv
[1]->ptr
,"segfault")) {
7040 } else if (!strcasecmp(c
->argv
[1]->ptr
,"reload")) {
7041 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
7042 addReply(c
,shared
.err
);
7046 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
7047 addReply(c
,shared
.err
);
7050 redisLog(REDIS_WARNING
,"DB reloaded by DEBUG RELOAD");
7051 addReply(c
,shared
.ok
);
7052 } else if (!strcasecmp(c
->argv
[1]->ptr
,"loadaof")) {
7054 if (loadAppendOnlyFile(server
.appendfilename
) != REDIS_OK
) {
7055 addReply(c
,shared
.err
);
7058 redisLog(REDIS_WARNING
,"Append Only File loaded by DEBUG LOADAOF");
7059 addReply(c
,shared
.ok
);
7060 } else if (!strcasecmp(c
->argv
[1]->ptr
,"object") && c
->argc
== 3) {
7061 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
7065 addReply(c
,shared
.nokeyerr
);
7068 key
= dictGetEntryKey(de
);
7069 val
= dictGetEntryVal(de
);
7070 addReplySds(c
,sdscatprintf(sdsempty(),
7071 "+Key at:%p refcount:%d, value at:%p refcount:%d encoding:%d serializedlength:%lld\r\n",
7072 (void*)key
, key
->refcount
, (void*)val
, val
->refcount
,
7073 val
->encoding
, rdbSavedObjectLen(val
)));
7074 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapout") && c
->argc
== 3) {
7075 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
7078 if (!server
.vm_enabled
) {
7079 addReplySds(c
,sdsnew("-ERR Virtual Memory is disabled\r\n"));
7083 addReply(c
,shared
.nokeyerr
);
7086 key
= dictGetEntryKey(de
);
7087 val
= dictGetEntryVal(de
);
7088 /* If the key is shared we want to create a copy */
7089 if (key
->refcount
> 1) {
7090 robj
*newkey
= dupStringObject(key
);
7092 key
= dictGetEntryKey(de
) = newkey
;
7095 if (key
->storage
!= REDIS_VM_MEMORY
) {
7096 addReplySds(c
,sdsnew("-ERR This key is not in memory\r\n"));
7097 } else if (vmSwapObject(key
,val
) == REDIS_OK
) {
7098 dictGetEntryVal(de
) = NULL
;
7099 addReply(c
,shared
.ok
);
7101 addReply(c
,shared
.err
);
7104 addReplySds(c
,sdsnew(
7105 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPOUT <key>|RELOAD]\r\n"));
7109 static void _redisAssert(char *estr
) {
7110 redisLog(REDIS_WARNING
,"=== ASSERTION FAILED ===");
7111 redisLog(REDIS_WARNING
,"==> %s\n",estr
);
7112 #ifdef HAVE_BACKTRACE
7113 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
7118 /* =================================== Main! ================================ */
7121 int linuxOvercommitMemoryValue(void) {
7122 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
7126 if (fgets(buf
,64,fp
) == NULL
) {
7135 void linuxOvercommitMemoryWarning(void) {
7136 if (linuxOvercommitMemoryValue() == 0) {
7137 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.");
7140 #endif /* __linux__ */
7142 static void daemonize(void) {
7146 if (fork() != 0) exit(0); /* parent exits */
7147 printf("New pid: %d\n", getpid());
7148 setsid(); /* create a new session */
7150 /* Every output goes to /dev/null. If Redis is daemonized but
7151 * the 'logfile' is set to 'stdout' in the configuration file
7152 * it will not log at all. */
7153 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
7154 dup2(fd
, STDIN_FILENO
);
7155 dup2(fd
, STDOUT_FILENO
);
7156 dup2(fd
, STDERR_FILENO
);
7157 if (fd
> STDERR_FILENO
) close(fd
);
7159 /* Try to write the pid file */
7160 fp
= fopen(server
.pidfile
,"w");
7162 fprintf(fp
,"%d\n",getpid());
7167 int main(int argc
, char **argv
) {
7170 resetServerSaveParams();
7171 loadServerConfig(argv
[1]);
7172 } else if (argc
> 2) {
7173 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
7176 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'");
7178 if (server
.daemonize
) daemonize();
7180 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
7182 linuxOvercommitMemoryWarning();
7184 if (server
.appendonly
) {
7185 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
7186 redisLog(REDIS_NOTICE
,"DB loaded from append only file");
7188 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
7189 redisLog(REDIS_NOTICE
,"DB loaded from disk");
7191 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
7192 acceptHandler
, NULL
) == AE_ERR
) oom("creating file event");
7193 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
7195 aeDeleteEventLoop(server
.el
);
7199 /* ============================= Backtrace support ========================= */
7201 #ifdef HAVE_BACKTRACE
7202 static char *findFuncName(void *pointer
, unsigned long *offset
);
7204 static void *getMcontextEip(ucontext_t
*uc
) {
7205 #if defined(__FreeBSD__)
7206 return (void*) uc
->uc_mcontext
.mc_eip
;
7207 #elif defined(__dietlibc__)
7208 return (void*) uc
->uc_mcontext
.eip
;
7209 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
7211 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
7213 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
7215 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
7216 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
7217 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
7219 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
7221 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
7222 return (void*) uc
->uc_mcontext
.gregs
[REG_EIP
]; /* Linux 32/64 bit */
7223 #elif defined(__ia64__) /* Linux IA64 */
7224 return (void*) uc
->uc_mcontext
.sc_ip
;
7230 static void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
7232 char **messages
= NULL
;
7233 int i
, trace_size
= 0;
7234 unsigned long offset
=0;
7235 ucontext_t
*uc
= (ucontext_t
*) secret
;
7237 REDIS_NOTUSED(info
);
7239 redisLog(REDIS_WARNING
,
7240 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
7241 infostring
= genRedisInfoString();
7242 redisLog(REDIS_WARNING
, "%s",infostring
);
7243 /* It's not safe to sdsfree() the returned string under memory
7244 * corruption conditions. Let it leak as we are going to abort */
7246 trace_size
= backtrace(trace
, 100);
7247 /* overwrite sigaction with caller's address */
7248 if (getMcontextEip(uc
) != NULL
) {
7249 trace
[1] = getMcontextEip(uc
);
7251 messages
= backtrace_symbols(trace
, trace_size
);
7253 for (i
=1; i
<trace_size
; ++i
) {
7254 char *fn
= findFuncName(trace
[i
], &offset
), *p
;
7256 p
= strchr(messages
[i
],'+');
7257 if (!fn
|| (p
&& ((unsigned long)strtol(p
+1,NULL
,10)) < offset
)) {
7258 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
7260 redisLog(REDIS_WARNING
,"%d redis-server %p %s + %d", i
, trace
[i
], fn
, (unsigned int)offset
);
7263 /* free(messages); Don't call free() with possibly corrupted memory. */
7267 static void setupSigSegvAction(void) {
7268 struct sigaction act
;
7270 sigemptyset (&act
.sa_mask
);
7271 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
7272 * is used. Otherwise, sa_handler is used */
7273 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
7274 act
.sa_sigaction
= segvHandler
;
7275 sigaction (SIGSEGV
, &act
, NULL
);
7276 sigaction (SIGBUS
, &act
, NULL
);
7277 sigaction (SIGFPE
, &act
, NULL
);
7278 sigaction (SIGILL
, &act
, NULL
);
7279 sigaction (SIGBUS
, &act
, NULL
);
7283 #include "staticsymbols.h"
7284 /* This function try to convert a pointer into a function name. It's used in
7285 * oreder to provide a backtrace under segmentation fault that's able to
7286 * display functions declared as static (otherwise the backtrace is useless). */
7287 static char *findFuncName(void *pointer
, unsigned long *offset
){
7289 unsigned long off
, minoff
= 0;
7291 /* Try to match against the Symbol with the smallest offset */
7292 for (i
=0; symsTable
[i
].pointer
; i
++) {
7293 unsigned long lp
= (unsigned long) pointer
;
7295 if (lp
!= (unsigned long)-1 && lp
>= symsTable
[i
].pointer
) {
7296 off
=lp
-symsTable
[i
].pointer
;
7297 if (ret
< 0 || off
< minoff
) {
7303 if (ret
== -1) return NULL
;
7305 return symsTable
[ret
].name
;
7307 #else /* HAVE_BACKTRACE */
7308 static void setupSigSegvAction(void) {
7310 #endif /* HAVE_BACKTRACE */