2 * Copyright (c) 2006-2009, Salvatore Sanfilippo <antirez at gmail dot com>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
8 * * Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * * Neither the name of Redis nor the names of its contributors may be used
14 * to endorse or promote products derived from this software without
15 * specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
30 #define REDIS_VERSION "1.3.2"
40 #define __USE_POSIX199309
46 #endif /* HAVE_BACKTRACE */
54 #include <arpa/inet.h>
58 #include <sys/resource.h>
64 #include "solarisfixes.h"
68 #include "ae.h" /* Event driven programming library */
69 #include "sds.h" /* Dynamic safe strings */
70 #include "anet.h" /* Networking the easy way */
71 #include "dict.h" /* Hash tables */
72 #include "adlist.h" /* Linked lists */
73 #include "zmalloc.h" /* total memory usage aware version of malloc/free */
74 #include "lzf.h" /* LZF compression library */
75 #include "pqsort.h" /* Partial qsort for SORT+LIMIT */
81 /* Static server configuration */
82 #define REDIS_SERVERPORT 6379 /* TCP port */
83 #define REDIS_MAXIDLETIME (60*5) /* default client timeout */
84 #define REDIS_IOBUF_LEN 1024
85 #define REDIS_LOADBUF_LEN 1024
86 #define REDIS_STATIC_ARGS 4
87 #define REDIS_DEFAULT_DBNUM 16
88 #define REDIS_CONFIGLINE_MAX 1024
89 #define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
90 #define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
91 #define REDIS_EXPIRELOOKUPS_PER_CRON 100 /* try to expire 100 keys/second */
92 #define REDIS_MAX_WRITE_PER_EVENT (1024*64)
93 #define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */
95 /* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */
96 #define REDIS_WRITEV_THRESHOLD 3
97 /* Max number of iovecs used for each writev call */
98 #define REDIS_WRITEV_IOVEC_COUNT 256
100 /* Hash table parameters */
101 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
104 #define REDIS_CMD_BULK 1 /* Bulk write command */
105 #define REDIS_CMD_INLINE 2 /* Inline command */
106 /* REDIS_CMD_DENYOOM reserves a longer comment: all the commands marked with
107 this flags will return an error when the 'maxmemory' option is set in the
108 config file and the server is using more than maxmemory bytes of memory.
109 In short this commands are denied on low memory conditions. */
110 #define REDIS_CMD_DENYOOM 4
113 #define REDIS_STRING 0
119 /* Objects encoding */
120 #define REDIS_ENCODING_RAW 0 /* Raw representation */
121 #define REDIS_ENCODING_INT 1 /* Encoded as integer */
123 /* Object types only used for dumping to disk */
124 #define REDIS_EXPIRETIME 253
125 #define REDIS_SELECTDB 254
126 #define REDIS_EOF 255
128 /* Defines related to the dump file format. To store 32 bits lengths for short
129 * keys requires a lot of space, so we check the most significant 2 bits of
130 * the first byte to interpreter the length:
132 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
133 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
134 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
135 * 11|000000 this means: specially encoded object will follow. The six bits
136 * number specify the kind of object that follows.
137 * See the REDIS_RDB_ENC_* defines.
139 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
140 * values, will fit inside. */
141 #define REDIS_RDB_6BITLEN 0
142 #define REDIS_RDB_14BITLEN 1
143 #define REDIS_RDB_32BITLEN 2
144 #define REDIS_RDB_ENCVAL 3
145 #define REDIS_RDB_LENERR UINT_MAX
147 /* When a length of a string object stored on disk has the first two bits
148 * set, the remaining two bits specify a special encoding for the object
149 * accordingly to the following defines: */
150 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
151 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
152 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
153 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
155 /* Virtual memory object->where field. */
156 #define REDIS_VM_MEMORY 0 /* The object is on memory */
157 #define REDIS_VM_SWAPPED 1 /* The object is on disk */
158 #define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
159 #define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
161 /* Virtual memory static configuration stuff.
162 * Check vmFindContiguousPages() to know more about this magic numbers. */
163 #define REDIS_VM_MAX_NEAR_PAGES 65536
164 #define REDIS_VM_MAX_RANDOM_JUMP 4096
167 #define REDIS_CLOSE 1 /* This client connection should be closed ASAP */
168 #define REDIS_SLAVE 2 /* This client is a slave server */
169 #define REDIS_MASTER 4 /* This client is a master server */
170 #define REDIS_MONITOR 8 /* This client is a slave monitor, see MONITOR */
171 #define REDIS_MULTI 16 /* This client is in a MULTI context */
172 #define REDIS_BLOCKED 32 /* The client is waiting in a blocking operation */
174 /* Slave replication state - slave side */
175 #define REDIS_REPL_NONE 0 /* No active replication */
176 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
177 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
179 /* Slave replication state - from the point of view of master
180 * Note that in SEND_BULK and ONLINE state the slave receives new updates
181 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
182 * to start the next background saving in order to send updates to it. */
183 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
184 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
185 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
186 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
188 /* List related stuff */
192 /* Sort operations */
193 #define REDIS_SORT_GET 0
194 #define REDIS_SORT_ASC 1
195 #define REDIS_SORT_DESC 2
196 #define REDIS_SORTKEY_MAX 1024
199 #define REDIS_DEBUG 0
200 #define REDIS_NOTICE 1
201 #define REDIS_WARNING 2
203 /* Anti-warning macro... */
204 #define REDIS_NOTUSED(V) ((void) V)
206 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
207 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
209 /* Append only defines */
210 #define APPENDFSYNC_NO 0
211 #define APPENDFSYNC_ALWAYS 1
212 #define APPENDFSYNC_EVERYSEC 2
214 /* We can print the stacktrace, so our assert is defined this way: */
215 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e),exit(1)))
216 static void _redisAssert(char *estr
);
218 /*================================= Data types ============================== */
220 /* A redis object, that is a type able to hold a string / list / set */
222 /* The VM object structure */
223 struct redisObjectVM
{
224 off_t page
; /* the page at witch the object is stored on disk */
225 off_t usedpages
; /* number of pages used on disk */
226 time_t atime
; /* Last access time */
229 /* The actual Redis Object */
230 typedef struct redisObject
{
233 unsigned char encoding
;
234 unsigned char storage
; /* If this object is a key, where is the value?
235 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
236 unsigned char vtype
; /* If this object is a key, and value is swapped out,
237 * this is the type of the swapped out object. */
239 /* VM fields, this are only allocated if VM is active, otherwise the
240 * object allocation function will just allocate
241 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
242 * Redis without VM active will not have any overhead. */
243 struct redisObjectVM vm
;
246 /* Macro used to initalize a Redis object allocated on the stack.
247 * Note that this macro is taken near the structure definition to make sure
248 * we'll update it when the structure is changed, to avoid bugs like
249 * bug #85 introduced exactly in this way. */
250 #define initStaticStringObject(_var,_ptr) do { \
252 _var.type = REDIS_STRING; \
253 _var.encoding = REDIS_ENCODING_RAW; \
255 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
258 typedef struct redisDb
{
259 dict
*dict
; /* The keyspace for this DB */
260 dict
*expires
; /* Timeout of keys with a timeout set */
261 dict
*blockingkeys
; /* Keys with clients waiting for data (BLPOP) */
265 /* Client MULTI/EXEC state */
266 typedef struct multiCmd
{
269 struct redisCommand
*cmd
;
272 typedef struct multiState
{
273 multiCmd
*commands
; /* Array of MULTI commands */
274 int count
; /* Total number of MULTI commands */
277 /* With multiplexing we need to take per-clinet state.
278 * Clients are taken in a liked list. */
279 typedef struct redisClient
{
284 robj
**argv
, **mbargv
;
286 int bulklen
; /* bulk read len. -1 if not in bulk read mode */
287 int multibulk
; /* multi bulk command format active */
290 time_t lastinteraction
; /* time of the last interaction, used for timeout */
291 int flags
; /* REDIS_CLOSE | REDIS_SLAVE | REDIS_MONITOR */
293 int slaveseldb
; /* slave selected db, if this client is a slave */
294 int authenticated
; /* when requirepass is non-NULL */
295 int replstate
; /* replication state if this is a slave */
296 int repldbfd
; /* replication DB file descriptor */
297 long repldboff
; /* replication DB file offset */
298 off_t repldbsize
; /* replication DB file size */
299 multiState mstate
; /* MULTI/EXEC state */
300 robj
**blockingkeys
; /* The key we waiting to terminate a blocking
301 * operation such as BLPOP. Otherwise NULL. */
302 int blockingkeysnum
; /* Number of blocking keys */
303 time_t blockingto
; /* Blocking operation timeout. If UNIX current time
304 * is >= blockingto then the operation timed out. */
312 /* Global server state structure */
317 dict
*sharingpool
; /* Poll used for object sharing */
318 unsigned int sharingpoolsize
;
319 long long dirty
; /* changes to DB from the last save */
321 list
*slaves
, *monitors
;
322 char neterr
[ANET_ERR_LEN
];
324 int cronloops
; /* number of times the cron function run */
325 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
326 time_t lastsave
; /* Unix time of last save succeeede */
327 size_t usedmemory
; /* Used memory in megabytes */
328 /* Fields used only for stats */
329 time_t stat_starttime
; /* server start time */
330 long long stat_numcommands
; /* number of processed commands */
331 long long stat_numconnections
; /* number of connections received */
344 pid_t bgsavechildpid
;
345 pid_t bgrewritechildpid
;
346 sds bgrewritebuf
; /* buffer taken by parent during oppend only rewrite */
347 struct saveparam
*saveparams
;
352 char *appendfilename
;
356 /* Replication related */
361 redisClient
*master
; /* client that is master for this slave */
363 unsigned int maxclients
;
364 unsigned long long maxmemory
;
365 unsigned int blockedclients
;
366 /* Sort parameters - qsort_r() is only available under BSD so we
367 * have to take this state global, in order to pass it to sortCompare() */
371 /* Virtual memory configuration */
375 unsigned long long vm_max_memory
;
376 /* Virtual memory state */
379 off_t vm_next_page
; /* Next probably empty page */
380 off_t vm_near_pages
; /* Number of pages allocated sequentially */
381 unsigned char *vm_bitmap
; /* Bitmap of free/used pages */
382 time_t unixtime
; /* Unix time sampled every second. */
385 typedef void redisCommandProc(redisClient
*c
);
386 struct redisCommand
{
388 redisCommandProc
*proc
;
393 struct redisFunctionSym
{
395 unsigned long pointer
;
398 typedef struct _redisSortObject
{
406 typedef struct _redisSortOperation
{
409 } redisSortOperation
;
411 /* ZSETs use a specialized version of Skiplists */
413 typedef struct zskiplistNode
{
414 struct zskiplistNode
**forward
;
415 struct zskiplistNode
*backward
;
420 typedef struct zskiplist
{
421 struct zskiplistNode
*header
, *tail
;
422 unsigned long length
;
426 typedef struct zset
{
431 /* Our shared "common" objects */
433 struct sharedObjectsStruct
{
434 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
435 *colon
, *nullbulk
, *nullmultibulk
, *queued
,
436 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
437 *outofrangeerr
, *plus
,
438 *select0
, *select1
, *select2
, *select3
, *select4
,
439 *select5
, *select6
, *select7
, *select8
, *select9
;
442 /* Global vars that are actally used as constants. The following double
443 * values are used for double on-disk serialization, and are initialized
444 * at runtime to avoid strange compiler optimizations. */
446 static double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
448 /*================================ Prototypes =============================== */
450 static void freeStringObject(robj
*o
);
451 static void freeListObject(robj
*o
);
452 static void freeSetObject(robj
*o
);
453 static void decrRefCount(void *o
);
454 static robj
*createObject(int type
, void *ptr
);
455 static void freeClient(redisClient
*c
);
456 static int rdbLoad(char *filename
);
457 static void addReply(redisClient
*c
, robj
*obj
);
458 static void addReplySds(redisClient
*c
, sds s
);
459 static void incrRefCount(robj
*o
);
460 static int rdbSaveBackground(char *filename
);
461 static robj
*createStringObject(char *ptr
, size_t len
);
462 static robj
*dupStringObject(robj
*o
);
463 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
464 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
465 static int syncWithMaster(void);
466 static robj
*tryObjectSharing(robj
*o
);
467 static int tryObjectEncoding(robj
*o
);
468 static robj
*getDecodedObject(robj
*o
);
469 static int removeExpire(redisDb
*db
, robj
*key
);
470 static int expireIfNeeded(redisDb
*db
, robj
*key
);
471 static int deleteIfVolatile(redisDb
*db
, robj
*key
);
472 static int deleteKey(redisDb
*db
, robj
*key
);
473 static time_t getExpire(redisDb
*db
, robj
*key
);
474 static int setExpire(redisDb
*db
, robj
*key
, time_t when
);
475 static void updateSlavesWaitingBgsave(int bgsaveerr
);
476 static void freeMemoryIfNeeded(void);
477 static int processCommand(redisClient
*c
);
478 static void setupSigSegvAction(void);
479 static void rdbRemoveTempFile(pid_t childpid
);
480 static void aofRemoveTempFile(pid_t childpid
);
481 static size_t stringObjectLen(robj
*o
);
482 static void processInputBuffer(redisClient
*c
);
483 static zskiplist
*zslCreate(void);
484 static void zslFree(zskiplist
*zsl
);
485 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
);
486 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
487 static void initClientMultiState(redisClient
*c
);
488 static void freeClientMultiState(redisClient
*c
);
489 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
);
490 static void unblockClient(redisClient
*c
);
491 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
);
492 static void vmInit(void);
493 static void vmMarkPagesFree(off_t page
, off_t count
);
494 static robj
*vmLoadObject(robj
*key
);
495 static int vmSwapOneObject(void);
497 static void authCommand(redisClient
*c
);
498 static void pingCommand(redisClient
*c
);
499 static void echoCommand(redisClient
*c
);
500 static void setCommand(redisClient
*c
);
501 static void setnxCommand(redisClient
*c
);
502 static void getCommand(redisClient
*c
);
503 static void delCommand(redisClient
*c
);
504 static void existsCommand(redisClient
*c
);
505 static void incrCommand(redisClient
*c
);
506 static void decrCommand(redisClient
*c
);
507 static void incrbyCommand(redisClient
*c
);
508 static void decrbyCommand(redisClient
*c
);
509 static void selectCommand(redisClient
*c
);
510 static void randomkeyCommand(redisClient
*c
);
511 static void keysCommand(redisClient
*c
);
512 static void dbsizeCommand(redisClient
*c
);
513 static void lastsaveCommand(redisClient
*c
);
514 static void saveCommand(redisClient
*c
);
515 static void bgsaveCommand(redisClient
*c
);
516 static void bgrewriteaofCommand(redisClient
*c
);
517 static void shutdownCommand(redisClient
*c
);
518 static void moveCommand(redisClient
*c
);
519 static void renameCommand(redisClient
*c
);
520 static void renamenxCommand(redisClient
*c
);
521 static void lpushCommand(redisClient
*c
);
522 static void rpushCommand(redisClient
*c
);
523 static void lpopCommand(redisClient
*c
);
524 static void rpopCommand(redisClient
*c
);
525 static void llenCommand(redisClient
*c
);
526 static void lindexCommand(redisClient
*c
);
527 static void lrangeCommand(redisClient
*c
);
528 static void ltrimCommand(redisClient
*c
);
529 static void typeCommand(redisClient
*c
);
530 static void lsetCommand(redisClient
*c
);
531 static void saddCommand(redisClient
*c
);
532 static void sremCommand(redisClient
*c
);
533 static void smoveCommand(redisClient
*c
);
534 static void sismemberCommand(redisClient
*c
);
535 static void scardCommand(redisClient
*c
);
536 static void spopCommand(redisClient
*c
);
537 static void srandmemberCommand(redisClient
*c
);
538 static void sinterCommand(redisClient
*c
);
539 static void sinterstoreCommand(redisClient
*c
);
540 static void sunionCommand(redisClient
*c
);
541 static void sunionstoreCommand(redisClient
*c
);
542 static void sdiffCommand(redisClient
*c
);
543 static void sdiffstoreCommand(redisClient
*c
);
544 static void syncCommand(redisClient
*c
);
545 static void flushdbCommand(redisClient
*c
);
546 static void flushallCommand(redisClient
*c
);
547 static void sortCommand(redisClient
*c
);
548 static void lremCommand(redisClient
*c
);
549 static void rpoplpushcommand(redisClient
*c
);
550 static void infoCommand(redisClient
*c
);
551 static void mgetCommand(redisClient
*c
);
552 static void monitorCommand(redisClient
*c
);
553 static void expireCommand(redisClient
*c
);
554 static void expireatCommand(redisClient
*c
);
555 static void getsetCommand(redisClient
*c
);
556 static void ttlCommand(redisClient
*c
);
557 static void slaveofCommand(redisClient
*c
);
558 static void debugCommand(redisClient
*c
);
559 static void msetCommand(redisClient
*c
);
560 static void msetnxCommand(redisClient
*c
);
561 static void zaddCommand(redisClient
*c
);
562 static void zincrbyCommand(redisClient
*c
);
563 static void zrangeCommand(redisClient
*c
);
564 static void zrangebyscoreCommand(redisClient
*c
);
565 static void zrevrangeCommand(redisClient
*c
);
566 static void zcardCommand(redisClient
*c
);
567 static void zremCommand(redisClient
*c
);
568 static void zscoreCommand(redisClient
*c
);
569 static void zremrangebyscoreCommand(redisClient
*c
);
570 static void multiCommand(redisClient
*c
);
571 static void execCommand(redisClient
*c
);
572 static void blpopCommand(redisClient
*c
);
573 static void brpopCommand(redisClient
*c
);
575 /*================================= Globals ================================= */
578 static struct redisServer server
; /* server global state */
579 static struct redisCommand cmdTable
[] = {
580 {"get",getCommand
,2,REDIS_CMD_INLINE
},
581 {"set",setCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
582 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
583 {"del",delCommand
,-2,REDIS_CMD_INLINE
},
584 {"exists",existsCommand
,2,REDIS_CMD_INLINE
},
585 {"incr",incrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
586 {"decr",decrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
587 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
},
588 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
589 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
590 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
},
591 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
},
592 {"brpop",brpopCommand
,-3,REDIS_CMD_INLINE
},
593 {"blpop",blpopCommand
,-3,REDIS_CMD_INLINE
},
594 {"llen",llenCommand
,2,REDIS_CMD_INLINE
},
595 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
},
596 {"lset",lsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
597 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
},
598 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
},
599 {"lrem",lremCommand
,4,REDIS_CMD_BULK
},
600 {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
601 {"sadd",saddCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
602 {"srem",sremCommand
,3,REDIS_CMD_BULK
},
603 {"smove",smoveCommand
,4,REDIS_CMD_BULK
},
604 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
},
605 {"scard",scardCommand
,2,REDIS_CMD_INLINE
},
606 {"spop",spopCommand
,2,REDIS_CMD_INLINE
},
607 {"srandmember",srandmemberCommand
,2,REDIS_CMD_INLINE
},
608 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
609 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
610 {"sunion",sunionCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
611 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
612 {"sdiff",sdiffCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
613 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
614 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
},
615 {"zadd",zaddCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
616 {"zincrby",zincrbyCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
617 {"zrem",zremCommand
,3,REDIS_CMD_BULK
},
618 {"zremrangebyscore",zremrangebyscoreCommand
,4,REDIS_CMD_INLINE
},
619 {"zrange",zrangeCommand
,-4,REDIS_CMD_INLINE
},
620 {"zrangebyscore",zrangebyscoreCommand
,-4,REDIS_CMD_INLINE
},
621 {"zrevrange",zrevrangeCommand
,-4,REDIS_CMD_INLINE
},
622 {"zcard",zcardCommand
,2,REDIS_CMD_INLINE
},
623 {"zscore",zscoreCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
624 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
625 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
626 {"getset",getsetCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
627 {"mset",msetCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
628 {"msetnx",msetnxCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
629 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
},
630 {"select",selectCommand
,2,REDIS_CMD_INLINE
},
631 {"move",moveCommand
,3,REDIS_CMD_INLINE
},
632 {"rename",renameCommand
,3,REDIS_CMD_INLINE
},
633 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
},
634 {"expire",expireCommand
,3,REDIS_CMD_INLINE
},
635 {"expireat",expireatCommand
,3,REDIS_CMD_INLINE
},
636 {"keys",keysCommand
,2,REDIS_CMD_INLINE
},
637 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
},
638 {"auth",authCommand
,2,REDIS_CMD_INLINE
},
639 {"ping",pingCommand
,1,REDIS_CMD_INLINE
},
640 {"echo",echoCommand
,2,REDIS_CMD_BULK
},
641 {"save",saveCommand
,1,REDIS_CMD_INLINE
},
642 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
},
643 {"bgrewriteaof",bgrewriteaofCommand
,1,REDIS_CMD_INLINE
},
644 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
},
645 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
},
646 {"type",typeCommand
,2,REDIS_CMD_INLINE
},
647 {"multi",multiCommand
,1,REDIS_CMD_INLINE
},
648 {"exec",execCommand
,1,REDIS_CMD_INLINE
},
649 {"sync",syncCommand
,1,REDIS_CMD_INLINE
},
650 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
},
651 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
},
652 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
653 {"info",infoCommand
,1,REDIS_CMD_INLINE
},
654 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
},
655 {"ttl",ttlCommand
,2,REDIS_CMD_INLINE
},
656 {"slaveof",slaveofCommand
,3,REDIS_CMD_INLINE
},
657 {"debug",debugCommand
,-2,REDIS_CMD_INLINE
},
661 /*============================ Utility functions ============================ */
663 /* Glob-style pattern matching. */
664 int stringmatchlen(const char *pattern
, int patternLen
,
665 const char *string
, int stringLen
, int nocase
)
670 while (pattern
[1] == '*') {
675 return 1; /* match */
677 if (stringmatchlen(pattern
+1, patternLen
-1,
678 string
, stringLen
, nocase
))
679 return 1; /* match */
683 return 0; /* no match */
687 return 0; /* no match */
697 not = pattern
[0] == '^';
704 if (pattern
[0] == '\\') {
707 if (pattern
[0] == string
[0])
709 } else if (pattern
[0] == ']') {
711 } else if (patternLen
== 0) {
715 } else if (pattern
[1] == '-' && patternLen
>= 3) {
716 int start
= pattern
[0];
717 int end
= pattern
[2];
725 start
= tolower(start
);
731 if (c
>= start
&& c
<= end
)
735 if (pattern
[0] == string
[0])
738 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
748 return 0; /* no match */
754 if (patternLen
>= 2) {
761 if (pattern
[0] != string
[0])
762 return 0; /* no match */
764 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
765 return 0; /* no match */
773 if (stringLen
== 0) {
774 while(*pattern
== '*') {
781 if (patternLen
== 0 && stringLen
== 0)
786 static void redisLog(int level
, const char *fmt
, ...) {
790 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
794 if (level
>= server
.verbosity
) {
800 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
801 fprintf(fp
,"%s %c ",buf
,c
[level
]);
802 vfprintf(fp
, fmt
, ap
);
808 if (server
.logfile
) fclose(fp
);
811 /*====================== Hash table type implementation ==================== */
813 /* This is an hash table type that uses the SDS dynamic strings libary as
814 * keys and radis objects as values (objects can hold SDS strings,
817 static void dictVanillaFree(void *privdata
, void *val
)
819 DICT_NOTUSED(privdata
);
823 static void dictListDestructor(void *privdata
, void *val
)
825 DICT_NOTUSED(privdata
);
826 listRelease((list
*)val
);
829 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
833 DICT_NOTUSED(privdata
);
835 l1
= sdslen((sds
)key1
);
836 l2
= sdslen((sds
)key2
);
837 if (l1
!= l2
) return 0;
838 return memcmp(key1
, key2
, l1
) == 0;
841 static void dictRedisObjectDestructor(void *privdata
, void *val
)
843 DICT_NOTUSED(privdata
);
845 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
849 static int dictObjKeyCompare(void *privdata
, const void *key1
,
852 const robj
*o1
= key1
, *o2
= key2
;
853 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
856 static unsigned int dictObjHash(const void *key
) {
858 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
861 static int dictEncObjKeyCompare(void *privdata
, const void *key1
,
864 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
867 o1
= getDecodedObject(o1
);
868 o2
= getDecodedObject(o2
);
869 cmp
= sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
875 static unsigned int dictEncObjHash(const void *key
) {
876 robj
*o
= (robj
*) key
;
878 o
= getDecodedObject(o
);
879 unsigned int hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
884 static dictType setDictType
= {
885 dictEncObjHash
, /* hash function */
888 dictEncObjKeyCompare
, /* key compare */
889 dictRedisObjectDestructor
, /* key destructor */
890 NULL
/* val destructor */
893 static dictType zsetDictType
= {
894 dictEncObjHash
, /* hash function */
897 dictEncObjKeyCompare
, /* key compare */
898 dictRedisObjectDestructor
, /* key destructor */
899 dictVanillaFree
/* val destructor of malloc(sizeof(double)) */
902 static dictType hashDictType
= {
903 dictObjHash
, /* hash function */
906 dictObjKeyCompare
, /* key compare */
907 dictRedisObjectDestructor
, /* key destructor */
908 dictRedisObjectDestructor
/* val destructor */
911 /* Keylist hash table type has unencoded redis objects as keys and
912 * lists as values. It's used for blocking operations (BLPOP) */
913 static dictType keylistDictType
= {
914 dictObjHash
, /* hash function */
917 dictObjKeyCompare
, /* key compare */
918 dictRedisObjectDestructor
, /* key destructor */
919 dictListDestructor
/* val destructor */
922 /* ========================= Random utility functions ======================= */
924 /* Redis generally does not try to recover from out of memory conditions
925 * when allocating objects or strings, it is not clear if it will be possible
926 * to report this condition to the client since the networking layer itself
927 * is based on heap allocation for send buffers, so we simply abort.
928 * At least the code will be simpler to read... */
929 static void oom(const char *msg
) {
930 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
935 /* ====================== Redis server networking stuff ===================== */
936 static void closeTimedoutClients(void) {
939 time_t now
= time(NULL
);
941 listRewind(server
.clients
);
942 while ((ln
= listYield(server
.clients
)) != NULL
) {
943 c
= listNodeValue(ln
);
944 if (server
.maxidletime
&&
945 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
946 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
947 (now
- c
->lastinteraction
> server
.maxidletime
))
949 redisLog(REDIS_DEBUG
,"Closing idle client");
951 } else if (c
->flags
& REDIS_BLOCKED
) {
952 if (c
->blockingto
!= 0 && c
->blockingto
< now
) {
953 addReply(c
,shared
.nullmultibulk
);
960 static int htNeedsResize(dict
*dict
) {
961 long long size
, used
;
963 size
= dictSlots(dict
);
964 used
= dictSize(dict
);
965 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
966 (used
*100/size
< REDIS_HT_MINFILL
));
969 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
970 * we resize the hash table to save memory */
971 static void tryResizeHashTables(void) {
974 for (j
= 0; j
< server
.dbnum
; j
++) {
975 if (htNeedsResize(server
.db
[j
].dict
)) {
976 redisLog(REDIS_DEBUG
,"The hash table %d is too sparse, resize it...",j
);
977 dictResize(server
.db
[j
].dict
);
978 redisLog(REDIS_DEBUG
,"Hash table %d resized.",j
);
980 if (htNeedsResize(server
.db
[j
].expires
))
981 dictResize(server
.db
[j
].expires
);
985 /* A background saving child (BGSAVE) terminated its work. Handle this. */
986 void backgroundSaveDoneHandler(int statloc
) {
987 int exitcode
= WEXITSTATUS(statloc
);
988 int bysignal
= WIFSIGNALED(statloc
);
990 if (!bysignal
&& exitcode
== 0) {
991 redisLog(REDIS_NOTICE
,
992 "Background saving terminated with success");
994 server
.lastsave
= time(NULL
);
995 } else if (!bysignal
&& exitcode
!= 0) {
996 redisLog(REDIS_WARNING
, "Background saving error");
998 redisLog(REDIS_WARNING
,
999 "Background saving terminated by signal");
1000 rdbRemoveTempFile(server
.bgsavechildpid
);
1002 server
.bgsavechildpid
= -1;
1003 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1004 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1005 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);
1008 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1010 void backgroundRewriteDoneHandler(int statloc
) {
1011 int exitcode
= WEXITSTATUS(statloc
);
1012 int bysignal
= WIFSIGNALED(statloc
);
1014 if (!bysignal
&& exitcode
== 0) {
1018 redisLog(REDIS_NOTICE
,
1019 "Background append only file rewriting terminated with success");
1020 /* Now it's time to flush the differences accumulated by the parent */
1021 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) server
.bgrewritechildpid
);
1022 fd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
1024 redisLog(REDIS_WARNING
, "Not able to open the temp append only file produced by the child: %s", strerror(errno
));
1027 /* Flush our data... */
1028 if (write(fd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
)) !=
1029 (signed) sdslen(server
.bgrewritebuf
)) {
1030 redisLog(REDIS_WARNING
, "Error or short write trying to flush the parent diff of the append log file in the child temp file: %s", strerror(errno
));
1034 redisLog(REDIS_NOTICE
,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server
.bgrewritebuf
));
1035 /* Now our work is to rename the temp file into the stable file. And
1036 * switch the file descriptor used by the server for append only. */
1037 if (rename(tmpfile
,server
.appendfilename
) == -1) {
1038 redisLog(REDIS_WARNING
,"Can't rename the temp append only file into the stable one: %s", strerror(errno
));
1042 /* Mission completed... almost */
1043 redisLog(REDIS_NOTICE
,"Append only file successfully rewritten.");
1044 if (server
.appendfd
!= -1) {
1045 /* If append only is actually enabled... */
1046 close(server
.appendfd
);
1047 server
.appendfd
= fd
;
1049 server
.appendseldb
= -1; /* Make sure it will issue SELECT */
1050 redisLog(REDIS_NOTICE
,"The new append only file was selected for future appends.");
1052 /* If append only is disabled we just generate a dump in this
1053 * format. Why not? */
1056 } else if (!bysignal
&& exitcode
!= 0) {
1057 redisLog(REDIS_WARNING
, "Background append only file rewriting error");
1059 redisLog(REDIS_WARNING
,
1060 "Background append only file rewriting terminated by signal");
1063 sdsfree(server
.bgrewritebuf
);
1064 server
.bgrewritebuf
= sdsempty();
1065 aofRemoveTempFile(server
.bgrewritechildpid
);
1066 server
.bgrewritechildpid
= -1;
1069 static int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
1070 int j
, loops
= server
.cronloops
++;
1071 REDIS_NOTUSED(eventLoop
);
1073 REDIS_NOTUSED(clientData
);
1075 /* We take a cached value of the unix time in the global state because
1076 * with virtual memory and aging there is to store the current time
1077 * in objects at every object access, and accuracy is not needed.
1078 * To access a global var is faster than calling time(NULL) */
1079 server
.unixtime
= time(NULL
);
1081 /* Update the global state with the amount of used memory */
1082 server
.usedmemory
= zmalloc_used_memory();
1084 /* Show some info about non-empty databases */
1085 for (j
= 0; j
< server
.dbnum
; j
++) {
1086 long long size
, used
, vkeys
;
1088 size
= dictSlots(server
.db
[j
].dict
);
1089 used
= dictSize(server
.db
[j
].dict
);
1090 vkeys
= dictSize(server
.db
[j
].expires
);
1091 if (!(loops
% 5) && (used
|| vkeys
)) {
1092 redisLog(REDIS_DEBUG
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
1093 /* dictPrintStats(server.dict); */
1097 /* We don't want to resize the hash tables while a bacground saving
1098 * is in progress: the saving child is created using fork() that is
1099 * implemented with a copy-on-write semantic in most modern systems, so
1100 * if we resize the HT while there is the saving child at work actually
1101 * a lot of memory movements in the parent will cause a lot of pages
1103 if (server
.bgsavechildpid
== -1) tryResizeHashTables();
1105 /* Show information about connected clients */
1107 redisLog(REDIS_DEBUG
,"%d clients connected (%d slaves), %zu bytes in use, %d shared objects",
1108 listLength(server
.clients
)-listLength(server
.slaves
),
1109 listLength(server
.slaves
),
1111 dictSize(server
.sharingpool
));
1114 /* Close connections of timedout clients */
1115 if ((server
.maxidletime
&& !(loops
% 10)) || server
.blockedclients
)
1116 closeTimedoutClients();
1118 /* Check if a background saving or AOF rewrite in progress terminated */
1119 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
1123 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
1124 if (pid
== server
.bgsavechildpid
) {
1125 backgroundSaveDoneHandler(statloc
);
1127 backgroundRewriteDoneHandler(statloc
);
1131 /* If there is not a background saving in progress check if
1132 * we have to save now */
1133 time_t now
= time(NULL
);
1134 for (j
= 0; j
< server
.saveparamslen
; j
++) {
1135 struct saveparam
*sp
= server
.saveparams
+j
;
1137 if (server
.dirty
>= sp
->changes
&&
1138 now
-server
.lastsave
> sp
->seconds
) {
1139 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
1140 sp
->changes
, sp
->seconds
);
1141 rdbSaveBackground(server
.dbfilename
);
1147 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1148 * will use few CPU cycles if there are few expiring keys, otherwise
1149 * it will get more aggressive to avoid that too much memory is used by
1150 * keys that can be removed from the keyspace. */
1151 for (j
= 0; j
< server
.dbnum
; j
++) {
1153 redisDb
*db
= server
.db
+j
;
1155 /* Continue to expire if at the end of the cycle more than 25%
1156 * of the keys were expired. */
1158 long num
= dictSize(db
->expires
);
1159 time_t now
= time(NULL
);
1162 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
1163 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
1168 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
1169 t
= (time_t) dictGetEntryVal(de
);
1171 deleteKey(db
,dictGetEntryKey(de
));
1175 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
1178 /* Swap a few keys on disk if we are over the memory limit and VM
1180 while (server
.vm_enabled
&& zmalloc_used_memory() > server
.vm_max_memory
) {
1181 if (vmSwapOneObject() == REDIS_ERR
) {
1182 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit reached but unable to swap more objects out!");
1187 /* Check if we should connect to a MASTER */
1188 if (server
.replstate
== REDIS_REPL_CONNECT
) {
1189 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
1190 if (syncWithMaster() == REDIS_OK
) {
1191 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
1197 static void createSharedObjects(void) {
1198 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
1199 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
1200 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
1201 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
1202 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
1203 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
1204 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
1205 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
1206 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
1207 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
1208 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
1209 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
1210 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1211 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
1212 "-ERR no such key\r\n"));
1213 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
1214 "-ERR syntax error\r\n"));
1215 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
1216 "-ERR source and destination objects are the same\r\n"));
1217 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
1218 "-ERR index out of range\r\n"));
1219 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
1220 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
1221 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
1222 shared
.select0
= createStringObject("select 0\r\n",10);
1223 shared
.select1
= createStringObject("select 1\r\n",10);
1224 shared
.select2
= createStringObject("select 2\r\n",10);
1225 shared
.select3
= createStringObject("select 3\r\n",10);
1226 shared
.select4
= createStringObject("select 4\r\n",10);
1227 shared
.select5
= createStringObject("select 5\r\n",10);
1228 shared
.select6
= createStringObject("select 6\r\n",10);
1229 shared
.select7
= createStringObject("select 7\r\n",10);
1230 shared
.select8
= createStringObject("select 8\r\n",10);
1231 shared
.select9
= createStringObject("select 9\r\n",10);
1234 static void appendServerSaveParams(time_t seconds
, int changes
) {
1235 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
1236 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
1237 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
1238 server
.saveparamslen
++;
1241 static void resetServerSaveParams() {
1242 zfree(server
.saveparams
);
1243 server
.saveparams
= NULL
;
1244 server
.saveparamslen
= 0;
1247 static void initServerConfig() {
1248 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
1249 server
.port
= REDIS_SERVERPORT
;
1250 server
.verbosity
= REDIS_DEBUG
;
1251 server
.maxidletime
= REDIS_MAXIDLETIME
;
1252 server
.saveparams
= NULL
;
1253 server
.logfile
= NULL
; /* NULL = log on standard output */
1254 server
.bindaddr
= NULL
;
1255 server
.glueoutputbuf
= 1;
1256 server
.daemonize
= 0;
1257 server
.appendonly
= 0;
1258 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1259 server
.lastfsync
= time(NULL
);
1260 server
.appendfd
= -1;
1261 server
.appendseldb
= -1; /* Make sure the first time will not match */
1262 server
.pidfile
= "/var/run/redis.pid";
1263 server
.dbfilename
= "dump.rdb";
1264 server
.appendfilename
= "appendonly.aof";
1265 server
.requirepass
= NULL
;
1266 server
.shareobjects
= 0;
1267 server
.rdbcompression
= 1;
1268 server
.sharingpoolsize
= 1024;
1269 server
.maxclients
= 0;
1270 server
.blockedclients
= 0;
1271 server
.maxmemory
= 0;
1272 server
.vm_enabled
= 0;
1273 server
.vm_page_size
= 256; /* 256 bytes per page */
1274 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
1275 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
1277 resetServerSaveParams();
1279 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1280 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1281 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1282 /* Replication related */
1284 server
.masterauth
= NULL
;
1285 server
.masterhost
= NULL
;
1286 server
.masterport
= 6379;
1287 server
.master
= NULL
;
1288 server
.replstate
= REDIS_REPL_NONE
;
1290 /* Double constants initialization */
1292 R_PosInf
= 1.0/R_Zero
;
1293 R_NegInf
= -1.0/R_Zero
;
1294 R_Nan
= R_Zero
/R_Zero
;
1297 static void initServer() {
1300 signal(SIGHUP
, SIG_IGN
);
1301 signal(SIGPIPE
, SIG_IGN
);
1302 setupSigSegvAction();
1304 server
.clients
= listCreate();
1305 server
.slaves
= listCreate();
1306 server
.monitors
= listCreate();
1307 server
.objfreelist
= listCreate();
1308 createSharedObjects();
1309 server
.el
= aeCreateEventLoop();
1310 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
1311 server
.sharingpool
= dictCreate(&setDictType
,NULL
);
1312 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
1313 if (server
.fd
== -1) {
1314 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
1317 for (j
= 0; j
< server
.dbnum
; j
++) {
1318 server
.db
[j
].dict
= dictCreate(&hashDictType
,NULL
);
1319 server
.db
[j
].expires
= dictCreate(&setDictType
,NULL
);
1320 server
.db
[j
].blockingkeys
= dictCreate(&keylistDictType
,NULL
);
1321 server
.db
[j
].id
= j
;
1323 server
.cronloops
= 0;
1324 server
.bgsavechildpid
= -1;
1325 server
.bgrewritechildpid
= -1;
1326 server
.bgrewritebuf
= sdsempty();
1327 server
.lastsave
= time(NULL
);
1329 server
.usedmemory
= 0;
1330 server
.stat_numcommands
= 0;
1331 server
.stat_numconnections
= 0;
1332 server
.stat_starttime
= time(NULL
);
1333 server
.unixtime
= time(NULL
);
1334 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
1336 if (server
.appendonly
) {
1337 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1338 if (server
.appendfd
== -1) {
1339 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1345 if (server
.vm_enabled
) vmInit();
1348 /* Empty the whole database */
1349 static long long emptyDb() {
1351 long long removed
= 0;
1353 for (j
= 0; j
< server
.dbnum
; j
++) {
1354 removed
+= dictSize(server
.db
[j
].dict
);
1355 dictEmpty(server
.db
[j
].dict
);
1356 dictEmpty(server
.db
[j
].expires
);
1361 static int yesnotoi(char *s
) {
1362 if (!strcasecmp(s
,"yes")) return 1;
1363 else if (!strcasecmp(s
,"no")) return 0;
1367 /* I agree, this is a very rudimental way to load a configuration...
1368 will improve later if the config gets more complex */
1369 static void loadServerConfig(char *filename
) {
1371 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
1375 if (filename
[0] == '-' && filename
[1] == '\0')
1378 if ((fp
= fopen(filename
,"r")) == NULL
) {
1379 redisLog(REDIS_WARNING
,"Fatal error, can't open config file");
1384 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
1390 line
= sdstrim(line
," \t\r\n");
1392 /* Skip comments and blank lines*/
1393 if (line
[0] == '#' || line
[0] == '\0') {
1398 /* Split into arguments */
1399 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
1400 sdstolower(argv
[0]);
1402 /* Execute config directives */
1403 if (!strcasecmp(argv
[0],"timeout") && argc
== 2) {
1404 server
.maxidletime
= atoi(argv
[1]);
1405 if (server
.maxidletime
< 0) {
1406 err
= "Invalid timeout value"; goto loaderr
;
1408 } else if (!strcasecmp(argv
[0],"port") && argc
== 2) {
1409 server
.port
= atoi(argv
[1]);
1410 if (server
.port
< 1 || server
.port
> 65535) {
1411 err
= "Invalid port"; goto loaderr
;
1413 } else if (!strcasecmp(argv
[0],"bind") && argc
== 2) {
1414 server
.bindaddr
= zstrdup(argv
[1]);
1415 } else if (!strcasecmp(argv
[0],"save") && argc
== 3) {
1416 int seconds
= atoi(argv
[1]);
1417 int changes
= atoi(argv
[2]);
1418 if (seconds
< 1 || changes
< 0) {
1419 err
= "Invalid save parameters"; goto loaderr
;
1421 appendServerSaveParams(seconds
,changes
);
1422 } else if (!strcasecmp(argv
[0],"dir") && argc
== 2) {
1423 if (chdir(argv
[1]) == -1) {
1424 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
1425 argv
[1], strerror(errno
));
1428 } else if (!strcasecmp(argv
[0],"loglevel") && argc
== 2) {
1429 if (!strcasecmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
1430 else if (!strcasecmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
1431 else if (!strcasecmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
1433 err
= "Invalid log level. Must be one of debug, notice, warning";
1436 } else if (!strcasecmp(argv
[0],"logfile") && argc
== 2) {
1439 server
.logfile
= zstrdup(argv
[1]);
1440 if (!strcasecmp(server
.logfile
,"stdout")) {
1441 zfree(server
.logfile
);
1442 server
.logfile
= NULL
;
1444 if (server
.logfile
) {
1445 /* Test if we are able to open the file. The server will not
1446 * be able to abort just for this problem later... */
1447 logfp
= fopen(server
.logfile
,"a");
1448 if (logfp
== NULL
) {
1449 err
= sdscatprintf(sdsempty(),
1450 "Can't open the log file: %s", strerror(errno
));
1455 } else if (!strcasecmp(argv
[0],"databases") && argc
== 2) {
1456 server
.dbnum
= atoi(argv
[1]);
1457 if (server
.dbnum
< 1) {
1458 err
= "Invalid number of databases"; goto loaderr
;
1460 } else if (!strcasecmp(argv
[0],"maxclients") && argc
== 2) {
1461 server
.maxclients
= atoi(argv
[1]);
1462 } else if (!strcasecmp(argv
[0],"maxmemory") && argc
== 2) {
1463 server
.maxmemory
= strtoll(argv
[1], NULL
, 10);
1464 } else if (!strcasecmp(argv
[0],"slaveof") && argc
== 3) {
1465 server
.masterhost
= sdsnew(argv
[1]);
1466 server
.masterport
= atoi(argv
[2]);
1467 server
.replstate
= REDIS_REPL_CONNECT
;
1468 } else if (!strcasecmp(argv
[0],"masterauth") && argc
== 2) {
1469 server
.masterauth
= zstrdup(argv
[1]);
1470 } else if (!strcasecmp(argv
[0],"glueoutputbuf") && argc
== 2) {
1471 if ((server
.glueoutputbuf
= yesnotoi(argv
[1])) == -1) {
1472 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1474 } else if (!strcasecmp(argv
[0],"shareobjects") && argc
== 2) {
1475 if ((server
.shareobjects
= yesnotoi(argv
[1])) == -1) {
1476 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1478 } else if (!strcasecmp(argv
[0],"rdbcompression") && argc
== 2) {
1479 if ((server
.rdbcompression
= yesnotoi(argv
[1])) == -1) {
1480 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1482 } else if (!strcasecmp(argv
[0],"shareobjectspoolsize") && argc
== 2) {
1483 server
.sharingpoolsize
= atoi(argv
[1]);
1484 if (server
.sharingpoolsize
< 1) {
1485 err
= "invalid object sharing pool size"; goto loaderr
;
1487 } else if (!strcasecmp(argv
[0],"daemonize") && argc
== 2) {
1488 if ((server
.daemonize
= yesnotoi(argv
[1])) == -1) {
1489 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1491 } else if (!strcasecmp(argv
[0],"appendonly") && argc
== 2) {
1492 if ((server
.appendonly
= yesnotoi(argv
[1])) == -1) {
1493 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1495 } else if (!strcasecmp(argv
[0],"appendfsync") && argc
== 2) {
1496 if (!strcasecmp(argv
[1],"no")) {
1497 server
.appendfsync
= APPENDFSYNC_NO
;
1498 } else if (!strcasecmp(argv
[1],"always")) {
1499 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1500 } else if (!strcasecmp(argv
[1],"everysec")) {
1501 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1503 err
= "argument must be 'no', 'always' or 'everysec'";
1506 } else if (!strcasecmp(argv
[0],"requirepass") && argc
== 2) {
1507 server
.requirepass
= zstrdup(argv
[1]);
1508 } else if (!strcasecmp(argv
[0],"pidfile") && argc
== 2) {
1509 server
.pidfile
= zstrdup(argv
[1]);
1510 } else if (!strcasecmp(argv
[0],"dbfilename") && argc
== 2) {
1511 server
.dbfilename
= zstrdup(argv
[1]);
1512 } else if (!strcasecmp(argv
[0],"vm-enabled") && argc
== 2) {
1513 if ((server
.vm_enabled
= yesnotoi(argv
[1])) == -1) {
1514 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1516 } else if (!strcasecmp(argv
[0],"vm-max-memory") && argc
== 2) {
1517 server
.vm_max_memory
= strtoll(argv
[1], NULL
, 10);
1518 } else if (!strcasecmp(argv
[0],"vm-page-size") && argc
== 2) {
1519 server
.vm_page_size
= strtoll(argv
[1], NULL
, 10);
1520 } else if (!strcasecmp(argv
[0],"vm-pages") && argc
== 2) {
1521 server
.vm_pages
= strtoll(argv
[1], NULL
, 10);
1523 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
1525 for (j
= 0; j
< argc
; j
++)
1530 if (fp
!= stdin
) fclose(fp
);
1534 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
1535 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
1536 fprintf(stderr
, ">>> '%s'\n", line
);
1537 fprintf(stderr
, "%s\n", err
);
1541 static void freeClientArgv(redisClient
*c
) {
1544 for (j
= 0; j
< c
->argc
; j
++)
1545 decrRefCount(c
->argv
[j
]);
1546 for (j
= 0; j
< c
->mbargc
; j
++)
1547 decrRefCount(c
->mbargv
[j
]);
1552 static void freeClient(redisClient
*c
) {
1555 /* Note that if the client we are freeing is blocked into a blocking
1556 * call, we have to set querybuf to NULL *before* to call unblockClient()
1557 * to avoid processInputBuffer() will get called. Also it is important
1558 * to remove the file events after this, because this call adds
1559 * the READABLE event. */
1560 sdsfree(c
->querybuf
);
1562 if (c
->flags
& REDIS_BLOCKED
)
1565 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
1566 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1567 listRelease(c
->reply
);
1570 ln
= listSearchKey(server
.clients
,c
);
1571 redisAssert(ln
!= NULL
);
1572 listDelNode(server
.clients
,ln
);
1573 if (c
->flags
& REDIS_SLAVE
) {
1574 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
1576 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
1577 ln
= listSearchKey(l
,c
);
1578 redisAssert(ln
!= NULL
);
1581 if (c
->flags
& REDIS_MASTER
) {
1582 server
.master
= NULL
;
1583 server
.replstate
= REDIS_REPL_CONNECT
;
1587 freeClientMultiState(c
);
1591 #define GLUEREPLY_UP_TO (1024)
1592 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
1594 char buf
[GLUEREPLY_UP_TO
];
1598 listRewind(c
->reply
);
1599 while((ln
= listYield(c
->reply
))) {
1603 objlen
= sdslen(o
->ptr
);
1604 if (copylen
+ objlen
<= GLUEREPLY_UP_TO
) {
1605 memcpy(buf
+copylen
,o
->ptr
,objlen
);
1607 listDelNode(c
->reply
,ln
);
1609 if (copylen
== 0) return;
1613 /* Now the output buffer is empty, add the new single element */
1614 o
= createObject(REDIS_STRING
,sdsnewlen(buf
,copylen
));
1615 listAddNodeHead(c
->reply
,o
);
1618 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1619 redisClient
*c
= privdata
;
1620 int nwritten
= 0, totwritten
= 0, objlen
;
1623 REDIS_NOTUSED(mask
);
1625 /* Use writev() if we have enough buffers to send */
1626 if (!server
.glueoutputbuf
&&
1627 listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD
&&
1628 !(c
->flags
& REDIS_MASTER
))
1630 sendReplyToClientWritev(el
, fd
, privdata
, mask
);
1634 while(listLength(c
->reply
)) {
1635 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
1636 glueReplyBuffersIfNeeded(c
);
1638 o
= listNodeValue(listFirst(c
->reply
));
1639 objlen
= sdslen(o
->ptr
);
1642 listDelNode(c
->reply
,listFirst(c
->reply
));
1646 if (c
->flags
& REDIS_MASTER
) {
1647 /* Don't reply to a master */
1648 nwritten
= objlen
- c
->sentlen
;
1650 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
1651 if (nwritten
<= 0) break;
1653 c
->sentlen
+= nwritten
;
1654 totwritten
+= nwritten
;
1655 /* If we fully sent the object on head go to the next one */
1656 if (c
->sentlen
== objlen
) {
1657 listDelNode(c
->reply
,listFirst(c
->reply
));
1660 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
1661 * bytes, in a single threaded server it's a good idea to serve
1662 * other clients as well, even if a very large request comes from
1663 * super fast link that is always able to accept data (in real world
1664 * scenario think about 'KEYS *' against the loopback interfae) */
1665 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
1667 if (nwritten
== -1) {
1668 if (errno
== EAGAIN
) {
1671 redisLog(REDIS_DEBUG
,
1672 "Error writing to client: %s", strerror(errno
));
1677 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
1678 if (listLength(c
->reply
) == 0) {
1680 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1684 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
)
1686 redisClient
*c
= privdata
;
1687 int nwritten
= 0, totwritten
= 0, objlen
, willwrite
;
1689 struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
];
1690 int offset
, ion
= 0;
1692 REDIS_NOTUSED(mask
);
1695 while (listLength(c
->reply
)) {
1696 offset
= c
->sentlen
;
1700 /* fill-in the iov[] array */
1701 for(node
= listFirst(c
->reply
); node
; node
= listNextNode(node
)) {
1702 o
= listNodeValue(node
);
1703 objlen
= sdslen(o
->ptr
);
1705 if (totwritten
+ objlen
- offset
> REDIS_MAX_WRITE_PER_EVENT
)
1708 if(ion
== REDIS_WRITEV_IOVEC_COUNT
)
1709 break; /* no more iovecs */
1711 iov
[ion
].iov_base
= ((char*)o
->ptr
) + offset
;
1712 iov
[ion
].iov_len
= objlen
- offset
;
1713 willwrite
+= objlen
- offset
;
1714 offset
= 0; /* just for the first item */
1721 /* write all collected blocks at once */
1722 if((nwritten
= writev(fd
, iov
, ion
)) < 0) {
1723 if (errno
!= EAGAIN
) {
1724 redisLog(REDIS_DEBUG
,
1725 "Error writing to client: %s", strerror(errno
));
1732 totwritten
+= nwritten
;
1733 offset
= c
->sentlen
;
1735 /* remove written robjs from c->reply */
1736 while (nwritten
&& listLength(c
->reply
)) {
1737 o
= listNodeValue(listFirst(c
->reply
));
1738 objlen
= sdslen(o
->ptr
);
1740 if(nwritten
>= objlen
- offset
) {
1741 listDelNode(c
->reply
, listFirst(c
->reply
));
1742 nwritten
-= objlen
- offset
;
1746 c
->sentlen
+= nwritten
;
1754 c
->lastinteraction
= time(NULL
);
1756 if (listLength(c
->reply
) == 0) {
1758 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1762 static struct redisCommand
*lookupCommand(char *name
) {
1764 while(cmdTable
[j
].name
!= NULL
) {
1765 if (!strcasecmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
1771 /* resetClient prepare the client to process the next command */
1772 static void resetClient(redisClient
*c
) {
1778 /* Call() is the core of Redis execution of a command */
1779 static void call(redisClient
*c
, struct redisCommand
*cmd
) {
1782 dirty
= server
.dirty
;
1784 if (server
.appendonly
&& server
.dirty
-dirty
)
1785 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1786 if (server
.dirty
-dirty
&& listLength(server
.slaves
))
1787 replicationFeedSlaves(server
.slaves
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1788 if (listLength(server
.monitors
))
1789 replicationFeedSlaves(server
.monitors
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1790 server
.stat_numcommands
++;
1793 /* If this function gets called we already read a whole
1794 * command, argments are in the client argv/argc fields.
1795 * processCommand() execute the command or prepare the
1796 * server for a bulk read from the client.
1798 * If 1 is returned the client is still alive and valid and
1799 * and other operations can be performed by the caller. Otherwise
1800 * if 0 is returned the client was destroied (i.e. after QUIT). */
1801 static int processCommand(redisClient
*c
) {
1802 struct redisCommand
*cmd
;
1804 /* Free some memory if needed (maxmemory setting) */
1805 if (server
.maxmemory
) freeMemoryIfNeeded();
1807 /* Handle the multi bulk command type. This is an alternative protocol
1808 * supported by Redis in order to receive commands that are composed of
1809 * multiple binary-safe "bulk" arguments. The latency of processing is
1810 * a bit higher but this allows things like multi-sets, so if this
1811 * protocol is used only for MSET and similar commands this is a big win. */
1812 if (c
->multibulk
== 0 && c
->argc
== 1 && ((char*)(c
->argv
[0]->ptr
))[0] == '*') {
1813 c
->multibulk
= atoi(((char*)c
->argv
[0]->ptr
)+1);
1814 if (c
->multibulk
<= 0) {
1818 decrRefCount(c
->argv
[c
->argc
-1]);
1822 } else if (c
->multibulk
) {
1823 if (c
->bulklen
== -1) {
1824 if (((char*)c
->argv
[0]->ptr
)[0] != '$') {
1825 addReplySds(c
,sdsnew("-ERR multi bulk protocol error\r\n"));
1829 int bulklen
= atoi(((char*)c
->argv
[0]->ptr
)+1);
1830 decrRefCount(c
->argv
[0]);
1831 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1833 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1838 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1842 c
->mbargv
= zrealloc(c
->mbargv
,(sizeof(robj
*))*(c
->mbargc
+1));
1843 c
->mbargv
[c
->mbargc
] = c
->argv
[0];
1847 if (c
->multibulk
== 0) {
1851 /* Here we need to swap the multi-bulk argc/argv with the
1852 * normal argc/argv of the client structure. */
1854 c
->argv
= c
->mbargv
;
1855 c
->mbargv
= auxargv
;
1858 c
->argc
= c
->mbargc
;
1859 c
->mbargc
= auxargc
;
1861 /* We need to set bulklen to something different than -1
1862 * in order for the code below to process the command without
1863 * to try to read the last argument of a bulk command as
1864 * a special argument. */
1866 /* continue below and process the command */
1873 /* -- end of multi bulk commands processing -- */
1875 /* The QUIT command is handled as a special case. Normal command
1876 * procs are unable to close the client connection safely */
1877 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
1881 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1884 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
1885 (char*)c
->argv
[0]->ptr
));
1888 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
1889 (c
->argc
< -cmd
->arity
)) {
1891 sdscatprintf(sdsempty(),
1892 "-ERR wrong number of arguments for '%s' command\r\n",
1896 } else if (server
.maxmemory
&& cmd
->flags
& REDIS_CMD_DENYOOM
&& zmalloc_used_memory() > server
.maxmemory
) {
1897 addReplySds(c
,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
1900 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
1901 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
1903 decrRefCount(c
->argv
[c
->argc
-1]);
1904 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1906 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1911 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1912 /* It is possible that the bulk read is already in the
1913 * buffer. Check this condition and handle it accordingly.
1914 * This is just a fast path, alternative to call processInputBuffer().
1915 * It's a good idea since the code is small and this condition
1916 * happens most of the times. */
1917 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
1918 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
1920 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
1925 /* Let's try to share objects on the command arguments vector */
1926 if (server
.shareobjects
) {
1928 for(j
= 1; j
< c
->argc
; j
++)
1929 c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]);
1931 /* Let's try to encode the bulk object to save space. */
1932 if (cmd
->flags
& REDIS_CMD_BULK
)
1933 tryObjectEncoding(c
->argv
[c
->argc
-1]);
1935 /* Check if the user is authenticated */
1936 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
1937 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
1942 /* Exec the command */
1943 if (c
->flags
& REDIS_MULTI
&& cmd
->proc
!= execCommand
) {
1944 queueMultiCommand(c
,cmd
);
1945 addReply(c
,shared
.queued
);
1950 /* Prepare the client for the next command */
1951 if (c
->flags
& REDIS_CLOSE
) {
1959 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
1963 /* (args*2)+1 is enough room for args, spaces, newlines */
1964 robj
*static_outv
[REDIS_STATIC_ARGS
*2+1];
1966 if (argc
<= REDIS_STATIC_ARGS
) {
1969 outv
= zmalloc(sizeof(robj
*)*(argc
*2+1));
1972 for (j
= 0; j
< argc
; j
++) {
1973 if (j
!= 0) outv
[outc
++] = shared
.space
;
1974 if ((cmd
->flags
& REDIS_CMD_BULK
) && j
== argc
-1) {
1977 lenobj
= createObject(REDIS_STRING
,
1978 sdscatprintf(sdsempty(),"%lu\r\n",
1979 (unsigned long) stringObjectLen(argv
[j
])));
1980 lenobj
->refcount
= 0;
1981 outv
[outc
++] = lenobj
;
1983 outv
[outc
++] = argv
[j
];
1985 outv
[outc
++] = shared
.crlf
;
1987 /* Increment all the refcounts at start and decrement at end in order to
1988 * be sure to free objects if there is no slave in a replication state
1989 * able to be feed with commands */
1990 for (j
= 0; j
< outc
; j
++) incrRefCount(outv
[j
]);
1992 while((ln
= listYield(slaves
))) {
1993 redisClient
*slave
= ln
->value
;
1995 /* Don't feed slaves that are still waiting for BGSAVE to start */
1996 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) continue;
1998 /* Feed all the other slaves, MONITORs and so on */
1999 if (slave
->slaveseldb
!= dictid
) {
2003 case 0: selectcmd
= shared
.select0
; break;
2004 case 1: selectcmd
= shared
.select1
; break;
2005 case 2: selectcmd
= shared
.select2
; break;
2006 case 3: selectcmd
= shared
.select3
; break;
2007 case 4: selectcmd
= shared
.select4
; break;
2008 case 5: selectcmd
= shared
.select5
; break;
2009 case 6: selectcmd
= shared
.select6
; break;
2010 case 7: selectcmd
= shared
.select7
; break;
2011 case 8: selectcmd
= shared
.select8
; break;
2012 case 9: selectcmd
= shared
.select9
; break;
2014 selectcmd
= createObject(REDIS_STRING
,
2015 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
2016 selectcmd
->refcount
= 0;
2019 addReply(slave
,selectcmd
);
2020 slave
->slaveseldb
= dictid
;
2022 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
2024 for (j
= 0; j
< outc
; j
++) decrRefCount(outv
[j
]);
2025 if (outv
!= static_outv
) zfree(outv
);
2028 static void processInputBuffer(redisClient
*c
) {
2030 /* Before to process the input buffer, make sure the client is not
2031 * waitig for a blocking operation such as BLPOP. Note that the first
2032 * iteration the client is never blocked, otherwise the processInputBuffer
2033 * would not be called at all, but after the execution of the first commands
2034 * in the input buffer the client may be blocked, and the "goto again"
2035 * will try to reiterate. The following line will make it return asap. */
2036 if (c
->flags
& REDIS_BLOCKED
) return;
2037 if (c
->bulklen
== -1) {
2038 /* Read the first line of the query */
2039 char *p
= strchr(c
->querybuf
,'\n');
2046 query
= c
->querybuf
;
2047 c
->querybuf
= sdsempty();
2048 querylen
= 1+(p
-(query
));
2049 if (sdslen(query
) > querylen
) {
2050 /* leave data after the first line of the query in the buffer */
2051 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
2053 *p
= '\0'; /* remove "\n" */
2054 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
2055 sdsupdatelen(query
);
2057 /* Now we can split the query in arguments */
2058 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
2061 if (c
->argv
) zfree(c
->argv
);
2062 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
2064 for (j
= 0; j
< argc
; j
++) {
2065 if (sdslen(argv
[j
])) {
2066 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
2074 /* Execute the command. If the client is still valid
2075 * after processCommand() return and there is something
2076 * on the query buffer try to process the next command. */
2077 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2079 /* Nothing to process, argc == 0. Just process the query
2080 * buffer if it's not empty or return to the caller */
2081 if (sdslen(c
->querybuf
)) goto again
;
2084 } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) {
2085 redisLog(REDIS_DEBUG
, "Client protocol error");
2090 /* Bulk read handling. Note that if we are at this point
2091 the client already sent a command terminated with a newline,
2092 we are reading the bulk data that is actually the last
2093 argument of the command. */
2094 int qbl
= sdslen(c
->querybuf
);
2096 if (c
->bulklen
<= qbl
) {
2097 /* Copy everything but the final CRLF as final argument */
2098 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2100 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2101 /* Process the command. If the client is still valid after
2102 * the processing and there is more data in the buffer
2103 * try to parse it. */
2104 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2110 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2111 redisClient
*c
= (redisClient
*) privdata
;
2112 char buf
[REDIS_IOBUF_LEN
];
2115 REDIS_NOTUSED(mask
);
2117 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
2119 if (errno
== EAGAIN
) {
2122 redisLog(REDIS_DEBUG
, "Reading from client: %s",strerror(errno
));
2126 } else if (nread
== 0) {
2127 redisLog(REDIS_DEBUG
, "Client closed connection");
2132 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
2133 c
->lastinteraction
= time(NULL
);
2137 processInputBuffer(c
);
2140 static int selectDb(redisClient
*c
, int id
) {
2141 if (id
< 0 || id
>= server
.dbnum
)
2143 c
->db
= &server
.db
[id
];
2147 static void *dupClientReplyValue(void *o
) {
2148 incrRefCount((robj
*)o
);
2152 static redisClient
*createClient(int fd
) {
2153 redisClient
*c
= zmalloc(sizeof(*c
));
2155 anetNonBlock(NULL
,fd
);
2156 anetTcpNoDelay(NULL
,fd
);
2157 if (!c
) return NULL
;
2160 c
->querybuf
= sdsempty();
2169 c
->lastinteraction
= time(NULL
);
2170 c
->authenticated
= 0;
2171 c
->replstate
= REDIS_REPL_NONE
;
2172 c
->reply
= listCreate();
2173 c
->blockingkeys
= NULL
;
2174 c
->blockingkeysnum
= 0;
2175 listSetFreeMethod(c
->reply
,decrRefCount
);
2176 listSetDupMethod(c
->reply
,dupClientReplyValue
);
2177 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
2178 readQueryFromClient
, c
) == AE_ERR
) {
2182 listAddNodeTail(server
.clients
,c
);
2183 initClientMultiState(c
);
2187 static void addReply(redisClient
*c
, robj
*obj
) {
2188 if (listLength(c
->reply
) == 0 &&
2189 (c
->replstate
== REDIS_REPL_NONE
||
2190 c
->replstate
== REDIS_REPL_ONLINE
) &&
2191 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
2192 sendReplyToClient
, c
) == AE_ERR
) return;
2194 if (server
.vm_enabled
&& obj
->storage
!= REDIS_VM_MEMORY
) {
2195 obj
= dupStringObject(obj
);
2196 obj
->refcount
= 0; /* getDecodedObject() will increment the refcount */
2198 listAddNodeTail(c
->reply
,getDecodedObject(obj
));
2201 static void addReplySds(redisClient
*c
, sds s
) {
2202 robj
*o
= createObject(REDIS_STRING
,s
);
2207 static void addReplyDouble(redisClient
*c
, double d
) {
2210 snprintf(buf
,sizeof(buf
),"%.17g",d
);
2211 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2212 (unsigned long) strlen(buf
),buf
));
2215 static void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
2218 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
2219 len
= sdslen(obj
->ptr
);
2221 long n
= (long)obj
->ptr
;
2223 /* Compute how many bytes will take this integer as a radix 10 string */
2229 while((n
= n
/10) != 0) {
2233 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",(unsigned long)len
));
2236 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2241 REDIS_NOTUSED(mask
);
2242 REDIS_NOTUSED(privdata
);
2244 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
2245 if (cfd
== AE_ERR
) {
2246 redisLog(REDIS_DEBUG
,"Accepting client connection: %s", server
.neterr
);
2249 redisLog(REDIS_DEBUG
,"Accepted %s:%d", cip
, cport
);
2250 if ((c
= createClient(cfd
)) == NULL
) {
2251 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
2252 close(cfd
); /* May be already closed, just ingore errors */
2255 /* If maxclient directive is set and this is one client more... close the
2256 * connection. Note that we create the client instead to check before
2257 * for this condition, since now the socket is already set in nonblocking
2258 * mode and we can send an error for free using the Kernel I/O */
2259 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
2260 char *err
= "-ERR max number of clients reached\r\n";
2262 /* That's a best effort error message, don't check write errors */
2263 if (write(c
->fd
,err
,strlen(err
)) == -1) {
2264 /* Nothing to do, Just to avoid the warning... */
2269 server
.stat_numconnections
++;
2272 /* ======================= Redis objects implementation ===================== */
2274 static robj
*createObject(int type
, void *ptr
) {
2277 if (listLength(server
.objfreelist
)) {
2278 listNode
*head
= listFirst(server
.objfreelist
);
2279 o
= listNodeValue(head
);
2280 listDelNode(server
.objfreelist
,head
);
2282 if (server
.vm_enabled
) {
2283 o
= zmalloc(sizeof(*o
));
2285 o
= zmalloc(sizeof(*o
)-sizeof(struct redisObjectVM
));
2289 o
->encoding
= REDIS_ENCODING_RAW
;
2292 if (server
.vm_enabled
) {
2293 o
->vm
.atime
= server
.unixtime
;
2294 o
->storage
= REDIS_VM_MEMORY
;
2299 static robj
*createStringObject(char *ptr
, size_t len
) {
2300 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
2303 static robj
*dupStringObject(robj
*o
) {
2304 return createStringObject(o
->ptr
,sdslen(o
->ptr
));
2307 static robj
*createListObject(void) {
2308 list
*l
= listCreate();
2310 listSetFreeMethod(l
,decrRefCount
);
2311 return createObject(REDIS_LIST
,l
);
2314 static robj
*createSetObject(void) {
2315 dict
*d
= dictCreate(&setDictType
,NULL
);
2316 return createObject(REDIS_SET
,d
);
2319 static robj
*createZsetObject(void) {
2320 zset
*zs
= zmalloc(sizeof(*zs
));
2322 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
2323 zs
->zsl
= zslCreate();
2324 return createObject(REDIS_ZSET
,zs
);
2327 static void freeStringObject(robj
*o
) {
2328 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2333 static void freeListObject(robj
*o
) {
2334 listRelease((list
*) o
->ptr
);
2337 static void freeSetObject(robj
*o
) {
2338 dictRelease((dict
*) o
->ptr
);
2341 static void freeZsetObject(robj
*o
) {
2344 dictRelease(zs
->dict
);
2349 static void freeHashObject(robj
*o
) {
2350 dictRelease((dict
*) o
->ptr
);
2353 static void incrRefCount(robj
*o
) {
2354 assert(!server
.vm_enabled
|| o
->storage
== REDIS_VM_MEMORY
);
2358 static void decrRefCount(void *obj
) {
2361 /* REDIS_VM_SWAPPED */
2362 if (server
.vm_enabled
&& o
->storage
== REDIS_VM_SWAPPED
) {
2363 assert(o
->refcount
== 1);
2364 assert(o
->type
== REDIS_STRING
);
2365 freeStringObject(o
);
2366 vmMarkPagesFree(o
->vm
.page
,o
->vm
.usedpages
);
2367 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2368 !listAddNodeHead(server
.objfreelist
,o
))
2372 /* REDIS_VM_MEMORY */
2373 if (--(o
->refcount
) == 0) {
2375 case REDIS_STRING
: freeStringObject(o
); break;
2376 case REDIS_LIST
: freeListObject(o
); break;
2377 case REDIS_SET
: freeSetObject(o
); break;
2378 case REDIS_ZSET
: freeZsetObject(o
); break;
2379 case REDIS_HASH
: freeHashObject(o
); break;
2380 default: redisAssert(0 != 0); break;
2382 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2383 !listAddNodeHead(server
.objfreelist
,o
))
2388 static robj
*lookupKey(redisDb
*db
, robj
*key
) {
2389 dictEntry
*de
= dictFind(db
->dict
,key
);
2391 robj
*key
= dictGetEntryKey(de
);
2392 robj
*val
= dictGetEntryVal(de
);
2394 if (server
.vm_enabled
) {
2395 if (key
->storage
== REDIS_VM_MEMORY
) {
2396 /* Update the access time of the key for the aging algorithm. */
2397 key
->vm
.atime
= server
.unixtime
;
2399 /* Our value was swapped on disk. Bring it at home. */
2400 assert(val
== NULL
);
2401 val
= vmLoadObject(key
);
2402 dictGetEntryVal(de
) = val
;
2411 static robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
2412 expireIfNeeded(db
,key
);
2413 return lookupKey(db
,key
);
2416 static robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
2417 deleteIfVolatile(db
,key
);
2418 return lookupKey(db
,key
);
2421 static int deleteKey(redisDb
*db
, robj
*key
) {
2424 /* We need to protect key from destruction: after the first dictDelete()
2425 * it may happen that 'key' is no longer valid if we don't increment
2426 * it's count. This may happen when we get the object reference directly
2427 * from the hash table with dictRandomKey() or dict iterators */
2429 if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
);
2430 retval
= dictDelete(db
->dict
,key
);
2433 return retval
== DICT_OK
;
2436 /* Try to share an object against the shared objects pool */
2437 static robj
*tryObjectSharing(robj
*o
) {
2438 struct dictEntry
*de
;
2441 if (o
== NULL
|| server
.shareobjects
== 0) return o
;
2443 redisAssert(o
->type
== REDIS_STRING
);
2444 de
= dictFind(server
.sharingpool
,o
);
2446 robj
*shared
= dictGetEntryKey(de
);
2448 c
= ((unsigned long) dictGetEntryVal(de
))+1;
2449 dictGetEntryVal(de
) = (void*) c
;
2450 incrRefCount(shared
);
2454 /* Here we are using a stream algorihtm: Every time an object is
2455 * shared we increment its count, everytime there is a miss we
2456 * recrement the counter of a random object. If this object reaches
2457 * zero we remove the object and put the current object instead. */
2458 if (dictSize(server
.sharingpool
) >=
2459 server
.sharingpoolsize
) {
2460 de
= dictGetRandomKey(server
.sharingpool
);
2461 redisAssert(de
!= NULL
);
2462 c
= ((unsigned long) dictGetEntryVal(de
))-1;
2463 dictGetEntryVal(de
) = (void*) c
;
2465 dictDelete(server
.sharingpool
,de
->key
);
2468 c
= 0; /* If the pool is empty we want to add this object */
2473 retval
= dictAdd(server
.sharingpool
,o
,(void*)1);
2474 redisAssert(retval
== DICT_OK
);
2481 /* Check if the nul-terminated string 's' can be represented by a long
2482 * (that is, is a number that fits into long without any other space or
2483 * character before or after the digits).
2485 * If so, the function returns REDIS_OK and *longval is set to the value
2486 * of the number. Otherwise REDIS_ERR is returned */
2487 static int isStringRepresentableAsLong(sds s
, long *longval
) {
2488 char buf
[32], *endptr
;
2492 value
= strtol(s
, &endptr
, 10);
2493 if (endptr
[0] != '\0') return REDIS_ERR
;
2494 slen
= snprintf(buf
,32,"%ld",value
);
2496 /* If the number converted back into a string is not identical
2497 * then it's not possible to encode the string as integer */
2498 if (sdslen(s
) != (unsigned)slen
|| memcmp(buf
,s
,slen
)) return REDIS_ERR
;
2499 if (longval
) *longval
= value
;
2503 /* Try to encode a string object in order to save space */
2504 static int tryObjectEncoding(robj
*o
) {
2508 if (o
->encoding
!= REDIS_ENCODING_RAW
)
2509 return REDIS_ERR
; /* Already encoded */
2511 /* It's not save to encode shared objects: shared objects can be shared
2512 * everywhere in the "object space" of Redis. Encoded objects can only
2513 * appear as "values" (and not, for instance, as keys) */
2514 if (o
->refcount
> 1) return REDIS_ERR
;
2516 /* Currently we try to encode only strings */
2517 redisAssert(o
->type
== REDIS_STRING
);
2519 /* Check if we can represent this string as a long integer */
2520 if (isStringRepresentableAsLong(s
,&value
) == REDIS_ERR
) return REDIS_ERR
;
2522 /* Ok, this object can be encoded */
2523 o
->encoding
= REDIS_ENCODING_INT
;
2525 o
->ptr
= (void*) value
;
2529 /* Get a decoded version of an encoded object (returned as a new object).
2530 * If the object is already raw-encoded just increment the ref count. */
2531 static robj
*getDecodedObject(robj
*o
) {
2534 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2538 if (o
->type
== REDIS_STRING
&& o
->encoding
== REDIS_ENCODING_INT
) {
2541 snprintf(buf
,32,"%ld",(long)o
->ptr
);
2542 dec
= createStringObject(buf
,strlen(buf
));
2545 redisAssert(1 != 1);
2549 /* Compare two string objects via strcmp() or alike.
2550 * Note that the objects may be integer-encoded. In such a case we
2551 * use snprintf() to get a string representation of the numbers on the stack
2552 * and compare the strings, it's much faster than calling getDecodedObject().
2554 * Important note: if objects are not integer encoded, but binary-safe strings,
2555 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
2557 static int compareStringObjects(robj
*a
, robj
*b
) {
2558 redisAssert(a
->type
== REDIS_STRING
&& b
->type
== REDIS_STRING
);
2559 char bufa
[128], bufb
[128], *astr
, *bstr
;
2562 if (a
== b
) return 0;
2563 if (a
->encoding
!= REDIS_ENCODING_RAW
) {
2564 snprintf(bufa
,sizeof(bufa
),"%ld",(long) a
->ptr
);
2570 if (b
->encoding
!= REDIS_ENCODING_RAW
) {
2571 snprintf(bufb
,sizeof(bufb
),"%ld",(long) b
->ptr
);
2577 return bothsds
? sdscmp(astr
,bstr
) : strcmp(astr
,bstr
);
2580 static size_t stringObjectLen(robj
*o
) {
2581 redisAssert(o
->type
== REDIS_STRING
);
2582 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2583 return sdslen(o
->ptr
);
2587 return snprintf(buf
,32,"%ld",(long)o
->ptr
);
2591 /*============================ RDB saving/loading =========================== */
2593 static int rdbSaveType(FILE *fp
, unsigned char type
) {
2594 if (fwrite(&type
,1,1,fp
) == 0) return -1;
2598 static int rdbSaveTime(FILE *fp
, time_t t
) {
2599 int32_t t32
= (int32_t) t
;
2600 if (fwrite(&t32
,4,1,fp
) == 0) return -1;
2604 /* check rdbLoadLen() comments for more info */
2605 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
2606 unsigned char buf
[2];
2609 /* Save a 6 bit len */
2610 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
2611 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2612 } else if (len
< (1<<14)) {
2613 /* Save a 14 bit len */
2614 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
2616 if (fwrite(buf
,2,1,fp
) == 0) return -1;
2618 /* Save a 32 bit len */
2619 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
2620 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2622 if (fwrite(&len
,4,1,fp
) == 0) return -1;
2627 /* String objects in the form "2391" "-100" without any space and with a
2628 * range of values that can fit in an 8, 16 or 32 bit signed value can be
2629 * encoded as integers to save space */
2630 static int rdbTryIntegerEncoding(sds s
, unsigned char *enc
) {
2632 char *endptr
, buf
[32];
2634 /* Check if it's possible to encode this value as a number */
2635 value
= strtoll(s
, &endptr
, 10);
2636 if (endptr
[0] != '\0') return 0;
2637 snprintf(buf
,32,"%lld",value
);
2639 /* If the number converted back into a string is not identical
2640 * then it's not possible to encode the string as integer */
2641 if (strlen(buf
) != sdslen(s
) || memcmp(buf
,s
,sdslen(s
))) return 0;
2643 /* Finally check if it fits in our ranges */
2644 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
2645 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
2646 enc
[1] = value
&0xFF;
2648 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
2649 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
2650 enc
[1] = value
&0xFF;
2651 enc
[2] = (value
>>8)&0xFF;
2653 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
2654 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
2655 enc
[1] = value
&0xFF;
2656 enc
[2] = (value
>>8)&0xFF;
2657 enc
[3] = (value
>>16)&0xFF;
2658 enc
[4] = (value
>>24)&0xFF;
2665 static int rdbSaveLzfStringObject(FILE *fp
, robj
*obj
) {
2666 unsigned int comprlen
, outlen
;
2670 /* We require at least four bytes compression for this to be worth it */
2671 outlen
= sdslen(obj
->ptr
)-4;
2672 if (outlen
<= 0) return 0;
2673 if ((out
= zmalloc(outlen
+1)) == NULL
) return 0;
2674 comprlen
= lzf_compress(obj
->ptr
, sdslen(obj
->ptr
), out
, outlen
);
2675 if (comprlen
== 0) {
2679 /* Data compressed! Let's save it on disk */
2680 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
2681 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
2682 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
2683 if (rdbSaveLen(fp
,sdslen(obj
->ptr
)) == -1) goto writeerr
;
2684 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
2693 /* Save a string objet as [len][data] on disk. If the object is a string
2694 * representation of an integer value we try to safe it in a special form */
2695 static int rdbSaveStringObjectRaw(FILE *fp
, robj
*obj
) {
2699 len
= sdslen(obj
->ptr
);
2701 /* Try integer encoding */
2703 unsigned char buf
[5];
2704 if ((enclen
= rdbTryIntegerEncoding(obj
->ptr
,buf
)) > 0) {
2705 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
2710 /* Try LZF compression - under 20 bytes it's unable to compress even
2711 * aaaaaaaaaaaaaaaaaa so skip it */
2712 if (server
.rdbcompression
&& len
> 20) {
2715 retval
= rdbSaveLzfStringObject(fp
,obj
);
2716 if (retval
== -1) return -1;
2717 if (retval
> 0) return 0;
2718 /* retval == 0 means data can't be compressed, save the old way */
2721 /* Store verbatim */
2722 if (rdbSaveLen(fp
,len
) == -1) return -1;
2723 if (len
&& fwrite(obj
->ptr
,len
,1,fp
) == 0) return -1;
2727 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
2728 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
2731 obj
= getDecodedObject(obj
);
2732 retval
= rdbSaveStringObjectRaw(fp
,obj
);
2737 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
2738 * 8 bit integer specifing the length of the representation.
2739 * This 8 bit integer has special values in order to specify the following
2745 static int rdbSaveDoubleValue(FILE *fp
, double val
) {
2746 unsigned char buf
[128];
2752 } else if (!isfinite(val
)) {
2754 buf
[0] = (val
< 0) ? 255 : 254;
2756 snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
);
2757 buf
[0] = strlen((char*)buf
+1);
2760 if (fwrite(buf
,len
,1,fp
) == 0) return -1;
2764 /* Save a Redis object. */
2765 static int rdbSaveObject(FILE *fp
, robj
*o
) {
2766 if (o
->type
== REDIS_STRING
) {
2767 /* Save a string value */
2768 if (rdbSaveStringObject(fp
,o
) == -1) return -1;
2769 } else if (o
->type
== REDIS_LIST
) {
2770 /* Save a list value */
2771 list
*list
= o
->ptr
;
2775 if (rdbSaveLen(fp
,listLength(list
)) == -1) return -1;
2776 while((ln
= listYield(list
))) {
2777 robj
*eleobj
= listNodeValue(ln
);
2779 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2781 } else if (o
->type
== REDIS_SET
) {
2782 /* Save a set value */
2784 dictIterator
*di
= dictGetIterator(set
);
2787 if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1;
2788 while((de
= dictNext(di
)) != NULL
) {
2789 robj
*eleobj
= dictGetEntryKey(de
);
2791 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2793 dictReleaseIterator(di
);
2794 } else if (o
->type
== REDIS_ZSET
) {
2795 /* Save a set value */
2797 dictIterator
*di
= dictGetIterator(zs
->dict
);
2800 if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1;
2801 while((de
= dictNext(di
)) != NULL
) {
2802 robj
*eleobj
= dictGetEntryKey(de
);
2803 double *score
= dictGetEntryVal(de
);
2805 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2806 if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1;
2808 dictReleaseIterator(di
);
2810 redisAssert(0 != 0);
2815 /* Return the length the object will have on disk if saved with
2816 * the rdbSaveObject() function. Currently we use a trick to get
2817 * this length with very little changes to the code. In the future
2818 * we could switch to a faster solution. */
2819 static off_t
rdbSavedObjectLen(robj
*o
) {
2820 static FILE *fp
= NULL
;
2822 if (fp
== NULL
) fp
= fopen("/dev/null","w");
2826 assert(rdbSaveObject(fp
,o
) != 1);
2830 /* Return the number of pages required to save this object in the swap file */
2831 static off_t
rdbSavedObjectPages(robj
*o
) {
2832 off_t bytes
= rdbSavedObjectLen(o
);
2834 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
2837 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
2838 static int rdbSave(char *filename
) {
2839 dictIterator
*di
= NULL
;
2844 time_t now
= time(NULL
);
2846 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
2847 fp
= fopen(tmpfile
,"w");
2849 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
2852 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
2853 for (j
= 0; j
< server
.dbnum
; j
++) {
2854 redisDb
*db
= server
.db
+j
;
2856 if (dictSize(d
) == 0) continue;
2857 di
= dictGetIterator(d
);
2863 /* Write the SELECT DB opcode */
2864 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
2865 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
2867 /* Iterate this DB writing every entry */
2868 while((de
= dictNext(di
)) != NULL
) {
2869 robj
*key
= dictGetEntryKey(de
);
2870 robj
*o
= dictGetEntryVal(de
);
2871 time_t expiretime
= getExpire(db
,key
);
2873 /* Save the expire time */
2874 if (expiretime
!= -1) {
2875 /* If this key is already expired skip it */
2876 if (expiretime
< now
) continue;
2877 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
2878 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
2880 /* Save the key and associated value */
2881 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
2882 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
2883 /* Save the actual value */
2884 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
2886 dictReleaseIterator(di
);
2889 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
2891 /* Make sure data will not remain on the OS's output buffers */
2896 /* Use RENAME to make sure the DB file is changed atomically only
2897 * if the generate DB file is ok. */
2898 if (rename(tmpfile
,filename
) == -1) {
2899 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
2903 redisLog(REDIS_NOTICE
,"DB saved on disk");
2905 server
.lastsave
= time(NULL
);
2911 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
2912 if (di
) dictReleaseIterator(di
);
2916 static int rdbSaveBackground(char *filename
) {
2919 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
2920 if ((childpid
= fork()) == 0) {
2923 if (rdbSave(filename
) == REDIS_OK
) {
2930 if (childpid
== -1) {
2931 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
2935 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
2936 server
.bgsavechildpid
= childpid
;
2939 return REDIS_OK
; /* unreached */
2942 static void rdbRemoveTempFile(pid_t childpid
) {
2945 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
2949 static int rdbLoadType(FILE *fp
) {
2951 if (fread(&type
,1,1,fp
) == 0) return -1;
2955 static time_t rdbLoadTime(FILE *fp
) {
2957 if (fread(&t32
,4,1,fp
) == 0) return -1;
2958 return (time_t) t32
;
2961 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
2962 * of this file for a description of how this are stored on disk.
2964 * isencoded is set to 1 if the readed length is not actually a length but
2965 * an "encoding type", check the above comments for more info */
2966 static uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
2967 unsigned char buf
[2];
2971 if (isencoded
) *isencoded
= 0;
2972 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
2973 type
= (buf
[0]&0xC0)>>6;
2974 if (type
== REDIS_RDB_6BITLEN
) {
2975 /* Read a 6 bit len */
2977 } else if (type
== REDIS_RDB_ENCVAL
) {
2978 /* Read a 6 bit len encoding type */
2979 if (isencoded
) *isencoded
= 1;
2981 } else if (type
== REDIS_RDB_14BITLEN
) {
2982 /* Read a 14 bit len */
2983 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
2984 return ((buf
[0]&0x3F)<<8)|buf
[1];
2986 /* Read a 32 bit len */
2987 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
2992 static robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
) {
2993 unsigned char enc
[4];
2996 if (enctype
== REDIS_RDB_ENC_INT8
) {
2997 if (fread(enc
,1,1,fp
) == 0) return NULL
;
2998 val
= (signed char)enc
[0];
2999 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
3001 if (fread(enc
,2,1,fp
) == 0) return NULL
;
3002 v
= enc
[0]|(enc
[1]<<8);
3004 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
3006 if (fread(enc
,4,1,fp
) == 0) return NULL
;
3007 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
3010 val
= 0; /* anti-warning */
3013 return createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",val
));
3016 static robj
*rdbLoadLzfStringObject(FILE*fp
) {
3017 unsigned int len
, clen
;
3018 unsigned char *c
= NULL
;
3021 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3022 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3023 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
3024 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
3025 if (fread(c
,clen
,1,fp
) == 0) goto err
;
3026 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
3028 return createObject(REDIS_STRING
,val
);
3035 static robj
*rdbLoadStringObject(FILE*fp
) {
3040 len
= rdbLoadLen(fp
,&isencoded
);
3043 case REDIS_RDB_ENC_INT8
:
3044 case REDIS_RDB_ENC_INT16
:
3045 case REDIS_RDB_ENC_INT32
:
3046 return tryObjectSharing(rdbLoadIntegerObject(fp
,len
));
3047 case REDIS_RDB_ENC_LZF
:
3048 return tryObjectSharing(rdbLoadLzfStringObject(fp
));
3054 if (len
== REDIS_RDB_LENERR
) return NULL
;
3055 val
= sdsnewlen(NULL
,len
);
3056 if (len
&& fread(val
,len
,1,fp
) == 0) {
3060 return tryObjectSharing(createObject(REDIS_STRING
,val
));
3063 /* For information about double serialization check rdbSaveDoubleValue() */
3064 static int rdbLoadDoubleValue(FILE *fp
, double *val
) {
3068 if (fread(&len
,1,1,fp
) == 0) return -1;
3070 case 255: *val
= R_NegInf
; return 0;
3071 case 254: *val
= R_PosInf
; return 0;
3072 case 253: *val
= R_Nan
; return 0;
3074 if (fread(buf
,len
,1,fp
) == 0) return -1;
3076 sscanf(buf
, "%lg", val
);
3081 /* Load a Redis object of the specified type from the specified file.
3082 * On success a newly allocated object is returned, otherwise NULL. */
3083 static robj
*rdbLoadObject(int type
, FILE *fp
) {
3086 if (type
== REDIS_STRING
) {
3087 /* Read string value */
3088 if ((o
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3089 tryObjectEncoding(o
);
3090 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
3091 /* Read list/set value */
3094 if ((listlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3095 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
3096 /* Load every single element of the list/set */
3100 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3101 tryObjectEncoding(ele
);
3102 if (type
== REDIS_LIST
) {
3103 listAddNodeTail((list
*)o
->ptr
,ele
);
3105 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
3108 } else if (type
== REDIS_ZSET
) {
3109 /* Read list/set value */
3113 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3114 o
= createZsetObject();
3116 /* Load every single element of the list/set */
3119 double *score
= zmalloc(sizeof(double));
3121 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3122 tryObjectEncoding(ele
);
3123 if (rdbLoadDoubleValue(fp
,score
) == -1) return NULL
;
3124 dictAdd(zs
->dict
,ele
,score
);
3125 zslInsert(zs
->zsl
,*score
,ele
);
3126 incrRefCount(ele
); /* added to skiplist */
3129 redisAssert(0 != 0);
3134 static int rdbLoad(char *filename
) {
3136 robj
*keyobj
= NULL
;
3138 int type
, retval
, rdbver
;
3139 dict
*d
= server
.db
[0].dict
;
3140 redisDb
*db
= server
.db
+0;
3142 time_t expiretime
= -1, now
= time(NULL
);
3144 fp
= fopen(filename
,"r");
3145 if (!fp
) return REDIS_ERR
;
3146 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
3148 if (memcmp(buf
,"REDIS",5) != 0) {
3150 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
3153 rdbver
= atoi(buf
+5);
3156 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
3163 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3164 if (type
== REDIS_EXPIRETIME
) {
3165 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
3166 /* We read the time so we need to read the object type again */
3167 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3169 if (type
== REDIS_EOF
) break;
3170 /* Handle SELECT DB opcode as a special case */
3171 if (type
== REDIS_SELECTDB
) {
3172 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
3174 if (dbid
>= (unsigned)server
.dbnum
) {
3175 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
3178 db
= server
.db
+dbid
;
3183 if ((keyobj
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
3185 if ((o
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
3186 /* Add the new object in the hash table */
3187 retval
= dictAdd(d
,keyobj
,o
);
3188 if (retval
== DICT_ERR
) {
3189 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
3192 /* Set the expire time if needed */
3193 if (expiretime
!= -1) {
3194 setExpire(db
,keyobj
,expiretime
);
3195 /* Delete this key if already expired */
3196 if (expiretime
< now
) deleteKey(db
,keyobj
);
3204 eoferr
: /* unexpected end of file is handled here with a fatal exit */
3205 if (keyobj
) decrRefCount(keyobj
);
3206 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
3208 return REDIS_ERR
; /* Just to avoid warning */
3211 /*================================== Commands =============================== */
3213 static void authCommand(redisClient
*c
) {
3214 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
3215 c
->authenticated
= 1;
3216 addReply(c
,shared
.ok
);
3218 c
->authenticated
= 0;
3219 addReplySds(c
,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
3223 static void pingCommand(redisClient
*c
) {
3224 addReply(c
,shared
.pong
);
3227 static void echoCommand(redisClient
*c
) {
3228 addReplyBulkLen(c
,c
->argv
[1]);
3229 addReply(c
,c
->argv
[1]);
3230 addReply(c
,shared
.crlf
);
3233 /*=================================== Strings =============================== */
3235 static void setGenericCommand(redisClient
*c
, int nx
) {
3238 if (nx
) deleteIfVolatile(c
->db
,c
->argv
[1]);
3239 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3240 if (retval
== DICT_ERR
) {
3242 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3243 incrRefCount(c
->argv
[2]);
3245 addReply(c
,shared
.czero
);
3249 incrRefCount(c
->argv
[1]);
3250 incrRefCount(c
->argv
[2]);
3253 removeExpire(c
->db
,c
->argv
[1]);
3254 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3257 static void setCommand(redisClient
*c
) {
3258 setGenericCommand(c
,0);
3261 static void setnxCommand(redisClient
*c
) {
3262 setGenericCommand(c
,1);
3265 static int getGenericCommand(redisClient
*c
) {
3266 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3269 addReply(c
,shared
.nullbulk
);
3272 if (o
->type
!= REDIS_STRING
) {
3273 addReply(c
,shared
.wrongtypeerr
);
3276 addReplyBulkLen(c
,o
);
3278 addReply(c
,shared
.crlf
);
3284 static void getCommand(redisClient
*c
) {
3285 getGenericCommand(c
);
3288 static void getsetCommand(redisClient
*c
) {
3289 if (getGenericCommand(c
) == REDIS_ERR
) return;
3290 if (dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]) == DICT_ERR
) {
3291 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3293 incrRefCount(c
->argv
[1]);
3295 incrRefCount(c
->argv
[2]);
3297 removeExpire(c
->db
,c
->argv
[1]);
3300 static void mgetCommand(redisClient
*c
) {
3303 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
3304 for (j
= 1; j
< c
->argc
; j
++) {
3305 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[j
]);
3307 addReply(c
,shared
.nullbulk
);
3309 if (o
->type
!= REDIS_STRING
) {
3310 addReply(c
,shared
.nullbulk
);
3312 addReplyBulkLen(c
,o
);
3314 addReply(c
,shared
.crlf
);
3320 static void msetGenericCommand(redisClient
*c
, int nx
) {
3321 int j
, busykeys
= 0;
3323 if ((c
->argc
% 2) == 0) {
3324 addReplySds(c
,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
3327 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
3328 * set nothing at all if at least one already key exists. */
3330 for (j
= 1; j
< c
->argc
; j
+= 2) {
3331 if (lookupKeyWrite(c
->db
,c
->argv
[j
]) != NULL
) {
3337 addReply(c
, shared
.czero
);
3341 for (j
= 1; j
< c
->argc
; j
+= 2) {
3344 tryObjectEncoding(c
->argv
[j
+1]);
3345 retval
= dictAdd(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3346 if (retval
== DICT_ERR
) {
3347 dictReplace(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3348 incrRefCount(c
->argv
[j
+1]);
3350 incrRefCount(c
->argv
[j
]);
3351 incrRefCount(c
->argv
[j
+1]);
3353 removeExpire(c
->db
,c
->argv
[j
]);
3355 server
.dirty
+= (c
->argc
-1)/2;
3356 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3359 static void msetCommand(redisClient
*c
) {
3360 msetGenericCommand(c
,0);
3363 static void msetnxCommand(redisClient
*c
) {
3364 msetGenericCommand(c
,1);
3367 static void incrDecrCommand(redisClient
*c
, long long incr
) {
3372 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3376 if (o
->type
!= REDIS_STRING
) {
3381 if (o
->encoding
== REDIS_ENCODING_RAW
)
3382 value
= strtoll(o
->ptr
, &eptr
, 10);
3383 else if (o
->encoding
== REDIS_ENCODING_INT
)
3384 value
= (long)o
->ptr
;
3386 redisAssert(1 != 1);
3391 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
3392 tryObjectEncoding(o
);
3393 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],o
);
3394 if (retval
== DICT_ERR
) {
3395 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
3396 removeExpire(c
->db
,c
->argv
[1]);
3398 incrRefCount(c
->argv
[1]);
3401 addReply(c
,shared
.colon
);
3403 addReply(c
,shared
.crlf
);
3406 static void incrCommand(redisClient
*c
) {
3407 incrDecrCommand(c
,1);
3410 static void decrCommand(redisClient
*c
) {
3411 incrDecrCommand(c
,-1);
3414 static void incrbyCommand(redisClient
*c
) {
3415 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3416 incrDecrCommand(c
,incr
);
3419 static void decrbyCommand(redisClient
*c
) {
3420 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3421 incrDecrCommand(c
,-incr
);
3424 /* ========================= Type agnostic commands ========================= */
3426 static void delCommand(redisClient
*c
) {
3429 for (j
= 1; j
< c
->argc
; j
++) {
3430 if (deleteKey(c
->db
,c
->argv
[j
])) {
3437 addReply(c
,shared
.czero
);
3440 addReply(c
,shared
.cone
);
3443 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",deleted
));
3448 static void existsCommand(redisClient
*c
) {
3449 addReply(c
,lookupKeyRead(c
->db
,c
->argv
[1]) ? shared
.cone
: shared
.czero
);
3452 static void selectCommand(redisClient
*c
) {
3453 int id
= atoi(c
->argv
[1]->ptr
);
3455 if (selectDb(c
,id
) == REDIS_ERR
) {
3456 addReplySds(c
,sdsnew("-ERR invalid DB index\r\n"));
3458 addReply(c
,shared
.ok
);
3462 static void randomkeyCommand(redisClient
*c
) {
3466 de
= dictGetRandomKey(c
->db
->dict
);
3467 if (!de
|| expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break;
3470 addReply(c
,shared
.plus
);
3471 addReply(c
,shared
.crlf
);
3473 addReply(c
,shared
.plus
);
3474 addReply(c
,dictGetEntryKey(de
));
3475 addReply(c
,shared
.crlf
);
3479 static void keysCommand(redisClient
*c
) {
3482 sds pattern
= c
->argv
[1]->ptr
;
3483 int plen
= sdslen(pattern
);
3484 unsigned long numkeys
= 0, keyslen
= 0;
3485 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
3487 di
= dictGetIterator(c
->db
->dict
);
3489 decrRefCount(lenobj
);
3490 while((de
= dictNext(di
)) != NULL
) {
3491 robj
*keyobj
= dictGetEntryKey(de
);
3493 sds key
= keyobj
->ptr
;
3494 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
3495 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
3496 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
3498 addReply(c
,shared
.space
);
3501 keyslen
+= sdslen(key
);
3505 dictReleaseIterator(di
);
3506 lenobj
->ptr
= sdscatprintf(sdsempty(),"$%lu\r\n",keyslen
+(numkeys
? (numkeys
-1) : 0));
3507 addReply(c
,shared
.crlf
);
3510 static void dbsizeCommand(redisClient
*c
) {
3512 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
)));
3515 static void lastsaveCommand(redisClient
*c
) {
3517 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
3520 static void typeCommand(redisClient
*c
) {
3524 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3529 case REDIS_STRING
: type
= "+string"; break;
3530 case REDIS_LIST
: type
= "+list"; break;
3531 case REDIS_SET
: type
= "+set"; break;
3532 case REDIS_ZSET
: type
= "+zset"; break;
3533 default: type
= "unknown"; break;
3536 addReplySds(c
,sdsnew(type
));
3537 addReply(c
,shared
.crlf
);
3540 static void saveCommand(redisClient
*c
) {
3541 if (server
.bgsavechildpid
!= -1) {
3542 addReplySds(c
,sdsnew("-ERR background save in progress\r\n"));
3545 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
3546 addReply(c
,shared
.ok
);
3548 addReply(c
,shared
.err
);
3552 static void bgsaveCommand(redisClient
*c
) {
3553 if (server
.bgsavechildpid
!= -1) {
3554 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
3557 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
3558 char *status
= "+Background saving started\r\n";
3559 addReplySds(c
,sdsnew(status
));
3561 addReply(c
,shared
.err
);
3565 static void shutdownCommand(redisClient
*c
) {
3566 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
3567 /* Kill the saving child if there is a background saving in progress.
3568 We want to avoid race conditions, for instance our saving child may
3569 overwrite the synchronous saving did by SHUTDOWN. */
3570 if (server
.bgsavechildpid
!= -1) {
3571 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
3572 kill(server
.bgsavechildpid
,SIGKILL
);
3573 rdbRemoveTempFile(server
.bgsavechildpid
);
3575 if (server
.appendonly
) {
3576 /* Append only file: fsync() the AOF and exit */
3577 fsync(server
.appendfd
);
3580 /* Snapshotting. Perform a SYNC SAVE and exit */
3581 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
3582 if (server
.daemonize
)
3583 unlink(server
.pidfile
);
3584 redisLog(REDIS_WARNING
,"%zu bytes used at exit",zmalloc_used_memory());
3585 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
3588 /* Ooops.. error saving! The best we can do is to continue operating.
3589 * Note that if there was a background saving process, in the next
3590 * cron() Redis will be notified that the background saving aborted,
3591 * handling special stuff like slaves pending for synchronization... */
3592 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
3593 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
3598 static void renameGenericCommand(redisClient
*c
, int nx
) {
3601 /* To use the same key as src and dst is probably an error */
3602 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
3603 addReply(c
,shared
.sameobjecterr
);
3607 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3609 addReply(c
,shared
.nokeyerr
);
3613 deleteIfVolatile(c
->db
,c
->argv
[2]);
3614 if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
3617 addReply(c
,shared
.czero
);
3620 dictReplace(c
->db
->dict
,c
->argv
[2],o
);
3622 incrRefCount(c
->argv
[2]);
3624 deleteKey(c
->db
,c
->argv
[1]);
3626 addReply(c
,nx
? shared
.cone
: shared
.ok
);
3629 static void renameCommand(redisClient
*c
) {
3630 renameGenericCommand(c
,0);
3633 static void renamenxCommand(redisClient
*c
) {
3634 renameGenericCommand(c
,1);
3637 static void moveCommand(redisClient
*c
) {
3642 /* Obtain source and target DB pointers */
3645 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
3646 addReply(c
,shared
.outofrangeerr
);
3650 selectDb(c
,srcid
); /* Back to the source DB */
3652 /* If the user is moving using as target the same
3653 * DB as the source DB it is probably an error. */
3655 addReply(c
,shared
.sameobjecterr
);
3659 /* Check if the element exists and get a reference */
3660 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3662 addReply(c
,shared
.czero
);
3666 /* Try to add the element to the target DB */
3667 deleteIfVolatile(dst
,c
->argv
[1]);
3668 if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) {
3669 addReply(c
,shared
.czero
);
3672 incrRefCount(c
->argv
[1]);
3675 /* OK! key moved, free the entry in the source DB */
3676 deleteKey(src
,c
->argv
[1]);
3678 addReply(c
,shared
.cone
);
3681 /* =================================== Lists ================================ */
3682 static void pushGenericCommand(redisClient
*c
, int where
) {
3686 lobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3688 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
3689 addReply(c
,shared
.ok
);
3692 lobj
= createListObject();
3694 if (where
== REDIS_HEAD
) {
3695 listAddNodeHead(list
,c
->argv
[2]);
3697 listAddNodeTail(list
,c
->argv
[2]);
3699 dictAdd(c
->db
->dict
,c
->argv
[1],lobj
);
3700 incrRefCount(c
->argv
[1]);
3701 incrRefCount(c
->argv
[2]);
3703 if (lobj
->type
!= REDIS_LIST
) {
3704 addReply(c
,shared
.wrongtypeerr
);
3707 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
3708 addReply(c
,shared
.ok
);
3712 if (where
== REDIS_HEAD
) {
3713 listAddNodeHead(list
,c
->argv
[2]);
3715 listAddNodeTail(list
,c
->argv
[2]);
3717 incrRefCount(c
->argv
[2]);
3720 addReply(c
,shared
.ok
);
3723 static void lpushCommand(redisClient
*c
) {
3724 pushGenericCommand(c
,REDIS_HEAD
);
3727 static void rpushCommand(redisClient
*c
) {
3728 pushGenericCommand(c
,REDIS_TAIL
);
3731 static void llenCommand(redisClient
*c
) {
3735 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3737 addReply(c
,shared
.czero
);
3740 if (o
->type
!= REDIS_LIST
) {
3741 addReply(c
,shared
.wrongtypeerr
);
3744 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
)));
3749 static void lindexCommand(redisClient
*c
) {
3751 int index
= atoi(c
->argv
[2]->ptr
);
3753 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3755 addReply(c
,shared
.nullbulk
);
3757 if (o
->type
!= REDIS_LIST
) {
3758 addReply(c
,shared
.wrongtypeerr
);
3760 list
*list
= o
->ptr
;
3763 ln
= listIndex(list
, index
);
3765 addReply(c
,shared
.nullbulk
);
3767 robj
*ele
= listNodeValue(ln
);
3768 addReplyBulkLen(c
,ele
);
3770 addReply(c
,shared
.crlf
);
3776 static void lsetCommand(redisClient
*c
) {
3778 int index
= atoi(c
->argv
[2]->ptr
);
3780 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3782 addReply(c
,shared
.nokeyerr
);
3784 if (o
->type
!= REDIS_LIST
) {
3785 addReply(c
,shared
.wrongtypeerr
);
3787 list
*list
= o
->ptr
;
3790 ln
= listIndex(list
, index
);
3792 addReply(c
,shared
.outofrangeerr
);
3794 robj
*ele
= listNodeValue(ln
);
3797 listNodeValue(ln
) = c
->argv
[3];
3798 incrRefCount(c
->argv
[3]);
3799 addReply(c
,shared
.ok
);
3806 static void popGenericCommand(redisClient
*c
, int where
) {
3809 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3811 addReply(c
,shared
.nullbulk
);
3813 if (o
->type
!= REDIS_LIST
) {
3814 addReply(c
,shared
.wrongtypeerr
);
3816 list
*list
= o
->ptr
;
3819 if (where
== REDIS_HEAD
)
3820 ln
= listFirst(list
);
3822 ln
= listLast(list
);
3825 addReply(c
,shared
.nullbulk
);
3827 robj
*ele
= listNodeValue(ln
);
3828 addReplyBulkLen(c
,ele
);
3830 addReply(c
,shared
.crlf
);
3831 listDelNode(list
,ln
);
3838 static void lpopCommand(redisClient
*c
) {
3839 popGenericCommand(c
,REDIS_HEAD
);
3842 static void rpopCommand(redisClient
*c
) {
3843 popGenericCommand(c
,REDIS_TAIL
);
3846 static void lrangeCommand(redisClient
*c
) {
3848 int start
= atoi(c
->argv
[2]->ptr
);
3849 int end
= atoi(c
->argv
[3]->ptr
);
3851 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3853 addReply(c
,shared
.nullmultibulk
);
3855 if (o
->type
!= REDIS_LIST
) {
3856 addReply(c
,shared
.wrongtypeerr
);
3858 list
*list
= o
->ptr
;
3860 int llen
= listLength(list
);
3864 /* convert negative indexes */
3865 if (start
< 0) start
= llen
+start
;
3866 if (end
< 0) end
= llen
+end
;
3867 if (start
< 0) start
= 0;
3868 if (end
< 0) end
= 0;
3870 /* indexes sanity checks */
3871 if (start
> end
|| start
>= llen
) {
3872 /* Out of range start or start > end result in empty list */
3873 addReply(c
,shared
.emptymultibulk
);
3876 if (end
>= llen
) end
= llen
-1;
3877 rangelen
= (end
-start
)+1;
3879 /* Return the result in form of a multi-bulk reply */
3880 ln
= listIndex(list
, start
);
3881 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
3882 for (j
= 0; j
< rangelen
; j
++) {
3883 ele
= listNodeValue(ln
);
3884 addReplyBulkLen(c
,ele
);
3886 addReply(c
,shared
.crlf
);
3893 static void ltrimCommand(redisClient
*c
) {
3895 int start
= atoi(c
->argv
[2]->ptr
);
3896 int end
= atoi(c
->argv
[3]->ptr
);
3898 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3900 addReply(c
,shared
.ok
);
3902 if (o
->type
!= REDIS_LIST
) {
3903 addReply(c
,shared
.wrongtypeerr
);
3905 list
*list
= o
->ptr
;
3907 int llen
= listLength(list
);
3908 int j
, ltrim
, rtrim
;
3910 /* convert negative indexes */
3911 if (start
< 0) start
= llen
+start
;
3912 if (end
< 0) end
= llen
+end
;
3913 if (start
< 0) start
= 0;
3914 if (end
< 0) end
= 0;
3916 /* indexes sanity checks */
3917 if (start
> end
|| start
>= llen
) {
3918 /* Out of range start or start > end result in empty list */
3922 if (end
>= llen
) end
= llen
-1;
3927 /* Remove list elements to perform the trim */
3928 for (j
= 0; j
< ltrim
; j
++) {
3929 ln
= listFirst(list
);
3930 listDelNode(list
,ln
);
3932 for (j
= 0; j
< rtrim
; j
++) {
3933 ln
= listLast(list
);
3934 listDelNode(list
,ln
);
3937 addReply(c
,shared
.ok
);
3942 static void lremCommand(redisClient
*c
) {
3945 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3947 addReply(c
,shared
.czero
);
3949 if (o
->type
!= REDIS_LIST
) {
3950 addReply(c
,shared
.wrongtypeerr
);
3952 list
*list
= o
->ptr
;
3953 listNode
*ln
, *next
;
3954 int toremove
= atoi(c
->argv
[2]->ptr
);
3959 toremove
= -toremove
;
3962 ln
= fromtail
? list
->tail
: list
->head
;
3964 robj
*ele
= listNodeValue(ln
);
3966 next
= fromtail
? ln
->prev
: ln
->next
;
3967 if (compareStringObjects(ele
,c
->argv
[3]) == 0) {
3968 listDelNode(list
,ln
);
3971 if (toremove
&& removed
== toremove
) break;
3975 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
3980 /* This is the semantic of this command:
3981 * RPOPLPUSH srclist dstlist:
3982 * IF LLEN(srclist) > 0
3983 * element = RPOP srclist
3984 * LPUSH dstlist element
3991 * The idea is to be able to get an element from a list in a reliable way
3992 * since the element is not just returned but pushed against another list
3993 * as well. This command was originally proposed by Ezra Zygmuntowicz.
3995 static void rpoplpushcommand(redisClient
*c
) {
3998 sobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4000 addReply(c
,shared
.nullbulk
);
4002 if (sobj
->type
!= REDIS_LIST
) {
4003 addReply(c
,shared
.wrongtypeerr
);
4005 list
*srclist
= sobj
->ptr
;
4006 listNode
*ln
= listLast(srclist
);
4009 addReply(c
,shared
.nullbulk
);
4011 robj
*dobj
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4012 robj
*ele
= listNodeValue(ln
);
4015 if (dobj
&& dobj
->type
!= REDIS_LIST
) {
4016 addReply(c
,shared
.wrongtypeerr
);
4020 /* Add the element to the target list (unless it's directly
4021 * passed to some BLPOP-ing client */
4022 if (!handleClientsWaitingListPush(c
,c
->argv
[2],ele
)) {
4024 /* Create the list if the key does not exist */
4025 dobj
= createListObject();
4026 dictAdd(c
->db
->dict
,c
->argv
[2],dobj
);
4027 incrRefCount(c
->argv
[2]);
4029 dstlist
= dobj
->ptr
;
4030 listAddNodeHead(dstlist
,ele
);
4034 /* Send the element to the client as reply as well */
4035 addReplyBulkLen(c
,ele
);
4037 addReply(c
,shared
.crlf
);
4039 /* Finally remove the element from the source list */
4040 listDelNode(srclist
,ln
);
4048 /* ==================================== Sets ================================ */
4050 static void saddCommand(redisClient
*c
) {
4053 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4055 set
= createSetObject();
4056 dictAdd(c
->db
->dict
,c
->argv
[1],set
);
4057 incrRefCount(c
->argv
[1]);
4059 if (set
->type
!= REDIS_SET
) {
4060 addReply(c
,shared
.wrongtypeerr
);
4064 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
4065 incrRefCount(c
->argv
[2]);
4067 addReply(c
,shared
.cone
);
4069 addReply(c
,shared
.czero
);
4073 static void sremCommand(redisClient
*c
) {
4076 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4078 addReply(c
,shared
.czero
);
4080 if (set
->type
!= REDIS_SET
) {
4081 addReply(c
,shared
.wrongtypeerr
);
4084 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
4086 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4087 addReply(c
,shared
.cone
);
4089 addReply(c
,shared
.czero
);
4094 static void smoveCommand(redisClient
*c
) {
4095 robj
*srcset
, *dstset
;
4097 srcset
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4098 dstset
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4100 /* If the source key does not exist return 0, if it's of the wrong type
4102 if (srcset
== NULL
|| srcset
->type
!= REDIS_SET
) {
4103 addReply(c
, srcset
? shared
.wrongtypeerr
: shared
.czero
);
4106 /* Error if the destination key is not a set as well */
4107 if (dstset
&& dstset
->type
!= REDIS_SET
) {
4108 addReply(c
,shared
.wrongtypeerr
);
4111 /* Remove the element from the source set */
4112 if (dictDelete(srcset
->ptr
,c
->argv
[3]) == DICT_ERR
) {
4113 /* Key not found in the src set! return zero */
4114 addReply(c
,shared
.czero
);
4118 /* Add the element to the destination set */
4120 dstset
= createSetObject();
4121 dictAdd(c
->db
->dict
,c
->argv
[2],dstset
);
4122 incrRefCount(c
->argv
[2]);
4124 if (dictAdd(dstset
->ptr
,c
->argv
[3],NULL
) == DICT_OK
)
4125 incrRefCount(c
->argv
[3]);
4126 addReply(c
,shared
.cone
);
4129 static void sismemberCommand(redisClient
*c
) {
4132 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4134 addReply(c
,shared
.czero
);
4136 if (set
->type
!= REDIS_SET
) {
4137 addReply(c
,shared
.wrongtypeerr
);
4140 if (dictFind(set
->ptr
,c
->argv
[2]))
4141 addReply(c
,shared
.cone
);
4143 addReply(c
,shared
.czero
);
4147 static void scardCommand(redisClient
*c
) {
4151 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4153 addReply(c
,shared
.czero
);
4156 if (o
->type
!= REDIS_SET
) {
4157 addReply(c
,shared
.wrongtypeerr
);
4160 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4166 static void spopCommand(redisClient
*c
) {
4170 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4172 addReply(c
,shared
.nullbulk
);
4174 if (set
->type
!= REDIS_SET
) {
4175 addReply(c
,shared
.wrongtypeerr
);
4178 de
= dictGetRandomKey(set
->ptr
);
4180 addReply(c
,shared
.nullbulk
);
4182 robj
*ele
= dictGetEntryKey(de
);
4184 addReplyBulkLen(c
,ele
);
4186 addReply(c
,shared
.crlf
);
4187 dictDelete(set
->ptr
,ele
);
4188 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4194 static void srandmemberCommand(redisClient
*c
) {
4198 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4200 addReply(c
,shared
.nullbulk
);
4202 if (set
->type
!= REDIS_SET
) {
4203 addReply(c
,shared
.wrongtypeerr
);
4206 de
= dictGetRandomKey(set
->ptr
);
4208 addReply(c
,shared
.nullbulk
);
4210 robj
*ele
= dictGetEntryKey(de
);
4212 addReplyBulkLen(c
,ele
);
4214 addReply(c
,shared
.crlf
);
4219 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
4220 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
4222 return dictSize(*d1
)-dictSize(*d2
);
4225 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, unsigned long setsnum
, robj
*dstkey
) {
4226 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4229 robj
*lenobj
= NULL
, *dstset
= NULL
;
4230 unsigned long j
, cardinality
= 0;
4232 for (j
= 0; j
< setsnum
; j
++) {
4236 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4237 lookupKeyRead(c
->db
,setskeys
[j
]);
4241 if (deleteKey(c
->db
,dstkey
))
4243 addReply(c
,shared
.czero
);
4245 addReply(c
,shared
.nullmultibulk
);
4249 if (setobj
->type
!= REDIS_SET
) {
4251 addReply(c
,shared
.wrongtypeerr
);
4254 dv
[j
] = setobj
->ptr
;
4256 /* Sort sets from the smallest to largest, this will improve our
4257 * algorithm's performace */
4258 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
4260 /* The first thing we should output is the total number of elements...
4261 * since this is a multi-bulk write, but at this stage we don't know
4262 * the intersection set size, so we use a trick, append an empty object
4263 * to the output list and save the pointer to later modify it with the
4266 lenobj
= createObject(REDIS_STRING
,NULL
);
4268 decrRefCount(lenobj
);
4270 /* If we have a target key where to store the resulting set
4271 * create this key with an empty set inside */
4272 dstset
= createSetObject();
4275 /* Iterate all the elements of the first (smallest) set, and test
4276 * the element against all the other sets, if at least one set does
4277 * not include the element it is discarded */
4278 di
= dictGetIterator(dv
[0]);
4280 while((de
= dictNext(di
)) != NULL
) {
4283 for (j
= 1; j
< setsnum
; j
++)
4284 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
4286 continue; /* at least one set does not contain the member */
4287 ele
= dictGetEntryKey(de
);
4289 addReplyBulkLen(c
,ele
);
4291 addReply(c
,shared
.crlf
);
4294 dictAdd(dstset
->ptr
,ele
,NULL
);
4298 dictReleaseIterator(di
);
4301 /* Store the resulting set into the target */
4302 deleteKey(c
->db
,dstkey
);
4303 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4304 incrRefCount(dstkey
);
4308 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",cardinality
);
4310 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4311 dictSize((dict
*)dstset
->ptr
)));
4317 static void sinterCommand(redisClient
*c
) {
4318 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
4321 static void sinterstoreCommand(redisClient
*c
) {
4322 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
4325 #define REDIS_OP_UNION 0
4326 #define REDIS_OP_DIFF 1
4328 static void sunionDiffGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
, int op
) {
4329 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4332 robj
*dstset
= NULL
;
4333 int j
, cardinality
= 0;
4335 for (j
= 0; j
< setsnum
; j
++) {
4339 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4340 lookupKeyRead(c
->db
,setskeys
[j
]);
4345 if (setobj
->type
!= REDIS_SET
) {
4347 addReply(c
,shared
.wrongtypeerr
);
4350 dv
[j
] = setobj
->ptr
;
4353 /* We need a temp set object to store our union. If the dstkey
4354 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
4355 * this set object will be the resulting object to set into the target key*/
4356 dstset
= createSetObject();
4358 /* Iterate all the elements of all the sets, add every element a single
4359 * time to the result set */
4360 for (j
= 0; j
< setsnum
; j
++) {
4361 if (op
== REDIS_OP_DIFF
&& j
== 0 && !dv
[j
]) break; /* result set is empty */
4362 if (!dv
[j
]) continue; /* non existing keys are like empty sets */
4364 di
= dictGetIterator(dv
[j
]);
4366 while((de
= dictNext(di
)) != NULL
) {
4369 /* dictAdd will not add the same element multiple times */
4370 ele
= dictGetEntryKey(de
);
4371 if (op
== REDIS_OP_UNION
|| j
== 0) {
4372 if (dictAdd(dstset
->ptr
,ele
,NULL
) == DICT_OK
) {
4376 } else if (op
== REDIS_OP_DIFF
) {
4377 if (dictDelete(dstset
->ptr
,ele
) == DICT_OK
) {
4382 dictReleaseIterator(di
);
4384 if (op
== REDIS_OP_DIFF
&& cardinality
== 0) break; /* result set is empty */
4387 /* Output the content of the resulting set, if not in STORE mode */
4389 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",cardinality
));
4390 di
= dictGetIterator(dstset
->ptr
);
4391 while((de
= dictNext(di
)) != NULL
) {
4394 ele
= dictGetEntryKey(de
);
4395 addReplyBulkLen(c
,ele
);
4397 addReply(c
,shared
.crlf
);
4399 dictReleaseIterator(di
);
4401 /* If we have a target key where to store the resulting set
4402 * create this key with the result set inside */
4403 deleteKey(c
->db
,dstkey
);
4404 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4405 incrRefCount(dstkey
);
4410 decrRefCount(dstset
);
4412 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4413 dictSize((dict
*)dstset
->ptr
)));
4419 static void sunionCommand(redisClient
*c
) {
4420 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_UNION
);
4423 static void sunionstoreCommand(redisClient
*c
) {
4424 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_UNION
);
4427 static void sdiffCommand(redisClient
*c
) {
4428 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_DIFF
);
4431 static void sdiffstoreCommand(redisClient
*c
) {
4432 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_DIFF
);
4435 /* ==================================== ZSets =============================== */
4437 /* ZSETs are ordered sets using two data structures to hold the same elements
4438 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
4441 * The elements are added to an hash table mapping Redis objects to scores.
4442 * At the same time the elements are added to a skip list mapping scores
4443 * to Redis objects (so objects are sorted by scores in this "view"). */
4445 /* This skiplist implementation is almost a C translation of the original
4446 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
4447 * Alternative to Balanced Trees", modified in three ways:
4448 * a) this implementation allows for repeated values.
4449 * b) the comparison is not just by key (our 'score') but by satellite data.
4450 * c) there is a back pointer, so it's a doubly linked list with the back
4451 * pointers being only at "level 1". This allows to traverse the list
4452 * from tail to head, useful for ZREVRANGE. */
4454 static zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
4455 zskiplistNode
*zn
= zmalloc(sizeof(*zn
));
4457 zn
->forward
= zmalloc(sizeof(zskiplistNode
*) * level
);
4463 static zskiplist
*zslCreate(void) {
4467 zsl
= zmalloc(sizeof(*zsl
));
4470 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
4471 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++)
4472 zsl
->header
->forward
[j
] = NULL
;
4473 zsl
->header
->backward
= NULL
;
4478 static void zslFreeNode(zskiplistNode
*node
) {
4479 decrRefCount(node
->obj
);
4480 zfree(node
->forward
);
4484 static void zslFree(zskiplist
*zsl
) {
4485 zskiplistNode
*node
= zsl
->header
->forward
[0], *next
;
4487 zfree(zsl
->header
->forward
);
4490 next
= node
->forward
[0];
4497 static int zslRandomLevel(void) {
4499 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
4504 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
4505 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4509 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4510 while (x
->forward
[i
] &&
4511 (x
->forward
[i
]->score
< score
||
4512 (x
->forward
[i
]->score
== score
&&
4513 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
4517 /* we assume the key is not already inside, since we allow duplicated
4518 * scores, and the re-insertion of score and redis object should never
4519 * happpen since the caller of zslInsert() should test in the hash table
4520 * if the element is already inside or not. */
4521 level
= zslRandomLevel();
4522 if (level
> zsl
->level
) {
4523 for (i
= zsl
->level
; i
< level
; i
++)
4524 update
[i
] = zsl
->header
;
4527 x
= zslCreateNode(level
,score
,obj
);
4528 for (i
= 0; i
< level
; i
++) {
4529 x
->forward
[i
] = update
[i
]->forward
[i
];
4530 update
[i
]->forward
[i
] = x
;
4532 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
4534 x
->forward
[0]->backward
= x
;
4540 /* Delete an element with matching score/object from the skiplist. */
4541 static int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
4542 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4546 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4547 while (x
->forward
[i
] &&
4548 (x
->forward
[i
]->score
< score
||
4549 (x
->forward
[i
]->score
== score
&&
4550 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
4554 /* We may have multiple elements with the same score, what we need
4555 * is to find the element with both the right score and object. */
4557 if (x
&& score
== x
->score
&& compareStringObjects(x
->obj
,obj
) == 0) {
4558 for (i
= 0; i
< zsl
->level
; i
++) {
4559 if (update
[i
]->forward
[i
] != x
) break;
4560 update
[i
]->forward
[i
] = x
->forward
[i
];
4562 if (x
->forward
[0]) {
4563 x
->forward
[0]->backward
= (x
->backward
== zsl
->header
) ?
4566 zsl
->tail
= x
->backward
;
4569 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
4574 return 0; /* not found */
4576 return 0; /* not found */
4579 /* Delete all the elements with score between min and max from the skiplist.
4580 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
4581 * Note that this function takes the reference to the hash table view of the
4582 * sorted set, in order to remove the elements from the hash table too. */
4583 static unsigned long zslDeleteRange(zskiplist
*zsl
, double min
, double max
, dict
*dict
) {
4584 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4585 unsigned long removed
= 0;
4589 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4590 while (x
->forward
[i
] && x
->forward
[i
]->score
< min
)
4594 /* We may have multiple elements with the same score, what we need
4595 * is to find the element with both the right score and object. */
4597 while (x
&& x
->score
<= max
) {
4598 zskiplistNode
*next
;
4600 for (i
= 0; i
< zsl
->level
; i
++) {
4601 if (update
[i
]->forward
[i
] != x
) break;
4602 update
[i
]->forward
[i
] = x
->forward
[i
];
4604 if (x
->forward
[0]) {
4605 x
->forward
[0]->backward
= (x
->backward
== zsl
->header
) ?
4608 zsl
->tail
= x
->backward
;
4610 next
= x
->forward
[0];
4611 dictDelete(dict
,x
->obj
);
4613 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
4619 return removed
; /* not found */
4622 /* Find the first node having a score equal or greater than the specified one.
4623 * Returns NULL if there is no match. */
4624 static zskiplistNode
*zslFirstWithScore(zskiplist
*zsl
, double score
) {
4629 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4630 while (x
->forward
[i
] && x
->forward
[i
]->score
< score
)
4633 /* We may have multiple elements with the same score, what we need
4634 * is to find the element with both the right score and object. */
4635 return x
->forward
[0];
4638 /* The actual Z-commands implementations */
4640 /* This generic command implements both ZADD and ZINCRBY.
4641 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
4642 * the increment if the operation is a ZINCRBY (doincrement == 1). */
4643 static void zaddGenericCommand(redisClient
*c
, robj
*key
, robj
*ele
, double scoreval
, int doincrement
) {
4648 zsetobj
= lookupKeyWrite(c
->db
,key
);
4649 if (zsetobj
== NULL
) {
4650 zsetobj
= createZsetObject();
4651 dictAdd(c
->db
->dict
,key
,zsetobj
);
4654 if (zsetobj
->type
!= REDIS_ZSET
) {
4655 addReply(c
,shared
.wrongtypeerr
);
4661 /* Ok now since we implement both ZADD and ZINCRBY here the code
4662 * needs to handle the two different conditions. It's all about setting
4663 * '*score', that is, the new score to set, to the right value. */
4664 score
= zmalloc(sizeof(double));
4668 /* Read the old score. If the element was not present starts from 0 */
4669 de
= dictFind(zs
->dict
,ele
);
4671 double *oldscore
= dictGetEntryVal(de
);
4672 *score
= *oldscore
+ scoreval
;
4680 /* What follows is a simple remove and re-insert operation that is common
4681 * to both ZADD and ZINCRBY... */
4682 if (dictAdd(zs
->dict
,ele
,score
) == DICT_OK
) {
4683 /* case 1: New element */
4684 incrRefCount(ele
); /* added to hash */
4685 zslInsert(zs
->zsl
,*score
,ele
);
4686 incrRefCount(ele
); /* added to skiplist */
4689 addReplyDouble(c
,*score
);
4691 addReply(c
,shared
.cone
);
4696 /* case 2: Score update operation */
4697 de
= dictFind(zs
->dict
,ele
);
4698 redisAssert(de
!= NULL
);
4699 oldscore
= dictGetEntryVal(de
);
4700 if (*score
!= *oldscore
) {
4703 /* Remove and insert the element in the skip list with new score */
4704 deleted
= zslDelete(zs
->zsl
,*oldscore
,ele
);
4705 redisAssert(deleted
!= 0);
4706 zslInsert(zs
->zsl
,*score
,ele
);
4708 /* Update the score in the hash table */
4709 dictReplace(zs
->dict
,ele
,score
);
4715 addReplyDouble(c
,*score
);
4717 addReply(c
,shared
.czero
);
4721 static void zaddCommand(redisClient
*c
) {
4724 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
4725 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0);
4728 static void zincrbyCommand(redisClient
*c
) {
4731 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
4732 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1);
4735 static void zremCommand(redisClient
*c
) {
4739 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4740 if (zsetobj
== NULL
) {
4741 addReply(c
,shared
.czero
);
4747 if (zsetobj
->type
!= REDIS_ZSET
) {
4748 addReply(c
,shared
.wrongtypeerr
);
4752 de
= dictFind(zs
->dict
,c
->argv
[2]);
4754 addReply(c
,shared
.czero
);
4757 /* Delete from the skiplist */
4758 oldscore
= dictGetEntryVal(de
);
4759 deleted
= zslDelete(zs
->zsl
,*oldscore
,c
->argv
[2]);
4760 redisAssert(deleted
!= 0);
4762 /* Delete from the hash table */
4763 dictDelete(zs
->dict
,c
->argv
[2]);
4764 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
4766 addReply(c
,shared
.cone
);
4770 static void zremrangebyscoreCommand(redisClient
*c
) {
4771 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
4772 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
4776 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4777 if (zsetobj
== NULL
) {
4778 addReply(c
,shared
.czero
);
4782 if (zsetobj
->type
!= REDIS_ZSET
) {
4783 addReply(c
,shared
.wrongtypeerr
);
4787 deleted
= zslDeleteRange(zs
->zsl
,min
,max
,zs
->dict
);
4788 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
4789 server
.dirty
+= deleted
;
4790 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",deleted
));
4794 static void zrangeGenericCommand(redisClient
*c
, int reverse
) {
4796 int start
= atoi(c
->argv
[2]->ptr
);
4797 int end
= atoi(c
->argv
[3]->ptr
);
4800 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
4802 } else if (c
->argc
>= 5) {
4803 addReply(c
,shared
.syntaxerr
);
4807 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4809 addReply(c
,shared
.nullmultibulk
);
4811 if (o
->type
!= REDIS_ZSET
) {
4812 addReply(c
,shared
.wrongtypeerr
);
4814 zset
*zsetobj
= o
->ptr
;
4815 zskiplist
*zsl
= zsetobj
->zsl
;
4818 int llen
= zsl
->length
;
4822 /* convert negative indexes */
4823 if (start
< 0) start
= llen
+start
;
4824 if (end
< 0) end
= llen
+end
;
4825 if (start
< 0) start
= 0;
4826 if (end
< 0) end
= 0;
4828 /* indexes sanity checks */
4829 if (start
> end
|| start
>= llen
) {
4830 /* Out of range start or start > end result in empty list */
4831 addReply(c
,shared
.emptymultibulk
);
4834 if (end
>= llen
) end
= llen
-1;
4835 rangelen
= (end
-start
)+1;
4837 /* Return the result in form of a multi-bulk reply */
4843 ln
= zsl
->header
->forward
[0];
4845 ln
= ln
->forward
[0];
4848 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",
4849 withscores
? (rangelen
*2) : rangelen
));
4850 for (j
= 0; j
< rangelen
; j
++) {
4852 addReplyBulkLen(c
,ele
);
4854 addReply(c
,shared
.crlf
);
4856 addReplyDouble(c
,ln
->score
);
4857 ln
= reverse
? ln
->backward
: ln
->forward
[0];
4863 static void zrangeCommand(redisClient
*c
) {
4864 zrangeGenericCommand(c
,0);
4867 static void zrevrangeCommand(redisClient
*c
) {
4868 zrangeGenericCommand(c
,1);
4871 static void zrangebyscoreCommand(redisClient
*c
) {
4873 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
4874 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
4875 int offset
= 0, limit
= -1;
4877 if (c
->argc
!= 4 && c
->argc
!= 7) {
4879 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
4881 } else if (c
->argc
== 7 && strcasecmp(c
->argv
[4]->ptr
,"limit")) {
4882 addReply(c
,shared
.syntaxerr
);
4884 } else if (c
->argc
== 7) {
4885 offset
= atoi(c
->argv
[5]->ptr
);
4886 limit
= atoi(c
->argv
[6]->ptr
);
4887 if (offset
< 0) offset
= 0;
4890 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4892 addReply(c
,shared
.nullmultibulk
);
4894 if (o
->type
!= REDIS_ZSET
) {
4895 addReply(c
,shared
.wrongtypeerr
);
4897 zset
*zsetobj
= o
->ptr
;
4898 zskiplist
*zsl
= zsetobj
->zsl
;
4901 unsigned int rangelen
= 0;
4903 /* Get the first node with the score >= min */
4904 ln
= zslFirstWithScore(zsl
,min
);
4906 /* No element matching the speciifed interval */
4907 addReply(c
,shared
.emptymultibulk
);
4911 /* We don't know in advance how many matching elements there
4912 * are in the list, so we push this object that will represent
4913 * the multi-bulk length in the output buffer, and will "fix"
4915 lenobj
= createObject(REDIS_STRING
,NULL
);
4917 decrRefCount(lenobj
);
4919 while(ln
&& ln
->score
<= max
) {
4922 ln
= ln
->forward
[0];
4925 if (limit
== 0) break;
4927 addReplyBulkLen(c
,ele
);
4929 addReply(c
,shared
.crlf
);
4930 ln
= ln
->forward
[0];
4932 if (limit
> 0) limit
--;
4934 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",rangelen
);
4939 static void zcardCommand(redisClient
*c
) {
4943 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4945 addReply(c
,shared
.czero
);
4948 if (o
->type
!= REDIS_ZSET
) {
4949 addReply(c
,shared
.wrongtypeerr
);
4952 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",zs
->zsl
->length
));
4957 static void zscoreCommand(redisClient
*c
) {
4961 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4963 addReply(c
,shared
.nullbulk
);
4966 if (o
->type
!= REDIS_ZSET
) {
4967 addReply(c
,shared
.wrongtypeerr
);
4972 de
= dictFind(zs
->dict
,c
->argv
[2]);
4974 addReply(c
,shared
.nullbulk
);
4976 double *score
= dictGetEntryVal(de
);
4978 addReplyDouble(c
,*score
);
4984 /* ========================= Non type-specific commands ==================== */
4986 static void flushdbCommand(redisClient
*c
) {
4987 server
.dirty
+= dictSize(c
->db
->dict
);
4988 dictEmpty(c
->db
->dict
);
4989 dictEmpty(c
->db
->expires
);
4990 addReply(c
,shared
.ok
);
4993 static void flushallCommand(redisClient
*c
) {
4994 server
.dirty
+= emptyDb();
4995 addReply(c
,shared
.ok
);
4996 rdbSave(server
.dbfilename
);
5000 static redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
5001 redisSortOperation
*so
= zmalloc(sizeof(*so
));
5003 so
->pattern
= pattern
;
5007 /* Return the value associated to the key with a name obtained
5008 * substituting the first occurence of '*' in 'pattern' with 'subst' */
5009 static robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
5013 int prefixlen
, sublen
, postfixlen
;
5014 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
5018 char buf
[REDIS_SORTKEY_MAX
+1];
5021 /* If the pattern is "#" return the substitution object itself in order
5022 * to implement the "SORT ... GET #" feature. */
5023 spat
= pattern
->ptr
;
5024 if (spat
[0] == '#' && spat
[1] == '\0') {
5028 /* The substitution object may be specially encoded. If so we create
5029 * a decoded object on the fly. Otherwise getDecodedObject will just
5030 * increment the ref count, that we'll decrement later. */
5031 subst
= getDecodedObject(subst
);
5034 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
5035 p
= strchr(spat
,'*');
5037 decrRefCount(subst
);
5042 sublen
= sdslen(ssub
);
5043 postfixlen
= sdslen(spat
)-(prefixlen
+1);
5044 memcpy(keyname
.buf
,spat
,prefixlen
);
5045 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
5046 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
5047 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
5048 keyname
.len
= prefixlen
+sublen
+postfixlen
;
5050 initStaticStringObject(keyobj
,((char*)&keyname
)+(sizeof(long)*2))
5051 decrRefCount(subst
);
5053 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
5054 return lookupKeyRead(db
,&keyobj
);
5057 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
5058 * the additional parameter is not standard but a BSD-specific we have to
5059 * pass sorting parameters via the global 'server' structure */
5060 static int sortCompare(const void *s1
, const void *s2
) {
5061 const redisSortObject
*so1
= s1
, *so2
= s2
;
5064 if (!server
.sort_alpha
) {
5065 /* Numeric sorting. Here it's trivial as we precomputed scores */
5066 if (so1
->u
.score
> so2
->u
.score
) {
5068 } else if (so1
->u
.score
< so2
->u
.score
) {
5074 /* Alphanumeric sorting */
5075 if (server
.sort_bypattern
) {
5076 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
5077 /* At least one compare object is NULL */
5078 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
5080 else if (so1
->u
.cmpobj
== NULL
)
5085 /* We have both the objects, use strcoll */
5086 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
5089 /* Compare elements directly */
5092 dec1
= getDecodedObject(so1
->obj
);
5093 dec2
= getDecodedObject(so2
->obj
);
5094 cmp
= strcoll(dec1
->ptr
,dec2
->ptr
);
5099 return server
.sort_desc
? -cmp
: cmp
;
5102 /* The SORT command is the most complex command in Redis. Warning: this code
5103 * is optimized for speed and a bit less for readability */
5104 static void sortCommand(redisClient
*c
) {
5107 int desc
= 0, alpha
= 0;
5108 int limit_start
= 0, limit_count
= -1, start
, end
;
5109 int j
, dontsort
= 0, vectorlen
;
5110 int getop
= 0; /* GET operation counter */
5111 robj
*sortval
, *sortby
= NULL
, *storekey
= NULL
;
5112 redisSortObject
*vector
; /* Resulting vector to sort */
5114 /* Lookup the key to sort. It must be of the right types */
5115 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
5116 if (sortval
== NULL
) {
5117 addReply(c
,shared
.nullmultibulk
);
5120 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
&&
5121 sortval
->type
!= REDIS_ZSET
)
5123 addReply(c
,shared
.wrongtypeerr
);
5127 /* Create a list of operations to perform for every sorted element.
5128 * Operations can be GET/DEL/INCR/DECR */
5129 operations
= listCreate();
5130 listSetFreeMethod(operations
,zfree
);
5133 /* Now we need to protect sortval incrementing its count, in the future
5134 * SORT may have options able to overwrite/delete keys during the sorting
5135 * and the sorted key itself may get destroied */
5136 incrRefCount(sortval
);
5138 /* The SORT command has an SQL-alike syntax, parse it */
5139 while(j
< c
->argc
) {
5140 int leftargs
= c
->argc
-j
-1;
5141 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
5143 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
5145 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
5147 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
5148 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
5149 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
5151 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"store") && leftargs
>= 1) {
5152 storekey
= c
->argv
[j
+1];
5154 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
5155 sortby
= c
->argv
[j
+1];
5156 /* If the BY pattern does not contain '*', i.e. it is constant,
5157 * we don't need to sort nor to lookup the weight keys. */
5158 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
5160 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
5161 listAddNodeTail(operations
,createSortOperation(
5162 REDIS_SORT_GET
,c
->argv
[j
+1]));
5166 decrRefCount(sortval
);
5167 listRelease(operations
);
5168 addReply(c
,shared
.syntaxerr
);
5174 /* Load the sorting vector with all the objects to sort */
5175 switch(sortval
->type
) {
5176 case REDIS_LIST
: vectorlen
= listLength((list
*)sortval
->ptr
); break;
5177 case REDIS_SET
: vectorlen
= dictSize((dict
*)sortval
->ptr
); break;
5178 case REDIS_ZSET
: vectorlen
= dictSize(((zset
*)sortval
->ptr
)->dict
); break;
5179 default: vectorlen
= 0; redisAssert(0); /* Avoid GCC warning */
5181 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
5184 if (sortval
->type
== REDIS_LIST
) {
5185 list
*list
= sortval
->ptr
;
5189 while((ln
= listYield(list
))) {
5190 robj
*ele
= ln
->value
;
5191 vector
[j
].obj
= ele
;
5192 vector
[j
].u
.score
= 0;
5193 vector
[j
].u
.cmpobj
= NULL
;
5201 if (sortval
->type
== REDIS_SET
) {
5204 zset
*zs
= sortval
->ptr
;
5208 di
= dictGetIterator(set
);
5209 while((setele
= dictNext(di
)) != NULL
) {
5210 vector
[j
].obj
= dictGetEntryKey(setele
);
5211 vector
[j
].u
.score
= 0;
5212 vector
[j
].u
.cmpobj
= NULL
;
5215 dictReleaseIterator(di
);
5217 redisAssert(j
== vectorlen
);
5219 /* Now it's time to load the right scores in the sorting vector */
5220 if (dontsort
== 0) {
5221 for (j
= 0; j
< vectorlen
; j
++) {
5225 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
5226 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
5228 vector
[j
].u
.cmpobj
= getDecodedObject(byval
);
5230 if (byval
->encoding
== REDIS_ENCODING_RAW
) {
5231 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
5233 /* Don't need to decode the object if it's
5234 * integer-encoded (the only encoding supported) so
5235 * far. We can just cast it */
5236 if (byval
->encoding
== REDIS_ENCODING_INT
) {
5237 vector
[j
].u
.score
= (long)byval
->ptr
;
5239 redisAssert(1 != 1);
5244 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_RAW
)
5245 vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
5247 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_INT
)
5248 vector
[j
].u
.score
= (long) vector
[j
].obj
->ptr
;
5250 redisAssert(1 != 1);
5257 /* We are ready to sort the vector... perform a bit of sanity check
5258 * on the LIMIT option too. We'll use a partial version of quicksort. */
5259 start
= (limit_start
< 0) ? 0 : limit_start
;
5260 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
5261 if (start
>= vectorlen
) {
5262 start
= vectorlen
-1;
5265 if (end
>= vectorlen
) end
= vectorlen
-1;
5267 if (dontsort
== 0) {
5268 server
.sort_desc
= desc
;
5269 server
.sort_alpha
= alpha
;
5270 server
.sort_bypattern
= sortby
? 1 : 0;
5271 if (sortby
&& (start
!= 0 || end
!= vectorlen
-1))
5272 pqsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
, start
,end
);
5274 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
5277 /* Send command output to the output buffer, performing the specified
5278 * GET/DEL/INCR/DECR operations if any. */
5279 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
5280 if (storekey
== NULL
) {
5281 /* STORE option not specified, sent the sorting result to client */
5282 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
5283 for (j
= start
; j
<= end
; j
++) {
5286 addReplyBulkLen(c
,vector
[j
].obj
);
5287 addReply(c
,vector
[j
].obj
);
5288 addReply(c
,shared
.crlf
);
5290 listRewind(operations
);
5291 while((ln
= listYield(operations
))) {
5292 redisSortOperation
*sop
= ln
->value
;
5293 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
5296 if (sop
->type
== REDIS_SORT_GET
) {
5297 if (!val
|| val
->type
!= REDIS_STRING
) {
5298 addReply(c
,shared
.nullbulk
);
5300 addReplyBulkLen(c
,val
);
5302 addReply(c
,shared
.crlf
);
5305 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
5310 robj
*listObject
= createListObject();
5311 list
*listPtr
= (list
*) listObject
->ptr
;
5313 /* STORE option specified, set the sorting result as a List object */
5314 for (j
= start
; j
<= end
; j
++) {
5317 listAddNodeTail(listPtr
,vector
[j
].obj
);
5318 incrRefCount(vector
[j
].obj
);
5320 listRewind(operations
);
5321 while((ln
= listYield(operations
))) {
5322 redisSortOperation
*sop
= ln
->value
;
5323 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
5326 if (sop
->type
== REDIS_SORT_GET
) {
5327 if (!val
|| val
->type
!= REDIS_STRING
) {
5328 listAddNodeTail(listPtr
,createStringObject("",0));
5330 listAddNodeTail(listPtr
,val
);
5334 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
5338 if (dictReplace(c
->db
->dict
,storekey
,listObject
)) {
5339 incrRefCount(storekey
);
5341 /* Note: we add 1 because the DB is dirty anyway since even if the
5342 * SORT result is empty a new key is set and maybe the old content
5344 server
.dirty
+= 1+outputlen
;
5345 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",outputlen
));
5349 decrRefCount(sortval
);
5350 listRelease(operations
);
5351 for (j
= 0; j
< vectorlen
; j
++) {
5352 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
5353 decrRefCount(vector
[j
].u
.cmpobj
);
5358 /* Create the string returned by the INFO command. This is decoupled
5359 * by the INFO command itself as we need to report the same information
5360 * on memory corruption problems. */
5361 static sds
genRedisInfoString(void) {
5363 time_t uptime
= time(NULL
)-server
.stat_starttime
;
5366 info
= sdscatprintf(sdsempty(),
5367 "redis_version:%s\r\n"
5369 "multiplexing_api:%s\r\n"
5370 "uptime_in_seconds:%ld\r\n"
5371 "uptime_in_days:%ld\r\n"
5372 "connected_clients:%d\r\n"
5373 "connected_slaves:%d\r\n"
5374 "blocked_clients:%d\r\n"
5375 "used_memory:%zu\r\n"
5376 "changes_since_last_save:%lld\r\n"
5377 "bgsave_in_progress:%d\r\n"
5378 "last_save_time:%ld\r\n"
5379 "bgrewriteaof_in_progress:%d\r\n"
5380 "total_connections_received:%lld\r\n"
5381 "total_commands_processed:%lld\r\n"
5384 (sizeof(long) == 8) ? "64" : "32",
5388 listLength(server
.clients
)-listLength(server
.slaves
),
5389 listLength(server
.slaves
),
5390 server
.blockedclients
,
5393 server
.bgsavechildpid
!= -1,
5395 server
.bgrewritechildpid
!= -1,
5396 server
.stat_numconnections
,
5397 server
.stat_numcommands
,
5398 server
.masterhost
== NULL
? "master" : "slave"
5400 if (server
.masterhost
) {
5401 info
= sdscatprintf(info
,
5402 "master_host:%s\r\n"
5403 "master_port:%d\r\n"
5404 "master_link_status:%s\r\n"
5405 "master_last_io_seconds_ago:%d\r\n"
5408 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
5410 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1
5413 for (j
= 0; j
< server
.dbnum
; j
++) {
5414 long long keys
, vkeys
;
5416 keys
= dictSize(server
.db
[j
].dict
);
5417 vkeys
= dictSize(server
.db
[j
].expires
);
5418 if (keys
|| vkeys
) {
5419 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
5426 static void infoCommand(redisClient
*c
) {
5427 sds info
= genRedisInfoString();
5428 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
5429 (unsigned long)sdslen(info
)));
5430 addReplySds(c
,info
);
5431 addReply(c
,shared
.crlf
);
5434 static void monitorCommand(redisClient
*c
) {
5435 /* ignore MONITOR if aleady slave or in monitor mode */
5436 if (c
->flags
& REDIS_SLAVE
) return;
5438 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
5440 listAddNodeTail(server
.monitors
,c
);
5441 addReply(c
,shared
.ok
);
5444 /* ================================= Expire ================================= */
5445 static int removeExpire(redisDb
*db
, robj
*key
) {
5446 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
5453 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
5454 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
5462 /* Return the expire time of the specified key, or -1 if no expire
5463 * is associated with this key (i.e. the key is non volatile) */
5464 static time_t getExpire(redisDb
*db
, robj
*key
) {
5467 /* No expire? return ASAP */
5468 if (dictSize(db
->expires
) == 0 ||
5469 (de
= dictFind(db
->expires
,key
)) == NULL
) return -1;
5471 return (time_t) dictGetEntryVal(de
);
5474 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
5478 /* No expire? return ASAP */
5479 if (dictSize(db
->expires
) == 0 ||
5480 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
5482 /* Lookup the expire */
5483 when
= (time_t) dictGetEntryVal(de
);
5484 if (time(NULL
) <= when
) return 0;
5486 /* Delete the key */
5487 dictDelete(db
->expires
,key
);
5488 return dictDelete(db
->dict
,key
) == DICT_OK
;
5491 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
5494 /* No expire? return ASAP */
5495 if (dictSize(db
->expires
) == 0 ||
5496 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
5498 /* Delete the key */
5500 dictDelete(db
->expires
,key
);
5501 return dictDelete(db
->dict
,key
) == DICT_OK
;
5504 static void expireGenericCommand(redisClient
*c
, robj
*key
, time_t seconds
) {
5507 de
= dictFind(c
->db
->dict
,key
);
5509 addReply(c
,shared
.czero
);
5513 if (deleteKey(c
->db
,key
)) server
.dirty
++;
5514 addReply(c
, shared
.cone
);
5517 time_t when
= time(NULL
)+seconds
;
5518 if (setExpire(c
->db
,key
,when
)) {
5519 addReply(c
,shared
.cone
);
5522 addReply(c
,shared
.czero
);
5528 static void expireCommand(redisClient
*c
) {
5529 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10));
5532 static void expireatCommand(redisClient
*c
) {
5533 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10)-time(NULL
));
5536 static void ttlCommand(redisClient
*c
) {
5540 expire
= getExpire(c
->db
,c
->argv
[1]);
5542 ttl
= (int) (expire
-time(NULL
));
5543 if (ttl
< 0) ttl
= -1;
5545 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",ttl
));
5548 /* ================================ MULTI/EXEC ============================== */
5550 /* Client state initialization for MULTI/EXEC */
5551 static void initClientMultiState(redisClient
*c
) {
5552 c
->mstate
.commands
= NULL
;
5553 c
->mstate
.count
= 0;
5556 /* Release all the resources associated with MULTI/EXEC state */
5557 static void freeClientMultiState(redisClient
*c
) {
5560 for (j
= 0; j
< c
->mstate
.count
; j
++) {
5562 multiCmd
*mc
= c
->mstate
.commands
+j
;
5564 for (i
= 0; i
< mc
->argc
; i
++)
5565 decrRefCount(mc
->argv
[i
]);
5568 zfree(c
->mstate
.commands
);
5571 /* Add a new command into the MULTI commands queue */
5572 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
) {
5576 c
->mstate
.commands
= zrealloc(c
->mstate
.commands
,
5577 sizeof(multiCmd
)*(c
->mstate
.count
+1));
5578 mc
= c
->mstate
.commands
+c
->mstate
.count
;
5581 mc
->argv
= zmalloc(sizeof(robj
*)*c
->argc
);
5582 memcpy(mc
->argv
,c
->argv
,sizeof(robj
*)*c
->argc
);
5583 for (j
= 0; j
< c
->argc
; j
++)
5584 incrRefCount(mc
->argv
[j
]);
5588 static void multiCommand(redisClient
*c
) {
5589 c
->flags
|= REDIS_MULTI
;
5590 addReply(c
,shared
.ok
);
5593 static void execCommand(redisClient
*c
) {
5598 if (!(c
->flags
& REDIS_MULTI
)) {
5599 addReplySds(c
,sdsnew("-ERR EXEC without MULTI\r\n"));
5603 orig_argv
= c
->argv
;
5604 orig_argc
= c
->argc
;
5605 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->mstate
.count
));
5606 for (j
= 0; j
< c
->mstate
.count
; j
++) {
5607 c
->argc
= c
->mstate
.commands
[j
].argc
;
5608 c
->argv
= c
->mstate
.commands
[j
].argv
;
5609 call(c
,c
->mstate
.commands
[j
].cmd
);
5611 c
->argv
= orig_argv
;
5612 c
->argc
= orig_argc
;
5613 freeClientMultiState(c
);
5614 initClientMultiState(c
);
5615 c
->flags
&= (~REDIS_MULTI
);
5618 /* =========================== Blocking Operations ========================= */
5620 /* Currently Redis blocking operations support is limited to list POP ops,
5621 * so the current implementation is not fully generic, but it is also not
5622 * completely specific so it will not require a rewrite to support new
5623 * kind of blocking operations in the future.
5625 * Still it's important to note that list blocking operations can be already
5626 * used as a notification mechanism in order to implement other blocking
5627 * operations at application level, so there must be a very strong evidence
5628 * of usefulness and generality before new blocking operations are implemented.
5630 * This is how the current blocking POP works, we use BLPOP as example:
5631 * - If the user calls BLPOP and the key exists and contains a non empty list
5632 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
5633 * if there is not to block.
5634 * - If instead BLPOP is called and the key does not exists or the list is
5635 * empty we need to block. In order to do so we remove the notification for
5636 * new data to read in the client socket (so that we'll not serve new
5637 * requests if the blocking request is not served). Also we put the client
5638 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
5639 * blocking for this keys.
5640 * - If a PUSH operation against a key with blocked clients waiting is
5641 * performed, we serve the first in the list: basically instead to push
5642 * the new element inside the list we return it to the (first / oldest)
5643 * blocking client, unblock the client, and remove it form the list.
5645 * The above comment and the source code should be enough in order to understand
5646 * the implementation and modify / fix it later.
5649 /* Set a client in blocking mode for the specified key, with the specified
5651 static void blockForKeys(redisClient
*c
, robj
**keys
, int numkeys
, time_t timeout
) {
5656 c
->blockingkeys
= zmalloc(sizeof(robj
*)*numkeys
);
5657 c
->blockingkeysnum
= numkeys
;
5658 c
->blockingto
= timeout
;
5659 for (j
= 0; j
< numkeys
; j
++) {
5660 /* Add the key in the client structure, to map clients -> keys */
5661 c
->blockingkeys
[j
] = keys
[j
];
5662 incrRefCount(keys
[j
]);
5664 /* And in the other "side", to map keys -> clients */
5665 de
= dictFind(c
->db
->blockingkeys
,keys
[j
]);
5669 /* For every key we take a list of clients blocked for it */
5671 retval
= dictAdd(c
->db
->blockingkeys
,keys
[j
],l
);
5672 incrRefCount(keys
[j
]);
5673 assert(retval
== DICT_OK
);
5675 l
= dictGetEntryVal(de
);
5677 listAddNodeTail(l
,c
);
5679 /* Mark the client as a blocked client */
5680 c
->flags
|= REDIS_BLOCKED
;
5681 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
5682 server
.blockedclients
++;
5685 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
5686 static void unblockClient(redisClient
*c
) {
5691 assert(c
->blockingkeys
!= NULL
);
5692 /* The client may wait for multiple keys, so unblock it for every key. */
5693 for (j
= 0; j
< c
->blockingkeysnum
; j
++) {
5694 /* Remove this client from the list of clients waiting for this key. */
5695 de
= dictFind(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
5697 l
= dictGetEntryVal(de
);
5698 listDelNode(l
,listSearchKey(l
,c
));
5699 /* If the list is empty we need to remove it to avoid wasting memory */
5700 if (listLength(l
) == 0)
5701 dictDelete(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
5702 decrRefCount(c
->blockingkeys
[j
]);
5704 /* Cleanup the client structure */
5705 zfree(c
->blockingkeys
);
5706 c
->blockingkeys
= NULL
;
5707 c
->flags
&= (~REDIS_BLOCKED
);
5708 server
.blockedclients
--;
5709 /* Ok now we are ready to get read events from socket, note that we
5710 * can't trap errors here as it's possible that unblockClients() is
5711 * called from freeClient() itself, and the only thing we can do
5712 * if we failed to register the READABLE event is to kill the client.
5713 * Still the following function should never fail in the real world as
5714 * we are sure the file descriptor is sane, and we exit on out of mem. */
5715 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
, readQueryFromClient
, c
);
5716 /* As a final step we want to process data if there is some command waiting
5717 * in the input buffer. Note that this is safe even if unblockClient()
5718 * gets called from freeClient() because freeClient() will be smart
5719 * enough to call this function *after* c->querybuf was set to NULL. */
5720 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0) processInputBuffer(c
);
5723 /* This should be called from any function PUSHing into lists.
5724 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
5725 * 'ele' is the element pushed.
5727 * If the function returns 0 there was no client waiting for a list push
5730 * If the function returns 1 there was a client waiting for a list push
5731 * against this key, the element was passed to this client thus it's not
5732 * needed to actually add it to the list and the caller should return asap. */
5733 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
) {
5734 struct dictEntry
*de
;
5735 redisClient
*receiver
;
5739 de
= dictFind(c
->db
->blockingkeys
,key
);
5740 if (de
== NULL
) return 0;
5741 l
= dictGetEntryVal(de
);
5744 receiver
= ln
->value
;
5746 addReplySds(receiver
,sdsnew("*2\r\n"));
5747 addReplyBulkLen(receiver
,key
);
5748 addReply(receiver
,key
);
5749 addReply(receiver
,shared
.crlf
);
5750 addReplyBulkLen(receiver
,ele
);
5751 addReply(receiver
,ele
);
5752 addReply(receiver
,shared
.crlf
);
5753 unblockClient(receiver
);
5757 /* Blocking RPOP/LPOP */
5758 static void blockingPopGenericCommand(redisClient
*c
, int where
) {
5763 for (j
= 1; j
< c
->argc
-1; j
++) {
5764 o
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
5766 if (o
->type
!= REDIS_LIST
) {
5767 addReply(c
,shared
.wrongtypeerr
);
5770 list
*list
= o
->ptr
;
5771 if (listLength(list
) != 0) {
5772 /* If the list contains elements fall back to the usual
5773 * non-blocking POP operation */
5774 robj
*argv
[2], **orig_argv
;
5777 /* We need to alter the command arguments before to call
5778 * popGenericCommand() as the command takes a single key. */
5779 orig_argv
= c
->argv
;
5780 orig_argc
= c
->argc
;
5781 argv
[1] = c
->argv
[j
];
5785 /* Also the return value is different, we need to output
5786 * the multi bulk reply header and the key name. The
5787 * "real" command will add the last element (the value)
5788 * for us. If this souds like an hack to you it's just
5789 * because it is... */
5790 addReplySds(c
,sdsnew("*2\r\n"));
5791 addReplyBulkLen(c
,argv
[1]);
5792 addReply(c
,argv
[1]);
5793 addReply(c
,shared
.crlf
);
5794 popGenericCommand(c
,where
);
5796 /* Fix the client structure with the original stuff */
5797 c
->argv
= orig_argv
;
5798 c
->argc
= orig_argc
;
5804 /* If the list is empty or the key does not exists we must block */
5805 timeout
= strtol(c
->argv
[c
->argc
-1]->ptr
,NULL
,10);
5806 if (timeout
> 0) timeout
+= time(NULL
);
5807 blockForKeys(c
,c
->argv
+1,c
->argc
-2,timeout
);
5810 static void blpopCommand(redisClient
*c
) {
5811 blockingPopGenericCommand(c
,REDIS_HEAD
);
5814 static void brpopCommand(redisClient
*c
) {
5815 blockingPopGenericCommand(c
,REDIS_TAIL
);
5818 /* =============================== Replication ============================= */
5820 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
5821 ssize_t nwritten
, ret
= size
;
5822 time_t start
= time(NULL
);
5826 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
5827 nwritten
= write(fd
,ptr
,size
);
5828 if (nwritten
== -1) return -1;
5832 if ((time(NULL
)-start
) > timeout
) {
5840 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
5841 ssize_t nread
, totread
= 0;
5842 time_t start
= time(NULL
);
5846 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
5847 nread
= read(fd
,ptr
,size
);
5848 if (nread
== -1) return -1;
5853 if ((time(NULL
)-start
) > timeout
) {
5861 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
5868 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
5871 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
5882 static void syncCommand(redisClient
*c
) {
5883 /* ignore SYNC if aleady slave or in monitor mode */
5884 if (c
->flags
& REDIS_SLAVE
) return;
5886 /* SYNC can't be issued when the server has pending data to send to
5887 * the client about already issued commands. We need a fresh reply
5888 * buffer registering the differences between the BGSAVE and the current
5889 * dataset, so that we can copy to other slaves if needed. */
5890 if (listLength(c
->reply
) != 0) {
5891 addReplySds(c
,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
5895 redisLog(REDIS_NOTICE
,"Slave ask for synchronization");
5896 /* Here we need to check if there is a background saving operation
5897 * in progress, or if it is required to start one */
5898 if (server
.bgsavechildpid
!= -1) {
5899 /* Ok a background save is in progress. Let's check if it is a good
5900 * one for replication, i.e. if there is another slave that is
5901 * registering differences since the server forked to save */
5905 listRewind(server
.slaves
);
5906 while((ln
= listYield(server
.slaves
))) {
5908 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) break;
5911 /* Perfect, the server is already registering differences for
5912 * another slave. Set the right state, and copy the buffer. */
5913 listRelease(c
->reply
);
5914 c
->reply
= listDup(slave
->reply
);
5915 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
5916 redisLog(REDIS_NOTICE
,"Waiting for end of BGSAVE for SYNC");
5918 /* No way, we need to wait for the next BGSAVE in order to
5919 * register differences */
5920 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
5921 redisLog(REDIS_NOTICE
,"Waiting for next BGSAVE for SYNC");
5924 /* Ok we don't have a BGSAVE in progress, let's start one */
5925 redisLog(REDIS_NOTICE
,"Starting BGSAVE for SYNC");
5926 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
5927 redisLog(REDIS_NOTICE
,"Replication failed, can't BGSAVE");
5928 addReplySds(c
,sdsnew("-ERR Unalbe to perform background save\r\n"));
5931 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
5934 c
->flags
|= REDIS_SLAVE
;
5936 listAddNodeTail(server
.slaves
,c
);
5940 static void sendBulkToSlave(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
5941 redisClient
*slave
= privdata
;
5943 REDIS_NOTUSED(mask
);
5944 char buf
[REDIS_IOBUF_LEN
];
5945 ssize_t nwritten
, buflen
;
5947 if (slave
->repldboff
== 0) {
5948 /* Write the bulk write count before to transfer the DB. In theory here
5949 * we don't know how much room there is in the output buffer of the
5950 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
5951 * operations) will never be smaller than the few bytes we need. */
5954 bulkcount
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
5956 if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
))
5964 lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
);
5965 buflen
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
);
5967 redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s",
5968 (buflen
== 0) ? "premature EOF" : strerror(errno
));
5972 if ((nwritten
= write(fd
,buf
,buflen
)) == -1) {
5973 redisLog(REDIS_DEBUG
,"Write error sending DB to slave: %s",
5978 slave
->repldboff
+= nwritten
;
5979 if (slave
->repldboff
== slave
->repldbsize
) {
5980 close(slave
->repldbfd
);
5981 slave
->repldbfd
= -1;
5982 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
5983 slave
->replstate
= REDIS_REPL_ONLINE
;
5984 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
,
5985 sendReplyToClient
, slave
) == AE_ERR
) {
5989 addReplySds(slave
,sdsempty());
5990 redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded");
5994 /* This function is called at the end of every backgrond saving.
5995 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
5996 * otherwise REDIS_ERR is passed to the function.
5998 * The goal of this function is to handle slaves waiting for a successful
5999 * background saving in order to perform non-blocking synchronization. */
6000 static void updateSlavesWaitingBgsave(int bgsaveerr
) {
6002 int startbgsave
= 0;
6004 listRewind(server
.slaves
);
6005 while((ln
= listYield(server
.slaves
))) {
6006 redisClient
*slave
= ln
->value
;
6008 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) {
6010 slave
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6011 } else if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) {
6012 struct redis_stat buf
;
6014 if (bgsaveerr
!= REDIS_OK
) {
6016 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error");
6019 if ((slave
->repldbfd
= open(server
.dbfilename
,O_RDONLY
)) == -1 ||
6020 redis_fstat(slave
->repldbfd
,&buf
) == -1) {
6022 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
));
6025 slave
->repldboff
= 0;
6026 slave
->repldbsize
= buf
.st_size
;
6027 slave
->replstate
= REDIS_REPL_SEND_BULK
;
6028 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
6029 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, sendBulkToSlave
, slave
) == AE_ERR
) {
6036 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
6037 listRewind(server
.slaves
);
6038 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed");
6039 while((ln
= listYield(server
.slaves
))) {
6040 redisClient
*slave
= ln
->value
;
6042 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
)
6049 static int syncWithMaster(void) {
6050 char buf
[1024], tmpfile
[256], authcmd
[1024];
6052 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
6056 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
6061 /* AUTH with the master if required. */
6062 if(server
.masterauth
) {
6063 snprintf(authcmd
, 1024, "AUTH %s\r\n", server
.masterauth
);
6064 if (syncWrite(fd
, authcmd
, strlen(server
.masterauth
)+7, 5) == -1) {
6066 redisLog(REDIS_WARNING
,"Unable to AUTH to MASTER: %s",
6070 /* Read the AUTH result. */
6071 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6073 redisLog(REDIS_WARNING
,"I/O error reading auth result from MASTER: %s",
6077 if (buf
[0] != '+') {
6079 redisLog(REDIS_WARNING
,"Cannot AUTH to MASTER, is the masterauth password correct?");
6084 /* Issue the SYNC command */
6085 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
6087 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
6091 /* Read the bulk write count */
6092 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6094 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
6098 if (buf
[0] != '$') {
6100 redisLog(REDIS_WARNING
,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
6103 dumpsize
= atoi(buf
+1);
6104 redisLog(REDIS_NOTICE
,"Receiving %d bytes data dump from MASTER",dumpsize
);
6105 /* Read the bulk write data on a temp file */
6106 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
6107 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644);
6110 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
6114 int nread
, nwritten
;
6116 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
6118 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
6124 nwritten
= write(dfd
,buf
,nread
);
6125 if (nwritten
== -1) {
6126 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
6134 if (rename(tmpfile
,server
.dbfilename
) == -1) {
6135 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
6141 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
6142 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
6146 server
.master
= createClient(fd
);
6147 server
.master
->flags
|= REDIS_MASTER
;
6148 server
.master
->authenticated
= 1;
6149 server
.replstate
= REDIS_REPL_CONNECTED
;
6153 static void slaveofCommand(redisClient
*c
) {
6154 if (!strcasecmp(c
->argv
[1]->ptr
,"no") &&
6155 !strcasecmp(c
->argv
[2]->ptr
,"one")) {
6156 if (server
.masterhost
) {
6157 sdsfree(server
.masterhost
);
6158 server
.masterhost
= NULL
;
6159 if (server
.master
) freeClient(server
.master
);
6160 server
.replstate
= REDIS_REPL_NONE
;
6161 redisLog(REDIS_NOTICE
,"MASTER MODE enabled (user request)");
6164 sdsfree(server
.masterhost
);
6165 server
.masterhost
= sdsdup(c
->argv
[1]->ptr
);
6166 server
.masterport
= atoi(c
->argv
[2]->ptr
);
6167 if (server
.master
) freeClient(server
.master
);
6168 server
.replstate
= REDIS_REPL_CONNECT
;
6169 redisLog(REDIS_NOTICE
,"SLAVE OF %s:%d enabled (user request)",
6170 server
.masterhost
, server
.masterport
);
6172 addReply(c
,shared
.ok
);
6175 /* ============================ Maxmemory directive ======================== */
6177 /* This function gets called when 'maxmemory' is set on the config file to limit
6178 * the max memory used by the server, and we are out of memory.
6179 * This function will try to, in order:
6181 * - Free objects from the free list
6182 * - Try to remove keys with an EXPIRE set
6184 * It is not possible to free enough memory to reach used-memory < maxmemory
6185 * the server will start refusing commands that will enlarge even more the
6188 static void freeMemoryIfNeeded(void) {
6189 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
6190 if (listLength(server
.objfreelist
)) {
6193 listNode
*head
= listFirst(server
.objfreelist
);
6194 o
= listNodeValue(head
);
6195 listDelNode(server
.objfreelist
,head
);
6198 int j
, k
, freed
= 0;
6200 for (j
= 0; j
< server
.dbnum
; j
++) {
6202 robj
*minkey
= NULL
;
6203 struct dictEntry
*de
;
6205 if (dictSize(server
.db
[j
].expires
)) {
6207 /* From a sample of three keys drop the one nearest to
6208 * the natural expire */
6209 for (k
= 0; k
< 3; k
++) {
6212 de
= dictGetRandomKey(server
.db
[j
].expires
);
6213 t
= (time_t) dictGetEntryVal(de
);
6214 if (minttl
== -1 || t
< minttl
) {
6215 minkey
= dictGetEntryKey(de
);
6219 deleteKey(server
.db
+j
,minkey
);
6222 if (!freed
) return; /* nothing to free... */
6227 /* ============================== Append Only file ========================== */
6229 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
6230 sds buf
= sdsempty();
6236 /* The DB this command was targetting is not the same as the last command
6237 * we appendend. To issue a SELECT command is needed. */
6238 if (dictid
!= server
.appendseldb
) {
6241 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
6242 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
6243 (unsigned long)strlen(seldb
),seldb
);
6244 server
.appendseldb
= dictid
;
6247 /* "Fix" the argv vector if the command is EXPIRE. We want to translate
6248 * EXPIREs into EXPIREATs calls */
6249 if (cmd
->proc
== expireCommand
) {
6252 tmpargv
[0] = createStringObject("EXPIREAT",8);
6253 tmpargv
[1] = argv
[1];
6254 incrRefCount(argv
[1]);
6255 when
= time(NULL
)+strtol(argv
[2]->ptr
,NULL
,10);
6256 tmpargv
[2] = createObject(REDIS_STRING
,
6257 sdscatprintf(sdsempty(),"%ld",when
));
6261 /* Append the actual command */
6262 buf
= sdscatprintf(buf
,"*%d\r\n",argc
);
6263 for (j
= 0; j
< argc
; j
++) {
6266 o
= getDecodedObject(o
);
6267 buf
= sdscatprintf(buf
,"$%lu\r\n",(unsigned long)sdslen(o
->ptr
));
6268 buf
= sdscatlen(buf
,o
->ptr
,sdslen(o
->ptr
));
6269 buf
= sdscatlen(buf
,"\r\n",2);
6273 /* Free the objects from the modified argv for EXPIREAT */
6274 if (cmd
->proc
== expireCommand
) {
6275 for (j
= 0; j
< 3; j
++)
6276 decrRefCount(argv
[j
]);
6279 /* We want to perform a single write. This should be guaranteed atomic
6280 * at least if the filesystem we are writing is a real physical one.
6281 * While this will save us against the server being killed I don't think
6282 * there is much to do about the whole server stopping for power problems
6284 nwritten
= write(server
.appendfd
,buf
,sdslen(buf
));
6285 if (nwritten
!= (signed)sdslen(buf
)) {
6286 /* Ooops, we are in troubles. The best thing to do for now is
6287 * to simply exit instead to give the illusion that everything is
6288 * working as expected. */
6289 if (nwritten
== -1) {
6290 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
6292 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
6296 /* If a background append only file rewriting is in progress we want to
6297 * accumulate the differences between the child DB and the current one
6298 * in a buffer, so that when the child process will do its work we
6299 * can append the differences to the new append only file. */
6300 if (server
.bgrewritechildpid
!= -1)
6301 server
.bgrewritebuf
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
));
6305 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
||
6306 (server
.appendfsync
== APPENDFSYNC_EVERYSEC
&&
6307 now
-server
.lastfsync
> 1))
6309 fsync(server
.appendfd
); /* Let's try to get this data on the disk */
6310 server
.lastfsync
= now
;
6314 /* In Redis commands are always executed in the context of a client, so in
6315 * order to load the append only file we need to create a fake client. */
6316 static struct redisClient
*createFakeClient(void) {
6317 struct redisClient
*c
= zmalloc(sizeof(*c
));
6321 c
->querybuf
= sdsempty();
6325 /* We set the fake client as a slave waiting for the synchronization
6326 * so that Redis will not try to send replies to this client. */
6327 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
6328 c
->reply
= listCreate();
6329 listSetFreeMethod(c
->reply
,decrRefCount
);
6330 listSetDupMethod(c
->reply
,dupClientReplyValue
);
6334 static void freeFakeClient(struct redisClient
*c
) {
6335 sdsfree(c
->querybuf
);
6336 listRelease(c
->reply
);
6340 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
6341 * error (the append only file is zero-length) REDIS_ERR is returned. On
6342 * fatal error an error message is logged and the program exists. */
6343 int loadAppendOnlyFile(char *filename
) {
6344 struct redisClient
*fakeClient
;
6345 FILE *fp
= fopen(filename
,"r");
6346 struct redis_stat sb
;
6348 if (redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0)
6352 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
6356 fakeClient
= createFakeClient();
6363 struct redisCommand
*cmd
;
6365 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
6371 if (buf
[0] != '*') goto fmterr
;
6373 argv
= zmalloc(sizeof(robj
*)*argc
);
6374 for (j
= 0; j
< argc
; j
++) {
6375 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
6376 if (buf
[0] != '$') goto fmterr
;
6377 len
= strtol(buf
+1,NULL
,10);
6378 argsds
= sdsnewlen(NULL
,len
);
6379 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
6380 argv
[j
] = createObject(REDIS_STRING
,argsds
);
6381 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
6384 /* Command lookup */
6385 cmd
= lookupCommand(argv
[0]->ptr
);
6387 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
6390 /* Try object sharing and encoding */
6391 if (server
.shareobjects
) {
6393 for(j
= 1; j
< argc
; j
++)
6394 argv
[j
] = tryObjectSharing(argv
[j
]);
6396 if (cmd
->flags
& REDIS_CMD_BULK
)
6397 tryObjectEncoding(argv
[argc
-1]);
6398 /* Run the command in the context of a fake client */
6399 fakeClient
->argc
= argc
;
6400 fakeClient
->argv
= argv
;
6401 cmd
->proc(fakeClient
);
6402 /* Discard the reply objects list from the fake client */
6403 while(listLength(fakeClient
->reply
))
6404 listDelNode(fakeClient
->reply
,listFirst(fakeClient
->reply
));
6405 /* Clean up, ready for the next command */
6406 for (j
= 0; j
< argc
; j
++) decrRefCount(argv
[j
]);
6410 freeFakeClient(fakeClient
);
6415 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
6417 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
6421 redisLog(REDIS_WARNING
,"Bad file format reading the append only file");
6425 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
6426 static int fwriteBulk(FILE *fp
, robj
*obj
) {
6428 obj
= getDecodedObject(obj
);
6429 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(long)sdslen(obj
->ptr
));
6430 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) goto err
;
6431 if (sdslen(obj
->ptr
) && fwrite(obj
->ptr
,sdslen(obj
->ptr
),1,fp
) == 0)
6433 if (fwrite("\r\n",2,1,fp
) == 0) goto err
;
6441 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
6442 static int fwriteBulkDouble(FILE *fp
, double d
) {
6443 char buf
[128], dbuf
[128];
6445 snprintf(dbuf
,sizeof(dbuf
),"%.17g\r\n",d
);
6446 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(dbuf
)-2);
6447 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
6448 if (fwrite(dbuf
,strlen(dbuf
),1,fp
) == 0) return 0;
6452 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
6453 static int fwriteBulkLong(FILE *fp
, long l
) {
6454 char buf
[128], lbuf
[128];
6456 snprintf(lbuf
,sizeof(lbuf
),"%ld\r\n",l
);
6457 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(lbuf
)-2);
6458 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
6459 if (fwrite(lbuf
,strlen(lbuf
),1,fp
) == 0) return 0;
6463 /* Write a sequence of commands able to fully rebuild the dataset into
6464 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
6465 static int rewriteAppendOnlyFile(char *filename
) {
6466 dictIterator
*di
= NULL
;
6471 time_t now
= time(NULL
);
6473 /* Note that we have to use a different temp name here compared to the
6474 * one used by rewriteAppendOnlyFileBackground() function. */
6475 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
6476 fp
= fopen(tmpfile
,"w");
6478 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
6481 for (j
= 0; j
< server
.dbnum
; j
++) {
6482 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
6483 redisDb
*db
= server
.db
+j
;
6485 if (dictSize(d
) == 0) continue;
6486 di
= dictGetIterator(d
);
6492 /* SELECT the new DB */
6493 if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
;
6494 if (fwriteBulkLong(fp
,j
) == 0) goto werr
;
6496 /* Iterate this DB writing every entry */
6497 while((de
= dictNext(di
)) != NULL
) {
6498 robj
*key
= dictGetEntryKey(de
);
6499 robj
*o
= dictGetEntryVal(de
);
6500 time_t expiretime
= getExpire(db
,key
);
6502 /* Save the key and associated value */
6503 if (o
->type
== REDIS_STRING
) {
6504 /* Emit a SET command */
6505 char cmd
[]="*3\r\n$3\r\nSET\r\n";
6506 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6508 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6509 if (fwriteBulk(fp
,o
) == 0) goto werr
;
6510 } else if (o
->type
== REDIS_LIST
) {
6511 /* Emit the RPUSHes needed to rebuild the list */
6512 list
*list
= o
->ptr
;
6516 while((ln
= listYield(list
))) {
6517 char cmd
[]="*3\r\n$5\r\nRPUSH\r\n";
6518 robj
*eleobj
= listNodeValue(ln
);
6520 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6521 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6522 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6524 } else if (o
->type
== REDIS_SET
) {
6525 /* Emit the SADDs needed to rebuild the set */
6527 dictIterator
*di
= dictGetIterator(set
);
6530 while((de
= dictNext(di
)) != NULL
) {
6531 char cmd
[]="*3\r\n$4\r\nSADD\r\n";
6532 robj
*eleobj
= dictGetEntryKey(de
);
6534 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6535 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6536 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6538 dictReleaseIterator(di
);
6539 } else if (o
->type
== REDIS_ZSET
) {
6540 /* Emit the ZADDs needed to rebuild the sorted set */
6542 dictIterator
*di
= dictGetIterator(zs
->dict
);
6545 while((de
= dictNext(di
)) != NULL
) {
6546 char cmd
[]="*4\r\n$4\r\nZADD\r\n";
6547 robj
*eleobj
= dictGetEntryKey(de
);
6548 double *score
= dictGetEntryVal(de
);
6550 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6551 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6552 if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
;
6553 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6555 dictReleaseIterator(di
);
6557 redisAssert(0 != 0);
6559 /* Save the expire time */
6560 if (expiretime
!= -1) {
6561 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n";
6562 /* If this key is already expired skip it */
6563 if (expiretime
< now
) continue;
6564 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6565 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6566 if (fwriteBulkLong(fp
,expiretime
) == 0) goto werr
;
6569 dictReleaseIterator(di
);
6572 /* Make sure data will not remain on the OS's output buffers */
6577 /* Use RENAME to make sure the DB file is changed atomically only
6578 * if the generate DB file is ok. */
6579 if (rename(tmpfile
,filename
) == -1) {
6580 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
6584 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
6590 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
6591 if (di
) dictReleaseIterator(di
);
6595 /* This is how rewriting of the append only file in background works:
6597 * 1) The user calls BGREWRITEAOF
6598 * 2) Redis calls this function, that forks():
6599 * 2a) the child rewrite the append only file in a temp file.
6600 * 2b) the parent accumulates differences in server.bgrewritebuf.
6601 * 3) When the child finished '2a' exists.
6602 * 4) The parent will trap the exit code, if it's OK, will append the
6603 * data accumulated into server.bgrewritebuf into the temp file, and
6604 * finally will rename(2) the temp file in the actual file name.
6605 * The the new file is reopened as the new append only file. Profit!
6607 static int rewriteAppendOnlyFileBackground(void) {
6610 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
6611 if ((childpid
= fork()) == 0) {
6616 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
6617 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
6624 if (childpid
== -1) {
6625 redisLog(REDIS_WARNING
,
6626 "Can't rewrite append only file in background: fork: %s",
6630 redisLog(REDIS_NOTICE
,
6631 "Background append only file rewriting started by pid %d",childpid
);
6632 server
.bgrewritechildpid
= childpid
;
6633 /* We set appendseldb to -1 in order to force the next call to the
6634 * feedAppendOnlyFile() to issue a SELECT command, so the differences
6635 * accumulated by the parent into server.bgrewritebuf will start
6636 * with a SELECT statement and it will be safe to merge. */
6637 server
.appendseldb
= -1;
6640 return REDIS_OK
; /* unreached */
6643 static void bgrewriteaofCommand(redisClient
*c
) {
6644 if (server
.bgrewritechildpid
!= -1) {
6645 addReplySds(c
,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
6648 if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
6649 char *status
= "+Background append only file rewriting started\r\n";
6650 addReplySds(c
,sdsnew(status
));
6652 addReply(c
,shared
.err
);
6656 static void aofRemoveTempFile(pid_t childpid
) {
6659 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
6663 /* =============================== Virtual Memory =========================== */
6664 static void vmInit(void) {
6667 server
.vm_fp
= fopen("/tmp/redisvm","w+b");
6668 if (server
.vm_fp
== NULL
) {
6669 redisLog(REDIS_WARNING
,"Impossible to open the swap file. Exiting.");
6672 server
.vm_fd
= fileno(server
.vm_fp
);
6673 server
.vm_next_page
= 0;
6674 server
.vm_near_pages
= 0;
6675 totsize
= server
.vm_pages
*server
.vm_page_size
;
6676 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
6677 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
6678 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
6682 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
6684 server
.vm_bitmap
= zmalloc((server
.vm_pages
+7)/8);
6685 redisLog(REDIS_DEBUG
,"Allocated %lld bytes page table for %lld pages",
6686 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
6687 memset(server
.vm_bitmap
,0,(server
.vm_pages
+7)/8);
6688 /* Try to remove the swap file, so the OS will really delete it from the
6689 * file system when Redis exists. */
6690 unlink("/tmp/redisvm");
6693 /* Mark the page as used */
6694 static void vmMarkPageUsed(off_t page
) {
6695 off_t byte
= page
/8;
6697 server
.vm_bitmap
[byte
] |= 1<<bit
;
6698 printf("Mark used: %lld (byte:%lld bit:%d)\n", (long long)page
,
6699 (long long)byte
, bit
);
6702 /* Mark N contiguous pages as used, with 'page' being the first. */
6703 static void vmMarkPagesUsed(off_t page
, off_t count
) {
6706 for (j
= 0; j
< count
; j
++)
6707 vmMarkPageUsed(page
+j
);
6710 /* Mark the page as free */
6711 static void vmMarkPageFree(off_t page
) {
6712 off_t byte
= page
/8;
6714 server
.vm_bitmap
[byte
] &= ~(1<<bit
);
6717 /* Mark N contiguous pages as free, with 'page' being the first. */
6718 static void vmMarkPagesFree(off_t page
, off_t count
) {
6721 for (j
= 0; j
< count
; j
++)
6722 vmMarkPageFree(page
+j
);
6725 /* Test if the page is free */
6726 static int vmFreePage(off_t page
) {
6727 off_t byte
= page
/8;
6729 return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0;
6732 /* Find N contiguous free pages storing the first page of the cluster in *first.
6733 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
6734 * REDIS_ERR is returned.
6736 * This function uses a simple algorithm: we try to allocate
6737 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
6738 * again from the start of the swap file searching for free spaces.
6740 * If it looks pretty clear that there are no free pages near our offset
6741 * we try to find less populated places doing a forward jump of
6742 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
6743 * without hurry, and then we jump again and so forth...
6745 * This function can be improved using a free list to avoid to guess
6746 * too much, since we could collect data about freed pages.
6748 * note: I implemented this function just after watching an episode of
6749 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
6751 static int vmFindContiguousPages(off_t
*first
, int n
) {
6752 off_t base
, offset
= 0, since_jump
= 0, numfree
= 0;
6754 if (server
.vm_near_pages
== REDIS_VM_MAX_NEAR_PAGES
) {
6755 server
.vm_near_pages
= 0;
6756 server
.vm_next_page
= 0;
6758 server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */
6759 base
= server
.vm_next_page
;
6761 while(offset
< server
.vm_pages
) {
6762 off_t
this = base
+offset
;
6764 printf("THIS: %lld (%c)\n", (long long) this, vmFreePage(this) ? 'F' : 'X');
6765 /* If we overflow, restart from page zero */
6766 if (this >= server
.vm_pages
) {
6767 this -= server
.vm_pages
;
6769 /* Just overflowed, what we found on tail is no longer
6770 * interesting, as it's no longer contiguous. */
6774 if (vmFreePage(this)) {
6775 /* This is a free page */
6777 /* Already got N free pages? Return to the caller, with success */
6779 *first
= this-(n
-1);
6780 server
.vm_next_page
= this+1;
6784 /* The current one is not a free page */
6788 /* Fast-forward if the current page is not free and we already
6789 * searched enough near this place. */
6791 if (!numfree
&& since_jump
>= REDIS_VM_MAX_RANDOM_JUMP
/4) {
6792 offset
+= random() % REDIS_VM_MAX_RANDOM_JUMP
;
6794 /* Note that even if we rewind after the jump, we are don't need
6795 * to make sure numfree is set to zero as we only jump *if* it
6796 * is set to zero. */
6798 /* Otherwise just check the next page */
6805 /* Swap the 'val' object relative to 'key' into disk. Store all the information
6806 * needed to later retrieve the object into the key object.
6807 * If we can't find enough contiguous empty pages to swap the object on disk
6808 * REDIS_ERR is returned. */
6809 static int vmSwapObject(robj
*key
, robj
*val
) {
6810 off_t pages
= rdbSavedObjectPages(val
);
6813 assert(key
->storage
== REDIS_VM_MEMORY
);
6814 assert(key
->refcount
== 1);
6815 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return REDIS_ERR
;
6816 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
6817 redisLog(REDIS_WARNING
,
6818 "Critical VM problem in vmSwapObject(): can't seek: %s",
6822 rdbSaveObject(server
.vm_fp
,val
);
6823 key
->vm
.page
= page
;
6824 key
->vm
.usedpages
= pages
;
6825 key
->storage
= REDIS_VM_SWAPPED
;
6826 key
->vtype
= val
->type
;
6827 decrRefCount(val
); /* Deallocate the object from memory. */
6828 vmMarkPagesUsed(page
,pages
);
6829 redisLog(REDIS_DEBUG
,"VM: object %s swapped out at %lld (%lld pages)",
6830 (unsigned char*) key
->ptr
,
6831 (unsigned long long) page
, (unsigned long long) pages
);
6835 /* Load the value object relative to the 'key' object from swap to memory.
6836 * The newly allocated object is returned. */
6837 static robj
*vmLoadObject(robj
*key
) {
6840 assert(key
->storage
== REDIS_VM_SWAPPED
);
6841 if (fseeko(server
.vm_fp
,key
->vm
.page
*server
.vm_page_size
,SEEK_SET
) == -1) {
6842 redisLog(REDIS_WARNING
,
6843 "Unrecoverable VM problem in vmLoadObject(): can't seek: %s",
6847 val
= rdbLoadObject(key
->vtype
,server
.vm_fp
);
6849 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmLoadObject(): can't load object from swap file: %s", strerror(errno
));
6852 key
->storage
= REDIS_VM_MEMORY
;
6853 key
->vm
.atime
= server
.unixtime
;
6854 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
6855 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk",
6856 (unsigned char*) key
->ptr
);
6860 /* How a good candidate is this object for swapping?
6861 * The better candidate it is, the greater the returned value.
6863 * Currently we try to perform a fast estimation of the object size in
6864 * memory, and combine it with aging informations.
6866 * Basically swappability = idle-time * log(estimated size)
6868 * Bigger objects are preferred over smaller objects, but not
6869 * proportionally, this is why we use the logarithm. This algorithm is
6870 * just a first try and will probably be tuned later. */
6871 static double computeObjectSwappability(robj
*o
) {
6872 time_t age
= server
.unixtime
- o
->vm
.atime
;
6876 struct dictEntry
*de
;
6879 if (age
<= 0) return 0;
6882 if (o
->encoding
!= REDIS_ENCODING_RAW
) {
6885 asize
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2;
6890 listNode
*ln
= listFirst(l
);
6892 asize
= sizeof(list
);
6894 robj
*ele
= ln
->value
;
6897 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
6898 (sizeof(*o
)+sdslen(ele
->ptr
)) :
6900 asize
+= (sizeof(listNode
)+elesize
)*listLength(l
);
6905 z
= (o
->type
== REDIS_ZSET
);
6906 d
= z
? ((zset
*)o
->ptr
)->dict
: o
->ptr
;
6908 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
6909 if (z
) asize
+= sizeof(zset
)-sizeof(dict
);
6914 de
= dictGetRandomKey(d
);
6915 ele
= dictGetEntryKey(de
);
6916 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
6917 (sizeof(*o
)+sdslen(ele
->ptr
)) :
6919 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
6920 if (z
) asize
+= sizeof(zskiplistNode
)*dictSize(d
);
6924 return (double)asize
*log(1+asize
);
6927 /* Try to swap an object that's a good candidate for swapping.
6928 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
6929 * to swap any object at all. */
6930 static int vmSwapOneObject(void) {
6932 struct dictEntry
*best
= NULL
;
6933 double best_swappability
= 0;
6936 for (j
= 0; j
< server
.dbnum
; j
++) {
6937 redisDb
*db
= server
.db
+j
;
6938 int maxtries
= 1000;
6940 if (dictSize(db
->dict
) == 0) continue;
6941 for (i
= 0; i
< 5; i
++) {
6943 double swappability
;
6945 if (maxtries
) maxtries
--;
6946 de
= dictGetRandomKey(db
->dict
);
6947 key
= dictGetEntryKey(de
);
6948 val
= dictGetEntryVal(de
);
6949 if (key
->storage
!= REDIS_VM_MEMORY
) {
6950 if (maxtries
) i
--; /* don't count this try */
6953 swappability
= computeObjectSwappability(val
);
6954 if (!best
|| swappability
> best_swappability
) {
6956 best_swappability
= swappability
;
6961 redisLog(REDIS_DEBUG
,"No swappable key found!");
6964 key
= dictGetEntryKey(best
);
6965 val
= dictGetEntryVal(best
);
6967 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f",
6968 key
->ptr
, best_swappability
);
6970 /* Unshare the key if needed */
6971 if (key
->refcount
> 1) {
6972 robj
*newkey
= dupStringObject(key
);
6974 key
= dictGetEntryKey(best
) = newkey
;
6977 if (vmSwapObject(key
,val
) == REDIS_OK
) {
6978 dictGetEntryVal(best
) = NULL
;
6985 /* ================================= Debugging ============================== */
6987 static void debugCommand(redisClient
*c
) {
6988 if (!strcasecmp(c
->argv
[1]->ptr
,"segfault")) {
6990 } else if (!strcasecmp(c
->argv
[1]->ptr
,"reload")) {
6991 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
6992 addReply(c
,shared
.err
);
6996 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
6997 addReply(c
,shared
.err
);
7000 redisLog(REDIS_WARNING
,"DB reloaded by DEBUG RELOAD");
7001 addReply(c
,shared
.ok
);
7002 } else if (!strcasecmp(c
->argv
[1]->ptr
,"loadaof")) {
7004 if (loadAppendOnlyFile(server
.appendfilename
) != REDIS_OK
) {
7005 addReply(c
,shared
.err
);
7008 redisLog(REDIS_WARNING
,"Append Only File loaded by DEBUG LOADAOF");
7009 addReply(c
,shared
.ok
);
7010 } else if (!strcasecmp(c
->argv
[1]->ptr
,"object") && c
->argc
== 3) {
7011 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
7015 addReply(c
,shared
.nokeyerr
);
7018 key
= dictGetEntryKey(de
);
7019 val
= dictGetEntryVal(de
);
7020 addReplySds(c
,sdscatprintf(sdsempty(),
7021 "+Key at:%p refcount:%d, value at:%p refcount:%d encoding:%d serializedlength:%lld\r\n",
7022 (void*)key
, key
->refcount
, (void*)val
, val
->refcount
,
7023 val
->encoding
, rdbSavedObjectLen(val
)));
7024 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapout") && c
->argc
== 3) {
7025 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
7028 if (!server
.vm_enabled
) {
7029 addReplySds(c
,sdsnew("-ERR Virtual Memory is disabled\r\n"));
7033 addReply(c
,shared
.nokeyerr
);
7036 key
= dictGetEntryKey(de
);
7037 val
= dictGetEntryVal(de
);
7038 /* If the key is shared we want to create a copy */
7039 if (key
->refcount
> 1) {
7040 robj
*newkey
= dupStringObject(key
);
7042 key
= dictGetEntryKey(de
) = newkey
;
7045 if (key
->storage
!= REDIS_VM_MEMORY
) {
7046 addReplySds(c
,sdsnew("-ERR This key is not in memory\r\n"));
7047 } else if (vmSwapObject(key
,val
) == REDIS_OK
) {
7048 dictGetEntryVal(de
) = NULL
;
7049 addReply(c
,shared
.ok
);
7051 addReply(c
,shared
.err
);
7054 addReplySds(c
,sdsnew(
7055 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPOUT <key>|RELOAD]\r\n"));
7059 static void _redisAssert(char *estr
) {
7060 redisLog(REDIS_WARNING
,"=== ASSERTION FAILED ===");
7061 redisLog(REDIS_WARNING
,"==> %s\n",estr
);
7062 #ifdef HAVE_BACKTRACE
7063 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
7068 /* =================================== Main! ================================ */
7071 int linuxOvercommitMemoryValue(void) {
7072 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
7076 if (fgets(buf
,64,fp
) == NULL
) {
7085 void linuxOvercommitMemoryWarning(void) {
7086 if (linuxOvercommitMemoryValue() == 0) {
7087 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.");
7090 #endif /* __linux__ */
7092 static void daemonize(void) {
7096 if (fork() != 0) exit(0); /* parent exits */
7097 printf("New pid: %d\n", getpid());
7098 setsid(); /* create a new session */
7100 /* Every output goes to /dev/null. If Redis is daemonized but
7101 * the 'logfile' is set to 'stdout' in the configuration file
7102 * it will not log at all. */
7103 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
7104 dup2(fd
, STDIN_FILENO
);
7105 dup2(fd
, STDOUT_FILENO
);
7106 dup2(fd
, STDERR_FILENO
);
7107 if (fd
> STDERR_FILENO
) close(fd
);
7109 /* Try to write the pid file */
7110 fp
= fopen(server
.pidfile
,"w");
7112 fprintf(fp
,"%d\n",getpid());
7117 int main(int argc
, char **argv
) {
7120 resetServerSaveParams();
7121 loadServerConfig(argv
[1]);
7122 } else if (argc
> 2) {
7123 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
7126 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'");
7128 if (server
.daemonize
) daemonize();
7130 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
7132 linuxOvercommitMemoryWarning();
7134 if (server
.appendonly
) {
7135 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
7136 redisLog(REDIS_NOTICE
,"DB loaded from append only file");
7138 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
7139 redisLog(REDIS_NOTICE
,"DB loaded from disk");
7141 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
7142 acceptHandler
, NULL
) == AE_ERR
) oom("creating file event");
7143 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
7145 aeDeleteEventLoop(server
.el
);
7149 /* ============================= Backtrace support ========================= */
7151 #ifdef HAVE_BACKTRACE
7152 static char *findFuncName(void *pointer
, unsigned long *offset
);
7154 static void *getMcontextEip(ucontext_t
*uc
) {
7155 #if defined(__FreeBSD__)
7156 return (void*) uc
->uc_mcontext
.mc_eip
;
7157 #elif defined(__dietlibc__)
7158 return (void*) uc
->uc_mcontext
.eip
;
7159 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
7161 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
7163 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
7165 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
7166 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
7167 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
7169 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
7171 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
7172 return (void*) uc
->uc_mcontext
.gregs
[REG_EIP
]; /* Linux 32/64 bit */
7173 #elif defined(__ia64__) /* Linux IA64 */
7174 return (void*) uc
->uc_mcontext
.sc_ip
;
7180 static void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
7182 char **messages
= NULL
;
7183 int i
, trace_size
= 0;
7184 unsigned long offset
=0;
7185 ucontext_t
*uc
= (ucontext_t
*) secret
;
7187 REDIS_NOTUSED(info
);
7189 redisLog(REDIS_WARNING
,
7190 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
7191 infostring
= genRedisInfoString();
7192 redisLog(REDIS_WARNING
, "%s",infostring
);
7193 /* It's not safe to sdsfree() the returned string under memory
7194 * corruption conditions. Let it leak as we are going to abort */
7196 trace_size
= backtrace(trace
, 100);
7197 /* overwrite sigaction with caller's address */
7198 if (getMcontextEip(uc
) != NULL
) {
7199 trace
[1] = getMcontextEip(uc
);
7201 messages
= backtrace_symbols(trace
, trace_size
);
7203 for (i
=1; i
<trace_size
; ++i
) {
7204 char *fn
= findFuncName(trace
[i
], &offset
), *p
;
7206 p
= strchr(messages
[i
],'+');
7207 if (!fn
|| (p
&& ((unsigned long)strtol(p
+1,NULL
,10)) < offset
)) {
7208 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
7210 redisLog(REDIS_WARNING
,"%d redis-server %p %s + %d", i
, trace
[i
], fn
, (unsigned int)offset
);
7213 /* free(messages); Don't call free() with possibly corrupted memory. */
7217 static void setupSigSegvAction(void) {
7218 struct sigaction act
;
7220 sigemptyset (&act
.sa_mask
);
7221 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
7222 * is used. Otherwise, sa_handler is used */
7223 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
7224 act
.sa_sigaction
= segvHandler
;
7225 sigaction (SIGSEGV
, &act
, NULL
);
7226 sigaction (SIGBUS
, &act
, NULL
);
7227 sigaction (SIGFPE
, &act
, NULL
);
7228 sigaction (SIGILL
, &act
, NULL
);
7229 sigaction (SIGBUS
, &act
, NULL
);
7233 #include "staticsymbols.h"
7234 /* This function try to convert a pointer into a function name. It's used in
7235 * oreder to provide a backtrace under segmentation fault that's able to
7236 * display functions declared as static (otherwise the backtrace is useless). */
7237 static char *findFuncName(void *pointer
, unsigned long *offset
){
7239 unsigned long off
, minoff
= 0;
7241 /* Try to match against the Symbol with the smallest offset */
7242 for (i
=0; symsTable
[i
].pointer
; i
++) {
7243 unsigned long lp
= (unsigned long) pointer
;
7245 if (lp
!= (unsigned long)-1 && lp
>= symsTable
[i
].pointer
) {
7246 off
=lp
-symsTable
[i
].pointer
;
7247 if (ret
< 0 || off
< minoff
) {
7253 if (ret
== -1) return NULL
;
7255 return symsTable
[ret
].name
;
7257 #else /* HAVE_BACKTRACE */
7258 static void setupSigSegvAction(void) {
7260 #endif /* HAVE_BACKTRACE */