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 "0.08"
44 #include <arpa/inet.h>
48 #include <sys/resource.h>
51 #include "ae.h" /* Event driven programming library */
52 #include "sds.h" /* Dynamic safe strings */
53 #include "anet.h" /* Networking the easy way */
54 #include "dict.h" /* Hash tables */
55 #include "adlist.h" /* Linked lists */
56 #include "zmalloc.h" /* total memory usage aware version of malloc/free */
62 /* Static server configuration */
63 #define REDIS_SERVERPORT 6379 /* TCP port */
64 #define REDIS_MAXIDLETIME (60*5) /* default client timeout */
65 #define REDIS_QUERYBUF_LEN 1024
66 #define REDIS_LOADBUF_LEN 1024
67 #define REDIS_MAX_ARGS 16
68 #define REDIS_DEFAULT_DBNUM 16
69 #define REDIS_CONFIGLINE_MAX 1024
70 #define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
71 #define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
73 /* Hash table parameters */
74 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
75 #define REDIS_HT_MINSLOTS 16384 /* Never resize the HT under this */
78 #define REDIS_CMD_BULK 1
79 #define REDIS_CMD_INLINE 2
82 #define REDIS_STRING 0
87 /* Object types only used for dumping to disk */
88 #define REDIS_SELECTDB 254
91 /* Defines related to the dump file format. To store 32 bits lengths for short
92 * keys requires a lot of space, so we check the most significant 2 bits of
93 * the first byte to interpreter the length:
95 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
96 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
97 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
98 * 11|000000 this means: specially encoded object will follow. The six bits
99 * number specify the kind of object that follows.
100 * See the REDIS_RDB_ENC_* defines.
102 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
103 * values, will fit inside. */
104 #define REDIS_RDB_6BITLEN 0
105 #define REDIS_RDB_14BITLEN 1
106 #define REDIS_RDB_32BITLEN 2
107 #define REDIS_RDB_64BITLEN 3
108 #define REDIS_RDB_LENERR UINT_MAX
110 /* When a length of a string object stored on disk has the first two bits
111 * set, the remaining two bits specify a special encoding for the object
112 * accordingly to the following defines: */
113 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
114 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
115 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
116 #define REDIS_RDB_ENC_FLZ 3 /* string compressed with FASTLZ */
119 #define REDIS_CLOSE 1 /* This client connection should be closed ASAP */
120 #define REDIS_SLAVE 2 /* This client is a slave server */
121 #define REDIS_MASTER 4 /* This client is a master server */
122 #define REDIS_MONITOR 8 /* This client is a slave monitor, see MONITOR */
124 /* Server replication state */
125 #define REDIS_REPL_NONE 0 /* No active replication */
126 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
127 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
129 /* List related stuff */
133 /* Sort operations */
134 #define REDIS_SORT_GET 0
135 #define REDIS_SORT_DEL 1
136 #define REDIS_SORT_INCR 2
137 #define REDIS_SORT_DECR 3
138 #define REDIS_SORT_ASC 4
139 #define REDIS_SORT_DESC 5
140 #define REDIS_SORTKEY_MAX 1024
143 #define REDIS_DEBUG 0
144 #define REDIS_NOTICE 1
145 #define REDIS_WARNING 2
147 /* Anti-warning macro... */
148 #define REDIS_NOTUSED(V) ((void) V)
150 /*================================= Data types ============================== */
152 /* A redis object, that is a type able to hold a string / list / set */
153 typedef struct redisObject
{
159 /* With multiplexing we need to take per-clinet state.
160 * Clients are taken in a liked list. */
161 typedef struct redisClient
{
166 robj
*argv
[REDIS_MAX_ARGS
];
168 int bulklen
; /* bulk read len. -1 if not in bulk read mode */
171 time_t lastinteraction
; /* time of the last interaction, used for timeout */
172 int flags
; /* REDIS_CLOSE | REDIS_SLAVE | REDIS_MONITOR */
173 int slaveseldb
; /* slave selected db, if this client is a slave */
174 int authenticated
; /* when requirepass is non-NULL */
182 /* Global server state structure */
188 unsigned int sharingpoolsize
;
189 long long dirty
; /* changes to DB from the last save */
191 list
*slaves
, *monitors
;
192 char neterr
[ANET_ERR_LEN
];
194 int cronloops
; /* number of times the cron function run */
195 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
196 time_t lastsave
; /* Unix time of last save succeeede */
197 int usedmemory
; /* Used memory in megabytes */
198 /* Fields used only for stats */
199 time_t stat_starttime
; /* server start time */
200 long long stat_numcommands
; /* number of processed commands */
201 long long stat_numconnections
; /* number of connections received */
209 int bgsaveinprogress
;
210 struct saveparam
*saveparams
;
217 /* Replication related */
223 /* Sort parameters - qsort_r() is only available under BSD so we
224 * have to take this state global, in order to pass it to sortCompare() */
230 typedef void redisCommandProc(redisClient
*c
);
231 struct redisCommand
{
233 redisCommandProc
*proc
;
238 typedef struct _redisSortObject
{
246 typedef struct _redisSortOperation
{
249 } redisSortOperation
;
251 struct sharedObjectsStruct
{
252 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
253 *colon
, *nullbulk
, *nullmultibulk
,
254 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
255 *outofrangeerr
, *plus
,
256 *select0
, *select1
, *select2
, *select3
, *select4
,
257 *select5
, *select6
, *select7
, *select8
, *select9
;
260 /*================================ Prototypes =============================== */
262 static void freeStringObject(robj
*o
);
263 static void freeListObject(robj
*o
);
264 static void freeSetObject(robj
*o
);
265 static void decrRefCount(void *o
);
266 static robj
*createObject(int type
, void *ptr
);
267 static void freeClient(redisClient
*c
);
268 static int rdbLoad(char *filename
);
269 static void addReply(redisClient
*c
, robj
*obj
);
270 static void addReplySds(redisClient
*c
, sds s
);
271 static void incrRefCount(robj
*o
);
272 static int rdbSaveBackground(char *filename
);
273 static robj
*createStringObject(char *ptr
, size_t len
);
274 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
275 static int syncWithMaster(void);
276 static robj
*tryObjectSharing(robj
*o
);
278 static void authCommand(redisClient
*c
);
279 static void pingCommand(redisClient
*c
);
280 static void echoCommand(redisClient
*c
);
281 static void setCommand(redisClient
*c
);
282 static void setnxCommand(redisClient
*c
);
283 static void getCommand(redisClient
*c
);
284 static void delCommand(redisClient
*c
);
285 static void existsCommand(redisClient
*c
);
286 static void incrCommand(redisClient
*c
);
287 static void decrCommand(redisClient
*c
);
288 static void incrbyCommand(redisClient
*c
);
289 static void decrbyCommand(redisClient
*c
);
290 static void selectCommand(redisClient
*c
);
291 static void randomkeyCommand(redisClient
*c
);
292 static void keysCommand(redisClient
*c
);
293 static void dbsizeCommand(redisClient
*c
);
294 static void lastsaveCommand(redisClient
*c
);
295 static void saveCommand(redisClient
*c
);
296 static void bgsaveCommand(redisClient
*c
);
297 static void shutdownCommand(redisClient
*c
);
298 static void moveCommand(redisClient
*c
);
299 static void renameCommand(redisClient
*c
);
300 static void renamenxCommand(redisClient
*c
);
301 static void lpushCommand(redisClient
*c
);
302 static void rpushCommand(redisClient
*c
);
303 static void lpopCommand(redisClient
*c
);
304 static void rpopCommand(redisClient
*c
);
305 static void llenCommand(redisClient
*c
);
306 static void lindexCommand(redisClient
*c
);
307 static void lrangeCommand(redisClient
*c
);
308 static void ltrimCommand(redisClient
*c
);
309 static void typeCommand(redisClient
*c
);
310 static void lsetCommand(redisClient
*c
);
311 static void saddCommand(redisClient
*c
);
312 static void sremCommand(redisClient
*c
);
313 static void sismemberCommand(redisClient
*c
);
314 static void scardCommand(redisClient
*c
);
315 static void sinterCommand(redisClient
*c
);
316 static void sinterstoreCommand(redisClient
*c
);
317 static void syncCommand(redisClient
*c
);
318 static void flushdbCommand(redisClient
*c
);
319 static void flushallCommand(redisClient
*c
);
320 static void sortCommand(redisClient
*c
);
321 static void lremCommand(redisClient
*c
);
322 static void infoCommand(redisClient
*c
);
323 static void mgetCommand(redisClient
*c
);
324 static void monitorCommand(redisClient
*c
);
326 /*================================= Globals ================================= */
329 static struct redisServer server
; /* server global state */
330 static struct redisCommand cmdTable
[] = {
331 {"get",getCommand
,2,REDIS_CMD_INLINE
},
332 {"set",setCommand
,3,REDIS_CMD_BULK
},
333 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
},
334 {"del",delCommand
,2,REDIS_CMD_INLINE
},
335 {"exists",existsCommand
,2,REDIS_CMD_INLINE
},
336 {"incr",incrCommand
,2,REDIS_CMD_INLINE
},
337 {"decr",decrCommand
,2,REDIS_CMD_INLINE
},
338 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
},
339 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
},
340 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
},
341 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
},
342 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
},
343 {"llen",llenCommand
,2,REDIS_CMD_INLINE
},
344 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
},
345 {"lset",lsetCommand
,4,REDIS_CMD_BULK
},
346 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
},
347 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
},
348 {"lrem",lremCommand
,4,REDIS_CMD_BULK
},
349 {"sadd",saddCommand
,3,REDIS_CMD_BULK
},
350 {"srem",sremCommand
,3,REDIS_CMD_BULK
},
351 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
},
352 {"scard",scardCommand
,2,REDIS_CMD_INLINE
},
353 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
},
354 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
},
355 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
},
356 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
},
357 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
},
358 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
},
359 {"select",selectCommand
,2,REDIS_CMD_INLINE
},
360 {"move",moveCommand
,3,REDIS_CMD_INLINE
},
361 {"rename",renameCommand
,3,REDIS_CMD_INLINE
},
362 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
},
363 {"keys",keysCommand
,2,REDIS_CMD_INLINE
},
364 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
},
365 {"auth",authCommand
,2,REDIS_CMD_INLINE
},
366 {"ping",pingCommand
,1,REDIS_CMD_INLINE
},
367 {"echo",echoCommand
,2,REDIS_CMD_BULK
},
368 {"save",saveCommand
,1,REDIS_CMD_INLINE
},
369 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
},
370 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
},
371 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
},
372 {"type",typeCommand
,2,REDIS_CMD_INLINE
},
373 {"sync",syncCommand
,1,REDIS_CMD_INLINE
},
374 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
},
375 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
},
376 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
},
377 {"info",infoCommand
,1,REDIS_CMD_INLINE
},
378 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
},
382 /*============================ Utility functions ============================ */
384 /* Glob-style pattern matching. */
385 int stringmatchlen(const char *pattern
, int patternLen
,
386 const char *string
, int stringLen
, int nocase
)
391 while (pattern
[1] == '*') {
396 return 1; /* match */
398 if (stringmatchlen(pattern
+1, patternLen
-1,
399 string
, stringLen
, nocase
))
400 return 1; /* match */
404 return 0; /* no match */
408 return 0; /* no match */
418 not = pattern
[0] == '^';
425 if (pattern
[0] == '\\') {
428 if (pattern
[0] == string
[0])
430 } else if (pattern
[0] == ']') {
432 } else if (patternLen
== 0) {
436 } else if (pattern
[1] == '-' && patternLen
>= 3) {
437 int start
= pattern
[0];
438 int end
= pattern
[2];
446 start
= tolower(start
);
452 if (c
>= start
&& c
<= end
)
456 if (pattern
[0] == string
[0])
459 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
469 return 0; /* no match */
475 if (patternLen
>= 2) {
482 if (pattern
[0] != string
[0])
483 return 0; /* no match */
485 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
486 return 0; /* no match */
494 if (stringLen
== 0) {
495 while(*pattern
== '*') {
502 if (patternLen
== 0 && stringLen
== 0)
507 void redisLog(int level
, const char *fmt
, ...)
512 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
516 if (level
>= server
.verbosity
) {
518 fprintf(fp
,"%c ",c
[level
]);
519 vfprintf(fp
, fmt
, ap
);
525 if (server
.logfile
) fclose(fp
);
528 /*====================== Hash table type implementation ==================== */
530 /* This is an hash table type that uses the SDS dynamic strings libary as
531 * keys and radis objects as values (objects can hold SDS strings,
534 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
538 DICT_NOTUSED(privdata
);
540 l1
= sdslen((sds
)key1
);
541 l2
= sdslen((sds
)key2
);
542 if (l1
!= l2
) return 0;
543 return memcmp(key1
, key2
, l1
) == 0;
546 static void dictRedisObjectDestructor(void *privdata
, void *val
)
548 DICT_NOTUSED(privdata
);
553 static int dictSdsKeyCompare(void *privdata
, const void *key1
,
556 const robj
*o1
= key1
, *o2
= key2
;
557 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
560 static unsigned int dictSdsHash(const void *key
) {
562 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
565 static dictType setDictType
= {
566 dictSdsHash
, /* hash function */
569 dictSdsKeyCompare
, /* key compare */
570 dictRedisObjectDestructor
, /* key destructor */
571 NULL
/* val destructor */
574 static dictType hashDictType
= {
575 dictSdsHash
, /* hash function */
578 dictSdsKeyCompare
, /* key compare */
579 dictRedisObjectDestructor
, /* key destructor */
580 dictRedisObjectDestructor
/* val destructor */
583 /* ========================= Random utility functions ======================= */
585 /* Redis generally does not try to recover from out of memory conditions
586 * when allocating objects or strings, it is not clear if it will be possible
587 * to report this condition to the client since the networking layer itself
588 * is based on heap allocation for send buffers, so we simply abort.
589 * At least the code will be simpler to read... */
590 static void oom(const char *msg
) {
591 fprintf(stderr
, "%s: Out of memory\n",msg
);
597 /* ====================== Redis server networking stuff ===================== */
598 void closeTimedoutClients(void) {
602 time_t now
= time(NULL
);
604 li
= listGetIterator(server
.clients
,AL_START_HEAD
);
606 while ((ln
= listNextElement(li
)) != NULL
) {
607 c
= listNodeValue(ln
);
608 if (!(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
609 (now
- c
->lastinteraction
> server
.maxidletime
)) {
610 redisLog(REDIS_DEBUG
,"Closing idle client");
614 listReleaseIterator(li
);
617 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
618 int j
, size
, used
, loops
= server
.cronloops
++;
619 REDIS_NOTUSED(eventLoop
);
621 REDIS_NOTUSED(clientData
);
623 /* Update the global state with the amount of used memory */
624 server
.usedmemory
= zmalloc_used_memory();
626 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
627 * we resize the hash table to save memory */
628 for (j
= 0; j
< server
.dbnum
; j
++) {
629 size
= dictGetHashTableSize(server
.dict
[j
]);
630 used
= dictGetHashTableUsed(server
.dict
[j
]);
631 if (!(loops
% 5) && used
> 0) {
632 redisLog(REDIS_DEBUG
,"DB %d: %d keys in %d slots HT.",j
,used
,size
);
633 /* dictPrintStats(server.dict); */
635 if (size
&& used
&& size
> REDIS_HT_MINSLOTS
&&
636 (used
*100/size
< REDIS_HT_MINFILL
)) {
637 redisLog(REDIS_NOTICE
,"The hash table %d is too sparse, resize it...",j
);
638 dictResize(server
.dict
[j
]);
639 redisLog(REDIS_NOTICE
,"Hash table %d resized.",j
);
643 /* Show information about connected clients */
645 redisLog(REDIS_DEBUG
,"%d clients connected (%d slaves), %d bytes in use",
646 listLength(server
.clients
)-listLength(server
.slaves
),
647 listLength(server
.slaves
),
649 dictGetHashTableUsed(server
.sharingpool
));
652 /* Close connections of timedout clients */
654 closeTimedoutClients();
656 /* Check if a background saving in progress terminated */
657 if (server
.bgsaveinprogress
) {
659 if (wait4(-1,&statloc
,WNOHANG
,NULL
)) {
660 int exitcode
= WEXITSTATUS(statloc
);
662 redisLog(REDIS_NOTICE
,
663 "Background saving terminated with success");
665 server
.lastsave
= time(NULL
);
667 redisLog(REDIS_WARNING
,
668 "Background saving error");
670 server
.bgsaveinprogress
= 0;
673 /* If there is not a background saving in progress check if
674 * we have to save now */
675 time_t now
= time(NULL
);
676 for (j
= 0; j
< server
.saveparamslen
; j
++) {
677 struct saveparam
*sp
= server
.saveparams
+j
;
679 if (server
.dirty
>= sp
->changes
&&
680 now
-server
.lastsave
> sp
->seconds
) {
681 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
682 sp
->changes
, sp
->seconds
);
683 rdbSaveBackground(server
.dbfilename
);
688 /* Check if we should connect to a MASTER */
689 if (server
.replstate
== REDIS_REPL_CONNECT
) {
690 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
691 if (syncWithMaster() == REDIS_OK
) {
692 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
698 static void createSharedObjects(void) {
699 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
700 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
701 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
702 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
703 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
704 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
705 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
706 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
707 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
709 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
710 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
711 "-ERR Operation against a key holding the wrong kind of value\r\n"));
712 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
713 "-ERR no such key\r\n"));
714 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
715 "-ERR syntax error\r\n"));
716 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
717 "-ERR source and destination objects are the same\r\n"));
718 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
719 "-ERR index out of range\r\n"));
720 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
721 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
722 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
723 shared
.select0
= createStringObject("select 0\r\n",10);
724 shared
.select1
= createStringObject("select 1\r\n",10);
725 shared
.select2
= createStringObject("select 2\r\n",10);
726 shared
.select3
= createStringObject("select 3\r\n",10);
727 shared
.select4
= createStringObject("select 4\r\n",10);
728 shared
.select5
= createStringObject("select 5\r\n",10);
729 shared
.select6
= createStringObject("select 6\r\n",10);
730 shared
.select7
= createStringObject("select 7\r\n",10);
731 shared
.select8
= createStringObject("select 8\r\n",10);
732 shared
.select9
= createStringObject("select 9\r\n",10);
735 static void appendServerSaveParams(time_t seconds
, int changes
) {
736 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
737 if (server
.saveparams
== NULL
) oom("appendServerSaveParams");
738 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
739 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
740 server
.saveparamslen
++;
743 static void ResetServerSaveParams() {
744 zfree(server
.saveparams
);
745 server
.saveparams
= NULL
;
746 server
.saveparamslen
= 0;
749 static void initServerConfig() {
750 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
751 server
.port
= REDIS_SERVERPORT
;
752 server
.verbosity
= REDIS_DEBUG
;
753 server
.maxidletime
= REDIS_MAXIDLETIME
;
754 server
.saveparams
= NULL
;
755 server
.logfile
= NULL
; /* NULL = log on standard output */
756 server
.bindaddr
= NULL
;
757 server
.glueoutputbuf
= 1;
758 server
.daemonize
= 0;
759 server
.pidfile
= "/var/run/redis.pid";
760 server
.dbfilename
= "dump.rdb";
761 server
.requirepass
= NULL
;
762 server
.shareobjects
= 0;
763 ResetServerSaveParams();
765 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
766 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
767 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
768 /* Replication related */
770 server
.masterhost
= NULL
;
771 server
.masterport
= 6379;
772 server
.master
= NULL
;
773 server
.replstate
= REDIS_REPL_NONE
;
776 static void initServer() {
779 signal(SIGHUP
, SIG_IGN
);
780 signal(SIGPIPE
, SIG_IGN
);
782 server
.clients
= listCreate();
783 server
.slaves
= listCreate();
784 server
.monitors
= listCreate();
785 server
.objfreelist
= listCreate();
786 createSharedObjects();
787 server
.el
= aeCreateEventLoop();
788 server
.dict
= zmalloc(sizeof(dict
*)*server
.dbnum
);
789 server
.sharingpool
= dictCreate(&setDictType
,NULL
);
790 server
.sharingpoolsize
= 1024;
791 if (!server
.dict
|| !server
.clients
|| !server
.slaves
|| !server
.monitors
|| !server
.el
|| !server
.objfreelist
)
792 oom("server initialization"); /* Fatal OOM */
793 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
794 if (server
.fd
== -1) {
795 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
798 for (j
= 0; j
< server
.dbnum
; j
++)
799 server
.dict
[j
] = dictCreate(&hashDictType
,NULL
);
800 server
.cronloops
= 0;
801 server
.bgsaveinprogress
= 0;
802 server
.lastsave
= time(NULL
);
804 server
.usedmemory
= 0;
805 server
.stat_numcommands
= 0;
806 server
.stat_numconnections
= 0;
807 server
.stat_starttime
= time(NULL
);
808 aeCreateTimeEvent(server
.el
, 1000, serverCron
, NULL
, NULL
);
811 /* Empty the whole database */
812 static void emptyDb() {
815 for (j
= 0; j
< server
.dbnum
; j
++)
816 dictEmpty(server
.dict
[j
]);
819 /* I agree, this is a very rudimental way to load a configuration...
820 will improve later if the config gets more complex */
821 static void loadServerConfig(char *filename
) {
822 FILE *fp
= fopen(filename
,"r");
823 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
828 redisLog(REDIS_WARNING
,"Fatal error, can't open config file");
831 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
837 line
= sdstrim(line
," \t\r\n");
839 /* Skip comments and blank lines*/
840 if (line
[0] == '#' || line
[0] == '\0') {
845 /* Split into arguments */
846 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
849 /* Execute config directives */
850 if (!strcmp(argv
[0],"timeout") && argc
== 2) {
851 server
.maxidletime
= atoi(argv
[1]);
852 if (server
.maxidletime
< 1) {
853 err
= "Invalid timeout value"; goto loaderr
;
855 } else if (!strcmp(argv
[0],"port") && argc
== 2) {
856 server
.port
= atoi(argv
[1]);
857 if (server
.port
< 1 || server
.port
> 65535) {
858 err
= "Invalid port"; goto loaderr
;
860 } else if (!strcmp(argv
[0],"bind") && argc
== 2) {
861 server
.bindaddr
= zstrdup(argv
[1]);
862 } else if (!strcmp(argv
[0],"save") && argc
== 3) {
863 int seconds
= atoi(argv
[1]);
864 int changes
= atoi(argv
[2]);
865 if (seconds
< 1 || changes
< 0) {
866 err
= "Invalid save parameters"; goto loaderr
;
868 appendServerSaveParams(seconds
,changes
);
869 } else if (!strcmp(argv
[0],"dir") && argc
== 2) {
870 if (chdir(argv
[1]) == -1) {
871 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
872 argv
[1], strerror(errno
));
875 } else if (!strcmp(argv
[0],"loglevel") && argc
== 2) {
876 if (!strcmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
877 else if (!strcmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
878 else if (!strcmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
880 err
= "Invalid log level. Must be one of debug, notice, warning";
883 } else if (!strcmp(argv
[0],"logfile") && argc
== 2) {
886 server
.logfile
= zstrdup(argv
[1]);
887 if (!strcmp(server
.logfile
,"stdout")) {
888 zfree(server
.logfile
);
889 server
.logfile
= NULL
;
891 if (server
.logfile
) {
892 /* Test if we are able to open the file. The server will not
893 * be able to abort just for this problem later... */
894 fp
= fopen(server
.logfile
,"a");
896 err
= sdscatprintf(sdsempty(),
897 "Can't open the log file: %s", strerror(errno
));
902 } else if (!strcmp(argv
[0],"databases") && argc
== 2) {
903 server
.dbnum
= atoi(argv
[1]);
904 if (server
.dbnum
< 1) {
905 err
= "Invalid number of databases"; goto loaderr
;
907 } else if (!strcmp(argv
[0],"slaveof") && argc
== 3) {
908 server
.masterhost
= sdsnew(argv
[1]);
909 server
.masterport
= atoi(argv
[2]);
910 server
.replstate
= REDIS_REPL_CONNECT
;
911 } else if (!strcmp(argv
[0],"glueoutputbuf") && argc
== 2) {
913 if (!strcmp(argv
[1],"yes")) server
.glueoutputbuf
= 1;
914 else if (!strcmp(argv
[1],"no")) server
.glueoutputbuf
= 0;
916 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
918 } else if (!strcmp(argv
[0],"shareobjects") && argc
== 2) {
920 if (!strcmp(argv
[1],"yes")) server
.shareobjects
= 1;
921 else if (!strcmp(argv
[1],"no")) server
.shareobjects
= 0;
923 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
925 } else if (!strcmp(argv
[0],"daemonize") && argc
== 2) {
927 if (!strcmp(argv
[1],"yes")) server
.daemonize
= 1;
928 else if (!strcmp(argv
[1],"no")) server
.daemonize
= 0;
930 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
932 } else if (!strcmp(argv
[0],"requirepass") && argc
== 2) {
933 server
.requirepass
= zstrdup(argv
[1]);
934 } else if (!strcmp(argv
[0],"pidfile") && argc
== 2) {
935 server
.pidfile
= zstrdup(argv
[1]);
937 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
939 for (j
= 0; j
< argc
; j
++)
948 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
949 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
950 fprintf(stderr
, ">>> '%s'\n", line
);
951 fprintf(stderr
, "%s\n", err
);
955 static void freeClientArgv(redisClient
*c
) {
958 for (j
= 0; j
< c
->argc
; j
++)
959 decrRefCount(c
->argv
[j
]);
963 static void freeClient(redisClient
*c
) {
966 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
967 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
968 sdsfree(c
->querybuf
);
969 listRelease(c
->reply
);
972 ln
= listSearchKey(server
.clients
,c
);
974 listDelNode(server
.clients
,ln
);
975 if (c
->flags
& REDIS_SLAVE
) {
976 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
977 ln
= listSearchKey(l
,c
);
981 if (c
->flags
& REDIS_MASTER
) {
982 server
.master
= NULL
;
983 server
.replstate
= REDIS_REPL_CONNECT
;
988 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
990 listNode
*ln
= c
->reply
->head
, *next
;
995 totlen
+= sdslen(o
->ptr
);
997 /* This optimization makes more sense if we don't have to copy
999 if (totlen
> 1024) return;
1005 ln
= c
->reply
->head
;
1009 memcpy(buf
+copylen
,o
->ptr
,sdslen(o
->ptr
));
1010 copylen
+= sdslen(o
->ptr
);
1011 listDelNode(c
->reply
,ln
);
1014 /* Now the output buffer is empty, add the new single element */
1015 addReplySds(c
,sdsnewlen(buf
,totlen
));
1019 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1020 redisClient
*c
= privdata
;
1021 int nwritten
= 0, totwritten
= 0, objlen
;
1024 REDIS_NOTUSED(mask
);
1026 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
1027 glueReplyBuffersIfNeeded(c
);
1028 while(listLength(c
->reply
)) {
1029 o
= listNodeValue(listFirst(c
->reply
));
1030 objlen
= sdslen(o
->ptr
);
1033 listDelNode(c
->reply
,listFirst(c
->reply
));
1037 if (c
->flags
& REDIS_MASTER
) {
1038 nwritten
= objlen
- c
->sentlen
;
1040 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
1041 if (nwritten
<= 0) break;
1043 c
->sentlen
+= nwritten
;
1044 totwritten
+= nwritten
;
1045 /* If we fully sent the object on head go to the next one */
1046 if (c
->sentlen
== objlen
) {
1047 listDelNode(c
->reply
,listFirst(c
->reply
));
1051 if (nwritten
== -1) {
1052 if (errno
== EAGAIN
) {
1055 redisLog(REDIS_DEBUG
,
1056 "Error writing to client: %s", strerror(errno
));
1061 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
1062 if (listLength(c
->reply
) == 0) {
1064 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1068 static struct redisCommand
*lookupCommand(char *name
) {
1070 while(cmdTable
[j
].name
!= NULL
) {
1071 if (!strcmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
1077 /* resetClient prepare the client to process the next command */
1078 static void resetClient(redisClient
*c
) {
1083 /* If this function gets called we already read a whole
1084 * command, argments are in the client argv/argc fields.
1085 * processCommand() execute the command or prepare the
1086 * server for a bulk read from the client.
1088 * If 1 is returned the client is still alive and valid and
1089 * and other operations can be performed by the caller. Otherwise
1090 * if 0 is returned the client was destroied (i.e. after QUIT). */
1091 static int processCommand(redisClient
*c
) {
1092 struct redisCommand
*cmd
;
1095 sdstolower(c
->argv
[0]->ptr
);
1096 /* The QUIT command is handled as a special case. Normal command
1097 * procs are unable to close the client connection safely */
1098 if (!strcmp(c
->argv
[0]->ptr
,"quit")) {
1102 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1104 addReplySds(c
,sdsnew("-ERR unknown command\r\n"));
1107 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
1108 (c
->argc
< -cmd
->arity
)) {
1109 addReplySds(c
,sdsnew("-ERR wrong number of arguments\r\n"));
1112 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
1113 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
1115 decrRefCount(c
->argv
[c
->argc
-1]);
1116 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1118 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1123 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1124 /* It is possible that the bulk read is already in the
1125 * buffer. Check this condition and handle it accordingly */
1126 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
1127 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
1129 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
1134 /* Let's try to share objects on the command arguments vector */
1135 if (server
.shareobjects
) {
1137 for(j
= 1; j
< c
->argc
; j
++)
1138 c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]);
1140 /* Check if the user is authenticated */
1141 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
1142 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
1147 /* Exec the command */
1148 dirty
= server
.dirty
;
1150 if (server
.dirty
-dirty
!= 0 && listLength(server
.slaves
))
1151 replicationFeedSlaves(server
.slaves
,cmd
,c
->dictid
,c
->argv
,c
->argc
);
1152 if (listLength(server
.monitors
))
1153 replicationFeedSlaves(server
.monitors
,cmd
,c
->dictid
,c
->argv
,c
->argc
);
1154 server
.stat_numcommands
++;
1156 /* Prepare the client for the next command */
1157 if (c
->flags
& REDIS_CLOSE
) {
1165 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
1166 listNode
*ln
= slaves
->head
;
1167 robj
*outv
[REDIS_MAX_ARGS
*4]; /* enough room for args, spaces, newlines */
1170 for (j
= 0; j
< argc
; j
++) {
1171 if (j
!= 0) outv
[outc
++] = shared
.space
;
1172 if ((cmd
->flags
& REDIS_CMD_BULK
) && j
== argc
-1) {
1175 lenobj
= createObject(REDIS_STRING
,
1176 sdscatprintf(sdsempty(),"%d\r\n",sdslen(argv
[j
]->ptr
)));
1177 lenobj
->refcount
= 0;
1178 outv
[outc
++] = lenobj
;
1180 outv
[outc
++] = argv
[j
];
1182 outv
[outc
++] = shared
.crlf
;
1185 redisClient
*slave
= ln
->value
;
1186 if (slave
->slaveseldb
!= dictid
) {
1190 case 0: selectcmd
= shared
.select0
; break;
1191 case 1: selectcmd
= shared
.select1
; break;
1192 case 2: selectcmd
= shared
.select2
; break;
1193 case 3: selectcmd
= shared
.select3
; break;
1194 case 4: selectcmd
= shared
.select4
; break;
1195 case 5: selectcmd
= shared
.select5
; break;
1196 case 6: selectcmd
= shared
.select6
; break;
1197 case 7: selectcmd
= shared
.select7
; break;
1198 case 8: selectcmd
= shared
.select8
; break;
1199 case 9: selectcmd
= shared
.select9
; break;
1201 selectcmd
= createObject(REDIS_STRING
,
1202 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
1203 selectcmd
->refcount
= 0;
1206 addReply(slave
,selectcmd
);
1207 slave
->slaveseldb
= dictid
;
1209 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
1214 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1215 redisClient
*c
= (redisClient
*) privdata
;
1216 char buf
[REDIS_QUERYBUF_LEN
];
1219 REDIS_NOTUSED(mask
);
1221 nread
= read(fd
, buf
, REDIS_QUERYBUF_LEN
);
1223 if (errno
== EAGAIN
) {
1226 redisLog(REDIS_DEBUG
, "Reading from client: %s",strerror(errno
));
1230 } else if (nread
== 0) {
1231 redisLog(REDIS_DEBUG
, "Client closed connection");
1236 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
1237 c
->lastinteraction
= time(NULL
);
1243 if (c
->bulklen
== -1) {
1244 /* Read the first line of the query */
1245 char *p
= strchr(c
->querybuf
,'\n');
1251 query
= c
->querybuf
;
1252 c
->querybuf
= sdsempty();
1253 querylen
= 1+(p
-(query
));
1254 if (sdslen(query
) > querylen
) {
1255 /* leave data after the first line of the query in the buffer */
1256 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
1258 *p
= '\0'; /* remove "\n" */
1259 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
1260 sdsupdatelen(query
);
1262 /* Now we can split the query in arguments */
1263 if (sdslen(query
) == 0) {
1264 /* Ignore empty query */
1268 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
1270 if (argv
== NULL
) oom("sdssplitlen");
1271 for (j
= 0; j
< argc
&& j
< REDIS_MAX_ARGS
; j
++) {
1272 if (sdslen(argv
[j
])) {
1273 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
1280 /* Execute the command. If the client is still valid
1281 * after processCommand() return and there is something
1282 * on the query buffer try to process the next command. */
1283 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
1285 } else if (sdslen(c
->querybuf
) >= 1024) {
1286 redisLog(REDIS_DEBUG
, "Client protocol error");
1291 /* Bulk read handling. Note that if we are at this point
1292 the client already sent a command terminated with a newline,
1293 we are reading the bulk data that is actually the last
1294 argument of the command. */
1295 int qbl
= sdslen(c
->querybuf
);
1297 if (c
->bulklen
<= qbl
) {
1298 /* Copy everything but the final CRLF as final argument */
1299 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
1301 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
1308 static int selectDb(redisClient
*c
, int id
) {
1309 if (id
< 0 || id
>= server
.dbnum
)
1311 c
->dict
= server
.dict
[id
];
1316 static redisClient
*createClient(int fd
) {
1317 redisClient
*c
= zmalloc(sizeof(*c
));
1319 anetNonBlock(NULL
,fd
);
1320 anetTcpNoDelay(NULL
,fd
);
1321 if (!c
) return NULL
;
1324 c
->querybuf
= sdsempty();
1329 c
->lastinteraction
= time(NULL
);
1330 c
->authenticated
= 0;
1331 if ((c
->reply
= listCreate()) == NULL
) oom("listCreate");
1332 listSetFreeMethod(c
->reply
,decrRefCount
);
1333 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
1334 readQueryFromClient
, c
, NULL
) == AE_ERR
) {
1338 if (!listAddNodeTail(server
.clients
,c
)) oom("listAddNodeTail");
1342 static void addReply(redisClient
*c
, robj
*obj
) {
1343 if (listLength(c
->reply
) == 0 &&
1344 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
1345 sendReplyToClient
, c
, NULL
) == AE_ERR
) return;
1346 if (!listAddNodeTail(c
->reply
,obj
)) oom("listAddNodeTail");
1350 static void addReplySds(redisClient
*c
, sds s
) {
1351 robj
*o
= createObject(REDIS_STRING
,s
);
1356 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1360 REDIS_NOTUSED(mask
);
1361 REDIS_NOTUSED(privdata
);
1363 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
1364 if (cfd
== AE_ERR
) {
1365 redisLog(REDIS_DEBUG
,"Accepting client connection: %s", server
.neterr
);
1368 redisLog(REDIS_DEBUG
,"Accepted %s:%d", cip
, cport
);
1369 if (createClient(cfd
) == NULL
) {
1370 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
1371 close(cfd
); /* May be already closed, just ingore errors */
1374 server
.stat_numconnections
++;
1377 /* ======================= Redis objects implementation ===================== */
1379 static robj
*createObject(int type
, void *ptr
) {
1382 if (listLength(server
.objfreelist
)) {
1383 listNode
*head
= listFirst(server
.objfreelist
);
1384 o
= listNodeValue(head
);
1385 listDelNode(server
.objfreelist
,head
);
1387 o
= zmalloc(sizeof(*o
));
1389 if (!o
) oom("createObject");
1396 static robj
*createStringObject(char *ptr
, size_t len
) {
1397 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
1400 static robj
*createListObject(void) {
1401 list
*l
= listCreate();
1403 if (!l
) oom("listCreate");
1404 listSetFreeMethod(l
,decrRefCount
);
1405 return createObject(REDIS_LIST
,l
);
1408 static robj
*createSetObject(void) {
1409 dict
*d
= dictCreate(&setDictType
,NULL
);
1410 if (!d
) oom("dictCreate");
1411 return createObject(REDIS_SET
,d
);
1415 static robj
*createHashObject(void) {
1416 dict
*d
= dictCreate(&hashDictType
,NULL
);
1417 if (!d
) oom("dictCreate");
1418 return createObject(REDIS_SET
,d
);
1422 static void freeStringObject(robj
*o
) {
1426 static void freeListObject(robj
*o
) {
1427 listRelease((list
*) o
->ptr
);
1430 static void freeSetObject(robj
*o
) {
1431 dictRelease((dict
*) o
->ptr
);
1434 static void freeHashObject(robj
*o
) {
1435 dictRelease((dict
*) o
->ptr
);
1438 static void incrRefCount(robj
*o
) {
1442 static void decrRefCount(void *obj
) {
1444 if (--(o
->refcount
) == 0) {
1446 case REDIS_STRING
: freeStringObject(o
); break;
1447 case REDIS_LIST
: freeListObject(o
); break;
1448 case REDIS_SET
: freeSetObject(o
); break;
1449 case REDIS_HASH
: freeHashObject(o
); break;
1450 default: assert(0 != 0); break;
1452 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
1453 !listAddNodeHead(server
.objfreelist
,o
))
1458 /* Try to share an object against the shared objects pool */
1459 static robj
*tryObjectSharing(robj
*o
) {
1460 struct dictEntry
*de
;
1463 if (server
.shareobjects
== 0) return o
;
1465 assert(o
->type
== REDIS_STRING
);
1466 de
= dictFind(server
.sharingpool
,o
);
1468 robj
*shared
= dictGetEntryKey(de
);
1470 c
= ((unsigned long) dictGetEntryVal(de
))+1;
1471 dictGetEntryVal(de
) = (void*) c
;
1472 incrRefCount(shared
);
1476 /* Here we are using a stream algorihtm: Every time an object is
1477 * shared we increment its count, everytime there is a miss we
1478 * recrement the counter of a random object. If this object reaches
1479 * zero we remove the object and put the current object instead. */
1480 if (dictGetHashTableUsed(server
.sharingpool
) >=
1481 server
.sharingpoolsize
) {
1482 de
= dictGetRandomKey(server
.sharingpool
);
1484 c
= ((unsigned long) dictGetEntryVal(de
))-1;
1485 dictGetEntryVal(de
) = (void*) c
;
1487 dictDelete(server
.sharingpool
,de
->key
);
1490 c
= 0; /* If the pool is empty we want to add this object */
1495 retval
= dictAdd(server
.sharingpool
,o
,(void*)1);
1496 assert(retval
== DICT_OK
);
1503 /*============================ DB saving/loading ============================ */
1505 static int rdbSaveType(FILE *fp
, unsigned char type
) {
1506 if (fwrite(&type
,1,1,fp
) == 0) return -1;
1510 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
1511 unsigned char buf
[2];
1514 /* Save a 6 bit len */
1515 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
1516 if (fwrite(buf
,1,1,fp
) == 0) return -1;
1517 } else if (len
< (1<<14)) {
1518 /* Save a 14 bit len */
1519 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
1521 if (fwrite(buf
,4,1,fp
) == 0) return -1;
1523 /* Save a 32 bit len */
1524 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
1525 if (fwrite(buf
,1,1,fp
) == 0) return -1;
1527 if (fwrite(&len
,4,1,fp
) == 0) return -1;
1532 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
1533 size_t len
= sdslen(obj
->ptr
);
1535 if (rdbSaveLen(fp
,len
) == -1) return -1;
1536 if (len
&& fwrite(obj
->ptr
,len
,1,fp
) == 0) return -1;
1540 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
1541 static int rdbSave(char *filename
) {
1542 dictIterator
*di
= NULL
;
1548 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
1549 fp
= fopen(tmpfile
,"w");
1551 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
1554 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
1555 for (j
= 0; j
< server
.dbnum
; j
++) {
1556 dict
*d
= server
.dict
[j
];
1557 if (dictGetHashTableUsed(d
) == 0) continue;
1558 di
= dictGetIterator(d
);
1564 /* Write the SELECT DB opcode */
1565 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
1566 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
1568 /* Iterate this DB writing every entry */
1569 while((de
= dictNext(di
)) != NULL
) {
1570 robj
*key
= dictGetEntryKey(de
);
1571 robj
*o
= dictGetEntryVal(de
);
1573 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
1574 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
1575 if (o
->type
== REDIS_STRING
) {
1576 /* Save a string value */
1577 if (rdbSaveStringObject(fp
,o
) == -1) goto werr
;
1578 } else if (o
->type
== REDIS_LIST
) {
1579 /* Save a list value */
1580 list
*list
= o
->ptr
;
1581 listNode
*ln
= list
->head
;
1583 if (rdbSaveLen(fp
,listLength(list
)) == -1) goto werr
;
1585 robj
*eleobj
= listNodeValue(ln
);
1587 if (rdbSaveStringObject(fp
,eleobj
) == -1) goto werr
;
1590 } else if (o
->type
== REDIS_SET
) {
1591 /* Save a set value */
1593 dictIterator
*di
= dictGetIterator(set
);
1596 if (!set
) oom("dictGetIteraotr");
1597 if (rdbSaveLen(fp
,dictGetHashTableUsed(set
)) == -1) goto werr
;
1598 while((de
= dictNext(di
)) != NULL
) {
1599 robj
*eleobj
= dictGetEntryKey(de
);
1601 if (rdbSaveStringObject(fp
,eleobj
) == -1) goto werr
;
1603 dictReleaseIterator(di
);
1608 dictReleaseIterator(di
);
1611 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
1613 /* Make sure data will not remain on the OS's output buffers */
1618 /* Use RENAME to make sure the DB file is changed atomically only
1619 * if the generate DB file is ok. */
1620 if (rename(tmpfile
,filename
) == -1) {
1621 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destionation: %s", strerror(errno
));
1625 redisLog(REDIS_NOTICE
,"DB saved on disk");
1627 server
.lastsave
= time(NULL
);
1633 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
1634 if (di
) dictReleaseIterator(di
);
1638 static int rdbSaveBackground(char *filename
) {
1641 if (server
.bgsaveinprogress
) return REDIS_ERR
;
1642 if ((childpid
= fork()) == 0) {
1645 if (rdbSave(filename
) == REDIS_OK
) {
1652 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
1653 server
.bgsaveinprogress
= 1;
1656 return REDIS_OK
; /* unreached */
1659 static int rdbLoadType(FILE *fp
) {
1661 if (fread(&type
,1,1,fp
) == 0) return -1;
1665 static uint32_t rdbLoadLen(FILE *fp
, int rdbver
) {
1666 unsigned char buf
[2];
1670 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
1673 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
1674 if ((buf
[0]&0xC0) == REDIS_RDB_6BITLEN
) {
1675 /* Read a 6 bit len */
1677 } else if ((buf
[0]&0xC0) == REDIS_RDB_14BITLEN
) {
1678 /* Read a 14 bit len */
1679 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
1680 return ((buf
[0]&0x3F)<<8)|buf
[1];
1682 /* Read a 32 bit len */
1683 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
1689 static robj
*rdbLoadStringObject(FILE*fp
,int rdbver
) {
1690 uint32_t len
= rdbLoadLen(fp
,rdbver
);
1693 if (len
== REDIS_RDB_LENERR
) return NULL
;
1694 val
= sdsnewlen(NULL
,len
);
1695 if (len
&& fread(val
,len
,1,fp
) == 0) {
1699 return tryObjectSharing(createObject(REDIS_STRING
,val
));
1702 static int rdbLoad(char *filename
) {
1704 robj
*keyobj
= NULL
;
1708 dict
*d
= server
.dict
[0];
1711 fp
= fopen(filename
,"r");
1712 if (!fp
) return REDIS_ERR
;
1713 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
1715 if (memcmp(buf
,"REDIS",5) != 0) {
1717 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
1720 rdbver
= atoi(buf
+5);
1723 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
1730 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
1731 if (type
== REDIS_EOF
) break;
1732 /* Handle SELECT DB opcode as a special case */
1733 if (type
== REDIS_SELECTDB
) {
1734 if ((dbid
= rdbLoadLen(fp
,rdbver
)) == REDIS_RDB_LENERR
) goto eoferr
;
1735 if (dbid
>= (unsigned)server
.dbnum
) {
1736 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
1739 d
= server
.dict
[dbid
];
1743 if ((keyobj
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1745 if (type
== REDIS_STRING
) {
1746 /* Read string value */
1747 if ((o
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1748 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
1749 /* Read list/set value */
1752 if ((listlen
= rdbLoadLen(fp
,rdbver
)) == REDIS_RDB_LENERR
)
1754 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
1755 /* Load every single element of the list/set */
1759 if ((ele
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1760 if (type
== REDIS_LIST
) {
1761 if (!listAddNodeTail((list
*)o
->ptr
,ele
))
1762 oom("listAddNodeTail");
1764 if (dictAdd((dict
*)o
->ptr
,ele
,NULL
) == DICT_ERR
)
1771 /* Add the new object in the hash table */
1772 retval
= dictAdd(d
,keyobj
,o
);
1773 if (retval
== DICT_ERR
) {
1774 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
1782 eoferr
: /* unexpected end of file is handled here with a fatal exit */
1783 decrRefCount(keyobj
);
1784 redisLog(REDIS_WARNING
,"Short read loading DB. Unrecoverable error, exiting now.");
1786 return REDIS_ERR
; /* Just to avoid warning */
1789 /*================================== Commands =============================== */
1791 static void authCommand(redisClient
*c
) {
1792 if (!strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1793 c
->authenticated
= 1;
1794 addReply(c
,shared
.ok
);
1796 c
->authenticated
= 0;
1797 addReply(c
,shared
.err
);
1801 static void pingCommand(redisClient
*c
) {
1802 addReply(c
,shared
.pong
);
1805 static void echoCommand(redisClient
*c
) {
1806 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
1807 (int)sdslen(c
->argv
[1]->ptr
)));
1808 addReply(c
,c
->argv
[1]);
1809 addReply(c
,shared
.crlf
);
1812 /*=================================== Strings =============================== */
1814 static void setGenericCommand(redisClient
*c
, int nx
) {
1817 retval
= dictAdd(c
->dict
,c
->argv
[1],c
->argv
[2]);
1818 if (retval
== DICT_ERR
) {
1820 dictReplace(c
->dict
,c
->argv
[1],c
->argv
[2]);
1821 incrRefCount(c
->argv
[2]);
1823 addReply(c
,shared
.czero
);
1827 incrRefCount(c
->argv
[1]);
1828 incrRefCount(c
->argv
[2]);
1831 addReply(c
, nx
? shared
.cone
: shared
.ok
);
1834 static void setCommand(redisClient
*c
) {
1835 setGenericCommand(c
,0);
1838 static void setnxCommand(redisClient
*c
) {
1839 setGenericCommand(c
,1);
1842 static void getCommand(redisClient
*c
) {
1845 de
= dictFind(c
->dict
,c
->argv
[1]);
1847 addReply(c
,shared
.nullbulk
);
1849 robj
*o
= dictGetEntryVal(de
);
1851 if (o
->type
!= REDIS_STRING
) {
1852 addReply(c
,shared
.wrongtypeerr
);
1854 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o
->ptr
)));
1856 addReply(c
,shared
.crlf
);
1861 static void mgetCommand(redisClient
*c
) {
1865 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
1866 for (j
= 1; j
< c
->argc
; j
++) {
1867 de
= dictFind(c
->dict
,c
->argv
[j
]);
1869 addReply(c
,shared
.nullbulk
);
1871 robj
*o
= dictGetEntryVal(de
);
1873 if (o
->type
!= REDIS_STRING
) {
1874 addReply(c
,shared
.nullbulk
);
1876 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o
->ptr
)));
1878 addReply(c
,shared
.crlf
);
1884 static void incrDecrCommand(redisClient
*c
, int incr
) {
1890 de
= dictFind(c
->dict
,c
->argv
[1]);
1894 robj
*o
= dictGetEntryVal(de
);
1896 if (o
->type
!= REDIS_STRING
) {
1901 value
= strtoll(o
->ptr
, &eptr
, 10);
1906 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
1907 retval
= dictAdd(c
->dict
,c
->argv
[1],o
);
1908 if (retval
== DICT_ERR
) {
1909 dictReplace(c
->dict
,c
->argv
[1],o
);
1911 incrRefCount(c
->argv
[1]);
1914 addReply(c
,shared
.colon
);
1916 addReply(c
,shared
.crlf
);
1919 static void incrCommand(redisClient
*c
) {
1920 incrDecrCommand(c
,1);
1923 static void decrCommand(redisClient
*c
) {
1924 incrDecrCommand(c
,-1);
1927 static void incrbyCommand(redisClient
*c
) {
1928 int incr
= atoi(c
->argv
[2]->ptr
);
1929 incrDecrCommand(c
,incr
);
1932 static void decrbyCommand(redisClient
*c
) {
1933 int incr
= atoi(c
->argv
[2]->ptr
);
1934 incrDecrCommand(c
,-incr
);
1937 /* ========================= Type agnostic commands ========================= */
1939 static void delCommand(redisClient
*c
) {
1940 if (dictDelete(c
->dict
,c
->argv
[1]) == DICT_OK
) {
1942 addReply(c
,shared
.cone
);
1944 addReply(c
,shared
.czero
);
1948 static void existsCommand(redisClient
*c
) {
1951 de
= dictFind(c
->dict
,c
->argv
[1]);
1953 addReply(c
,shared
.czero
);
1955 addReply(c
,shared
.cone
);
1958 static void selectCommand(redisClient
*c
) {
1959 int id
= atoi(c
->argv
[1]->ptr
);
1961 if (selectDb(c
,id
) == REDIS_ERR
) {
1962 addReplySds(c
,"-ERR invalid DB index\r\n");
1964 addReply(c
,shared
.ok
);
1968 static void randomkeyCommand(redisClient
*c
) {
1971 de
= dictGetRandomKey(c
->dict
);
1973 addReply(c
,shared
.crlf
);
1975 addReply(c
,shared
.plus
);
1976 addReply(c
,dictGetEntryKey(de
));
1977 addReply(c
,shared
.crlf
);
1981 static void keysCommand(redisClient
*c
) {
1984 sds pattern
= c
->argv
[1]->ptr
;
1985 int plen
= sdslen(pattern
);
1986 int numkeys
= 0, keyslen
= 0;
1987 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
1989 di
= dictGetIterator(c
->dict
);
1990 if (!di
) oom("dictGetIterator");
1992 decrRefCount(lenobj
);
1993 while((de
= dictNext(di
)) != NULL
) {
1994 robj
*keyobj
= dictGetEntryKey(de
);
1995 sds key
= keyobj
->ptr
;
1996 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
1997 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
1999 addReply(c
,shared
.space
);
2002 keyslen
+= sdslen(key
);
2005 dictReleaseIterator(di
);
2006 lenobj
->ptr
= sdscatprintf(sdsempty(),"$%lu\r\n",keyslen
+(numkeys
? (numkeys
-1) : 0));
2007 addReply(c
,shared
.crlf
);
2010 static void dbsizeCommand(redisClient
*c
) {
2012 sdscatprintf(sdsempty(),":%lu\r\n",dictGetHashTableUsed(c
->dict
)));
2015 static void lastsaveCommand(redisClient
*c
) {
2017 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
2020 static void typeCommand(redisClient
*c
) {
2024 de
= dictFind(c
->dict
,c
->argv
[1]);
2028 robj
*o
= dictGetEntryVal(de
);
2031 case REDIS_STRING
: type
= "+string"; break;
2032 case REDIS_LIST
: type
= "+list"; break;
2033 case REDIS_SET
: type
= "+set"; break;
2034 default: type
= "unknown"; break;
2037 addReplySds(c
,sdsnew(type
));
2038 addReply(c
,shared
.crlf
);
2041 static void saveCommand(redisClient
*c
) {
2042 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
2043 addReply(c
,shared
.ok
);
2045 addReply(c
,shared
.err
);
2049 static void bgsaveCommand(redisClient
*c
) {
2050 if (server
.bgsaveinprogress
) {
2051 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
2054 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
2055 addReply(c
,shared
.ok
);
2057 addReply(c
,shared
.err
);
2061 static void shutdownCommand(redisClient
*c
) {
2062 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
2063 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
2064 if (server
.daemonize
) {
2065 unlink(server
.pidfile
);
2067 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
2070 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
2071 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
2075 static void renameGenericCommand(redisClient
*c
, int nx
) {
2079 /* To use the same key as src and dst is probably an error */
2080 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
2081 addReply(c
,shared
.sameobjecterr
);
2085 de
= dictFind(c
->dict
,c
->argv
[1]);
2087 addReply(c
,shared
.nokeyerr
);
2090 o
= dictGetEntryVal(de
);
2092 if (dictAdd(c
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
2095 addReply(c
,shared
.czero
);
2098 dictReplace(c
->dict
,c
->argv
[2],o
);
2100 incrRefCount(c
->argv
[2]);
2102 dictDelete(c
->dict
,c
->argv
[1]);
2104 addReply(c
,nx
? shared
.cone
: shared
.ok
);
2107 static void renameCommand(redisClient
*c
) {
2108 renameGenericCommand(c
,0);
2111 static void renamenxCommand(redisClient
*c
) {
2112 renameGenericCommand(c
,1);
2115 static void moveCommand(redisClient
*c
) {
2121 /* Obtain source and target DB pointers */
2124 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
2125 addReply(c
,shared
.outofrangeerr
);
2132 /* If the user is moving using as target the same
2133 * DB as the source DB it is probably an error. */
2135 addReply(c
,shared
.sameobjecterr
);
2139 /* Check if the element exists and get a reference */
2140 de
= dictFind(c
->dict
,c
->argv
[1]);
2142 addReply(c
,shared
.czero
);
2146 /* Try to add the element to the target DB */
2147 key
= dictGetEntryKey(de
);
2148 o
= dictGetEntryVal(de
);
2149 if (dictAdd(dst
,key
,o
) == DICT_ERR
) {
2150 addReply(c
,shared
.czero
);
2156 /* OK! key moved, free the entry in the source DB */
2157 dictDelete(src
,c
->argv
[1]);
2159 addReply(c
,shared
.cone
);
2162 /* =================================== Lists ================================ */
2163 static void pushGenericCommand(redisClient
*c
, int where
) {
2168 de
= dictFind(c
->dict
,c
->argv
[1]);
2170 lobj
= createListObject();
2172 if (where
== REDIS_HEAD
) {
2173 if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead");
2175 if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail");
2177 dictAdd(c
->dict
,c
->argv
[1],lobj
);
2178 incrRefCount(c
->argv
[1]);
2179 incrRefCount(c
->argv
[2]);
2181 lobj
= dictGetEntryVal(de
);
2182 if (lobj
->type
!= REDIS_LIST
) {
2183 addReply(c
,shared
.wrongtypeerr
);
2187 if (where
== REDIS_HEAD
) {
2188 if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead");
2190 if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail");
2192 incrRefCount(c
->argv
[2]);
2195 addReply(c
,shared
.ok
);
2198 static void lpushCommand(redisClient
*c
) {
2199 pushGenericCommand(c
,REDIS_HEAD
);
2202 static void rpushCommand(redisClient
*c
) {
2203 pushGenericCommand(c
,REDIS_TAIL
);
2206 static void llenCommand(redisClient
*c
) {
2210 de
= dictFind(c
->dict
,c
->argv
[1]);
2212 addReply(c
,shared
.czero
);
2215 robj
*o
= dictGetEntryVal(de
);
2216 if (o
->type
!= REDIS_LIST
) {
2217 addReply(c
,shared
.wrongtypeerr
);
2220 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
)));
2225 static void lindexCommand(redisClient
*c
) {
2227 int index
= atoi(c
->argv
[2]->ptr
);
2229 de
= dictFind(c
->dict
,c
->argv
[1]);
2231 addReply(c
,shared
.nullbulk
);
2233 robj
*o
= dictGetEntryVal(de
);
2235 if (o
->type
!= REDIS_LIST
) {
2236 addReply(c
,shared
.wrongtypeerr
);
2238 list
*list
= o
->ptr
;
2241 ln
= listIndex(list
, index
);
2243 addReply(c
,shared
.nullbulk
);
2245 robj
*ele
= listNodeValue(ln
);
2246 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2248 addReply(c
,shared
.crlf
);
2254 static void lsetCommand(redisClient
*c
) {
2256 int index
= atoi(c
->argv
[2]->ptr
);
2258 de
= dictFind(c
->dict
,c
->argv
[1]);
2260 addReply(c
,shared
.nokeyerr
);
2262 robj
*o
= dictGetEntryVal(de
);
2264 if (o
->type
!= REDIS_LIST
) {
2265 addReply(c
,shared
.wrongtypeerr
);
2267 list
*list
= o
->ptr
;
2270 ln
= listIndex(list
, index
);
2272 addReply(c
,shared
.outofrangeerr
);
2274 robj
*ele
= listNodeValue(ln
);
2277 listNodeValue(ln
) = c
->argv
[3];
2278 incrRefCount(c
->argv
[3]);
2279 addReply(c
,shared
.ok
);
2286 static void popGenericCommand(redisClient
*c
, int where
) {
2289 de
= dictFind(c
->dict
,c
->argv
[1]);
2291 addReply(c
,shared
.nullbulk
);
2293 robj
*o
= dictGetEntryVal(de
);
2295 if (o
->type
!= REDIS_LIST
) {
2296 addReply(c
,shared
.wrongtypeerr
);
2298 list
*list
= o
->ptr
;
2301 if (where
== REDIS_HEAD
)
2302 ln
= listFirst(list
);
2304 ln
= listLast(list
);
2307 addReply(c
,shared
.nullbulk
);
2309 robj
*ele
= listNodeValue(ln
);
2310 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2312 addReply(c
,shared
.crlf
);
2313 listDelNode(list
,ln
);
2320 static void lpopCommand(redisClient
*c
) {
2321 popGenericCommand(c
,REDIS_HEAD
);
2324 static void rpopCommand(redisClient
*c
) {
2325 popGenericCommand(c
,REDIS_TAIL
);
2328 static void lrangeCommand(redisClient
*c
) {
2330 int start
= atoi(c
->argv
[2]->ptr
);
2331 int end
= atoi(c
->argv
[3]->ptr
);
2333 de
= dictFind(c
->dict
,c
->argv
[1]);
2335 addReply(c
,shared
.nullmultibulk
);
2337 robj
*o
= dictGetEntryVal(de
);
2339 if (o
->type
!= REDIS_LIST
) {
2340 addReply(c
,shared
.wrongtypeerr
);
2342 list
*list
= o
->ptr
;
2344 int llen
= listLength(list
);
2348 /* convert negative indexes */
2349 if (start
< 0) start
= llen
+start
;
2350 if (end
< 0) end
= llen
+end
;
2351 if (start
< 0) start
= 0;
2352 if (end
< 0) end
= 0;
2354 /* indexes sanity checks */
2355 if (start
> end
|| start
>= llen
) {
2356 /* Out of range start or start > end result in empty list */
2357 addReply(c
,shared
.emptymultibulk
);
2360 if (end
>= llen
) end
= llen
-1;
2361 rangelen
= (end
-start
)+1;
2363 /* Return the result in form of a multi-bulk reply */
2364 ln
= listIndex(list
, start
);
2365 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
2366 for (j
= 0; j
< rangelen
; j
++) {
2367 ele
= listNodeValue(ln
);
2368 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2370 addReply(c
,shared
.crlf
);
2377 static void ltrimCommand(redisClient
*c
) {
2379 int start
= atoi(c
->argv
[2]->ptr
);
2380 int end
= atoi(c
->argv
[3]->ptr
);
2382 de
= dictFind(c
->dict
,c
->argv
[1]);
2384 addReply(c
,shared
.nokeyerr
);
2386 robj
*o
= dictGetEntryVal(de
);
2388 if (o
->type
!= REDIS_LIST
) {
2389 addReply(c
,shared
.wrongtypeerr
);
2391 list
*list
= o
->ptr
;
2393 int llen
= listLength(list
);
2394 int j
, ltrim
, rtrim
;
2396 /* convert negative indexes */
2397 if (start
< 0) start
= llen
+start
;
2398 if (end
< 0) end
= llen
+end
;
2399 if (start
< 0) start
= 0;
2400 if (end
< 0) end
= 0;
2402 /* indexes sanity checks */
2403 if (start
> end
|| start
>= llen
) {
2404 /* Out of range start or start > end result in empty list */
2408 if (end
>= llen
) end
= llen
-1;
2413 /* Remove list elements to perform the trim */
2414 for (j
= 0; j
< ltrim
; j
++) {
2415 ln
= listFirst(list
);
2416 listDelNode(list
,ln
);
2418 for (j
= 0; j
< rtrim
; j
++) {
2419 ln
= listLast(list
);
2420 listDelNode(list
,ln
);
2422 addReply(c
,shared
.ok
);
2428 static void lremCommand(redisClient
*c
) {
2431 de
= dictFind(c
->dict
,c
->argv
[1]);
2433 addReply(c
,shared
.nokeyerr
);
2435 robj
*o
= dictGetEntryVal(de
);
2437 if (o
->type
!= REDIS_LIST
) {
2438 addReply(c
,shared
.wrongtypeerr
);
2440 list
*list
= o
->ptr
;
2441 listNode
*ln
, *next
;
2442 int toremove
= atoi(c
->argv
[2]->ptr
);
2447 toremove
= -toremove
;
2450 ln
= fromtail
? list
->tail
: list
->head
;
2452 robj
*ele
= listNodeValue(ln
);
2454 next
= fromtail
? ln
->prev
: ln
->next
;
2455 if (sdscmp(ele
->ptr
,c
->argv
[3]->ptr
) == 0) {
2456 listDelNode(list
,ln
);
2459 if (toremove
&& removed
== toremove
) break;
2463 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
2468 /* ==================================== Sets ================================ */
2470 static void saddCommand(redisClient
*c
) {
2474 de
= dictFind(c
->dict
,c
->argv
[1]);
2476 set
= createSetObject();
2477 dictAdd(c
->dict
,c
->argv
[1],set
);
2478 incrRefCount(c
->argv
[1]);
2480 set
= dictGetEntryVal(de
);
2481 if (set
->type
!= REDIS_SET
) {
2482 addReply(c
,shared
.wrongtypeerr
);
2486 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
2487 incrRefCount(c
->argv
[2]);
2489 addReply(c
,shared
.cone
);
2491 addReply(c
,shared
.czero
);
2495 static void sremCommand(redisClient
*c
) {
2498 de
= dictFind(c
->dict
,c
->argv
[1]);
2500 addReply(c
,shared
.czero
);
2504 set
= dictGetEntryVal(de
);
2505 if (set
->type
!= REDIS_SET
) {
2506 addReply(c
,shared
.wrongtypeerr
);
2509 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
2511 addReply(c
,shared
.cone
);
2513 addReply(c
,shared
.czero
);
2518 static void sismemberCommand(redisClient
*c
) {
2521 de
= dictFind(c
->dict
,c
->argv
[1]);
2523 addReply(c
,shared
.czero
);
2527 set
= dictGetEntryVal(de
);
2528 if (set
->type
!= REDIS_SET
) {
2529 addReply(c
,shared
.wrongtypeerr
);
2532 if (dictFind(set
->ptr
,c
->argv
[2]))
2533 addReply(c
,shared
.cone
);
2535 addReply(c
,shared
.czero
);
2539 static void scardCommand(redisClient
*c
) {
2543 de
= dictFind(c
->dict
,c
->argv
[1]);
2545 addReply(c
,shared
.czero
);
2548 robj
*o
= dictGetEntryVal(de
);
2549 if (o
->type
!= REDIS_SET
) {
2550 addReply(c
,shared
.wrongtypeerr
);
2553 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",
2554 dictGetHashTableUsed(s
)));
2559 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
2560 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
2562 return dictGetHashTableUsed(*d1
)-dictGetHashTableUsed(*d2
);
2565 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
) {
2566 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
2569 robj
*lenobj
= NULL
, *dstset
= NULL
;
2570 int j
, cardinality
= 0;
2572 if (!dv
) oom("sinterCommand");
2573 for (j
= 0; j
< setsnum
; j
++) {
2577 de
= dictFind(c
->dict
,setskeys
[j
]);
2580 addReply(c
,shared
.nokeyerr
);
2583 setobj
= dictGetEntryVal(de
);
2584 if (setobj
->type
!= REDIS_SET
) {
2586 addReply(c
,shared
.wrongtypeerr
);
2589 dv
[j
] = setobj
->ptr
;
2591 /* Sort sets from the smallest to largest, this will improve our
2592 * algorithm's performace */
2593 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
2595 /* The first thing we should output is the total number of elements...
2596 * since this is a multi-bulk write, but at this stage we don't know
2597 * the intersection set size, so we use a trick, append an empty object
2598 * to the output list and save the pointer to later modify it with the
2601 lenobj
= createObject(REDIS_STRING
,NULL
);
2603 decrRefCount(lenobj
);
2605 /* If we have a target key where to store the resulting set
2606 * create this key with an empty set inside */
2607 dstset
= createSetObject();
2608 dictDelete(c
->dict
,dstkey
);
2609 dictAdd(c
->dict
,dstkey
,dstset
);
2610 incrRefCount(dstkey
);
2613 /* Iterate all the elements of the first (smallest) set, and test
2614 * the element against all the other sets, if at least one set does
2615 * not include the element it is discarded */
2616 di
= dictGetIterator(dv
[0]);
2617 if (!di
) oom("dictGetIterator");
2619 while((de
= dictNext(di
)) != NULL
) {
2622 for (j
= 1; j
< setsnum
; j
++)
2623 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
2625 continue; /* at least one set does not contain the member */
2626 ele
= dictGetEntryKey(de
);
2628 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(ele
->ptr
)));
2630 addReply(c
,shared
.crlf
);
2633 dictAdd(dstset
->ptr
,ele
,NULL
);
2637 dictReleaseIterator(di
);
2640 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",cardinality
);
2642 addReply(c
,shared
.ok
);
2646 static void sinterCommand(redisClient
*c
) {
2647 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
2650 static void sinterstoreCommand(redisClient
*c
) {
2651 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
2654 static void flushdbCommand(redisClient
*c
) {
2656 addReply(c
,shared
.ok
);
2657 rdbSave(server
.dbfilename
);
2660 static void flushallCommand(redisClient
*c
) {
2662 addReply(c
,shared
.ok
);
2663 rdbSave(server
.dbfilename
);
2666 redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
2667 redisSortOperation
*so
= zmalloc(sizeof(*so
));
2668 if (!so
) oom("createSortOperation");
2670 so
->pattern
= pattern
;
2674 /* Return the value associated to the key with a name obtained
2675 * substituting the first occurence of '*' in 'pattern' with 'subst' */
2676 robj
*lookupKeyByPattern(dict
*dict
, robj
*pattern
, robj
*subst
) {
2680 int prefixlen
, sublen
, postfixlen
;
2682 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
2686 char buf
[REDIS_SORTKEY_MAX
+1];
2690 spat
= pattern
->ptr
;
2692 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
2693 p
= strchr(spat
,'*');
2694 if (!p
) return NULL
;
2697 sublen
= sdslen(ssub
);
2698 postfixlen
= sdslen(spat
)-(prefixlen
+1);
2699 memcpy(keyname
.buf
,spat
,prefixlen
);
2700 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
2701 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
2702 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
2703 keyname
.len
= prefixlen
+sublen
+postfixlen
;
2705 keyobj
.refcount
= 1;
2706 keyobj
.type
= REDIS_STRING
;
2707 keyobj
.ptr
= ((char*)&keyname
)+(sizeof(long)*2);
2709 de
= dictFind(dict
,&keyobj
);
2710 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
2711 if (!de
) return NULL
;
2712 return dictGetEntryVal(de
);
2715 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
2716 * the additional parameter is not standard but a BSD-specific we have to
2717 * pass sorting parameters via the global 'server' structure */
2718 static int sortCompare(const void *s1
, const void *s2
) {
2719 const redisSortObject
*so1
= s1
, *so2
= s2
;
2722 if (!server
.sort_alpha
) {
2723 /* Numeric sorting. Here it's trivial as we precomputed scores */
2724 if (so1
->u
.score
> so2
->u
.score
) {
2726 } else if (so1
->u
.score
< so2
->u
.score
) {
2732 /* Alphanumeric sorting */
2733 if (server
.sort_bypattern
) {
2734 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
2735 /* At least one compare object is NULL */
2736 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
2738 else if (so1
->u
.cmpobj
== NULL
)
2743 /* We have both the objects, use strcoll */
2744 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
2747 /* Compare elements directly */
2748 cmp
= strcoll(so1
->obj
->ptr
,so2
->obj
->ptr
);
2751 return server
.sort_desc
? -cmp
: cmp
;
2754 /* The SORT command is the most complex command in Redis. Warning: this code
2755 * is optimized for speed and a bit less for readability */
2756 static void sortCommand(redisClient
*c
) {
2760 int desc
= 0, alpha
= 0;
2761 int limit_start
= 0, limit_count
= -1, start
, end
;
2762 int j
, dontsort
= 0, vectorlen
;
2763 int getop
= 0; /* GET operation counter */
2764 robj
*sortval
, *sortby
= NULL
;
2765 redisSortObject
*vector
; /* Resulting vector to sort */
2767 /* Lookup the key to sort. It must be of the right types */
2768 de
= dictFind(c
->dict
,c
->argv
[1]);
2770 addReply(c
,shared
.nokeyerr
);
2773 sortval
= dictGetEntryVal(de
);
2774 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
) {
2775 addReply(c
,shared
.wrongtypeerr
);
2779 /* Create a list of operations to perform for every sorted element.
2780 * Operations can be GET/DEL/INCR/DECR */
2781 operations
= listCreate();
2782 listSetFreeMethod(operations
,zfree
);
2785 /* Now we need to protect sortval incrementing its count, in the future
2786 * SORT may have options able to overwrite/delete keys during the sorting
2787 * and the sorted key itself may get destroied */
2788 incrRefCount(sortval
);
2790 /* The SORT command has an SQL-alike syntax, parse it */
2791 while(j
< c
->argc
) {
2792 int leftargs
= c
->argc
-j
-1;
2793 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
2795 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
2797 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
2799 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
2800 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
2801 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
2803 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
2804 sortby
= c
->argv
[j
+1];
2805 /* If the BY pattern does not contain '*', i.e. it is constant,
2806 * we don't need to sort nor to lookup the weight keys. */
2807 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
2809 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
2810 listAddNodeTail(operations
,createSortOperation(
2811 REDIS_SORT_GET
,c
->argv
[j
+1]));
2814 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"del") && leftargs
>= 1) {
2815 listAddNodeTail(operations
,createSortOperation(
2816 REDIS_SORT_DEL
,c
->argv
[j
+1]));
2818 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"incr") && leftargs
>= 1) {
2819 listAddNodeTail(operations
,createSortOperation(
2820 REDIS_SORT_INCR
,c
->argv
[j
+1]));
2822 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
2823 listAddNodeTail(operations
,createSortOperation(
2824 REDIS_SORT_DECR
,c
->argv
[j
+1]));
2827 decrRefCount(sortval
);
2828 listRelease(operations
);
2829 addReply(c
,shared
.syntaxerr
);
2835 /* Load the sorting vector with all the objects to sort */
2836 vectorlen
= (sortval
->type
== REDIS_LIST
) ?
2837 listLength((list
*)sortval
->ptr
) :
2838 dictGetHashTableUsed((dict
*)sortval
->ptr
);
2839 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
2840 if (!vector
) oom("allocating objects vector for SORT");
2842 if (sortval
->type
== REDIS_LIST
) {
2843 list
*list
= sortval
->ptr
;
2844 listNode
*ln
= list
->head
;
2846 robj
*ele
= ln
->value
;
2847 vector
[j
].obj
= ele
;
2848 vector
[j
].u
.score
= 0;
2849 vector
[j
].u
.cmpobj
= NULL
;
2854 dict
*set
= sortval
->ptr
;
2858 di
= dictGetIterator(set
);
2859 if (!di
) oom("dictGetIterator");
2860 while((setele
= dictNext(di
)) != NULL
) {
2861 vector
[j
].obj
= dictGetEntryKey(setele
);
2862 vector
[j
].u
.score
= 0;
2863 vector
[j
].u
.cmpobj
= NULL
;
2866 dictReleaseIterator(di
);
2868 assert(j
== vectorlen
);
2870 /* Now it's time to load the right scores in the sorting vector */
2871 if (dontsort
== 0) {
2872 for (j
= 0; j
< vectorlen
; j
++) {
2876 byval
= lookupKeyByPattern(c
->dict
,sortby
,vector
[j
].obj
);
2877 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
2879 vector
[j
].u
.cmpobj
= byval
;
2880 incrRefCount(byval
);
2882 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
2885 if (!alpha
) vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
2890 /* We are ready to sort the vector... perform a bit of sanity check
2891 * on the LIMIT option too. We'll use a partial version of quicksort. */
2892 start
= (limit_start
< 0) ? 0 : limit_start
;
2893 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
2894 if (start
>= vectorlen
) {
2895 start
= vectorlen
-1;
2898 if (end
>= vectorlen
) end
= vectorlen
-1;
2900 if (dontsort
== 0) {
2901 server
.sort_desc
= desc
;
2902 server
.sort_alpha
= alpha
;
2903 server
.sort_bypattern
= sortby
? 1 : 0;
2904 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
2907 /* Send command output to the output buffer, performing the specified
2908 * GET/DEL/INCR/DECR operations if any. */
2909 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
2910 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
2911 for (j
= start
; j
<= end
; j
++) {
2912 listNode
*ln
= operations
->head
;
2914 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
2915 sdslen(vector
[j
].obj
->ptr
)));
2916 addReply(c
,vector
[j
].obj
);
2917 addReply(c
,shared
.crlf
);
2920 redisSortOperation
*sop
= ln
->value
;
2921 robj
*val
= lookupKeyByPattern(c
->dict
,sop
->pattern
,
2924 if (sop
->type
== REDIS_SORT_GET
) {
2925 if (!val
|| val
->type
!= REDIS_STRING
) {
2926 addReply(c
,shared
.nullbulk
);
2928 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
2931 addReply(c
,shared
.crlf
);
2933 } else if (sop
->type
== REDIS_SORT_DEL
) {
2941 decrRefCount(sortval
);
2942 listRelease(operations
);
2943 for (j
= 0; j
< vectorlen
; j
++) {
2944 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
2945 decrRefCount(vector
[j
].u
.cmpobj
);
2950 static void infoCommand(redisClient
*c
) {
2952 time_t uptime
= time(NULL
)-server
.stat_starttime
;
2954 info
= sdscatprintf(sdsempty(),
2955 "redis_version:%s\r\n"
2956 "connected_clients:%d\r\n"
2957 "connected_slaves:%d\r\n"
2958 "used_memory:%d\r\n"
2959 "changes_since_last_save:%lld\r\n"
2960 "last_save_time:%d\r\n"
2961 "total_connections_received:%lld\r\n"
2962 "total_commands_processed:%lld\r\n"
2963 "uptime_in_seconds:%d\r\n"
2964 "uptime_in_days:%d\r\n"
2966 listLength(server
.clients
)-listLength(server
.slaves
),
2967 listLength(server
.slaves
),
2971 server
.stat_numconnections
,
2972 server
.stat_numcommands
,
2976 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(info
)));
2977 addReplySds(c
,info
);
2978 addReply(c
,shared
.crlf
);
2981 /* =============================== Replication ============================= */
2983 /* Send the whole output buffer syncronously to the slave. This a general operation in theory, but it is actually useful only for replication. */
2984 static int flushClientOutput(redisClient
*c
) {
2986 time_t start
= time(NULL
);
2988 while(listLength(c
->reply
)) {
2989 if (time(NULL
)-start
> 5) return REDIS_ERR
; /* 5 seconds timeout */
2990 retval
= aeWait(c
->fd
,AE_WRITABLE
,1000);
2993 } else if (retval
& AE_WRITABLE
) {
2994 sendReplyToClient(NULL
, c
->fd
, c
, AE_WRITABLE
);
3000 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
3001 ssize_t nwritten
, ret
= size
;
3002 time_t start
= time(NULL
);
3006 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
3007 nwritten
= write(fd
,ptr
,size
);
3008 if (nwritten
== -1) return -1;
3012 if ((time(NULL
)-start
) > timeout
) {
3020 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
3021 ssize_t nread
, totread
= 0;
3022 time_t start
= time(NULL
);
3026 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
3027 nread
= read(fd
,ptr
,size
);
3028 if (nread
== -1) return -1;
3033 if ((time(NULL
)-start
) > timeout
) {
3041 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
3048 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
3051 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
3062 static void syncCommand(redisClient
*c
) {
3065 time_t start
= time(NULL
);
3068 /* ignore SYNC if aleady slave or in monitor mode */
3069 if (c
->flags
& REDIS_SLAVE
) return;
3071 redisLog(REDIS_NOTICE
,"Slave ask for syncronization");
3072 if (flushClientOutput(c
) == REDIS_ERR
||
3073 rdbSave(server
.dbfilename
) != REDIS_OK
)
3076 fd
= open(server
.dbfilename
, O_RDONLY
);
3077 if (fd
== -1 || fstat(fd
,&sb
) == -1) goto closeconn
;
3080 snprintf(sizebuf
,32,"$%d\r\n",len
);
3081 if (syncWrite(c
->fd
,sizebuf
,strlen(sizebuf
),5) == -1) goto closeconn
;
3086 if (time(NULL
)-start
> REDIS_MAX_SYNC_TIME
) goto closeconn
;
3087 nread
= read(fd
,buf
,1024);
3088 if (nread
== -1) goto closeconn
;
3090 if (syncWrite(c
->fd
,buf
,nread
,5) == -1) goto closeconn
;
3092 if (syncWrite(c
->fd
,"\r\n",2,5) == -1) goto closeconn
;
3094 c
->flags
|= REDIS_SLAVE
;
3096 if (!listAddNodeTail(server
.slaves
,c
)) oom("listAddNodeTail");
3097 redisLog(REDIS_NOTICE
,"Syncronization with slave succeeded");
3101 if (fd
!= -1) close(fd
);
3102 c
->flags
|= REDIS_CLOSE
;
3103 redisLog(REDIS_WARNING
,"Syncronization with slave failed");
3107 static int syncWithMaster(void) {
3108 char buf
[1024], tmpfile
[256];
3110 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
3114 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
3118 /* Issue the SYNC command */
3119 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
3121 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
3125 /* Read the bulk write count */
3126 if (syncReadLine(fd
,buf
,1024,5) == -1) {
3128 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
3132 dumpsize
= atoi(buf
+1);
3133 redisLog(REDIS_NOTICE
,"Receiving %d bytes data dump from MASTER",dumpsize
);
3134 /* Read the bulk write data on a temp file */
3135 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
3136 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644);
3139 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
3143 int nread
, nwritten
;
3145 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
3147 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
3153 nwritten
= write(dfd
,buf
,nread
);
3154 if (nwritten
== -1) {
3155 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
3163 if (rename(tmpfile
,server
.dbfilename
) == -1) {
3164 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
3170 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
3171 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
3175 server
.master
= createClient(fd
);
3176 server
.master
->flags
|= REDIS_MASTER
;
3177 server
.replstate
= REDIS_REPL_CONNECTED
;
3181 static void monitorCommand(redisClient
*c
) {
3182 /* ignore MONITOR if aleady slave or in monitor mode */
3183 if (c
->flags
& REDIS_SLAVE
) return;
3185 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
3187 if (!listAddNodeTail(server
.monitors
,c
)) oom("listAddNodeTail");
3188 addReply(c
,shared
.ok
);
3191 /* =================================== Main! ================================ */
3193 static void daemonize(void) {
3197 if (fork() != 0) exit(0); /* parent exits */
3198 setsid(); /* create a new session */
3200 /* Every output goes to /dev/null. If Redis is daemonized but
3201 * the 'logfile' is set to 'stdout' in the configuration file
3202 * it will not log at all. */
3203 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
3204 dup2(fd
, STDIN_FILENO
);
3205 dup2(fd
, STDOUT_FILENO
);
3206 dup2(fd
, STDERR_FILENO
);
3207 if (fd
> STDERR_FILENO
) close(fd
);
3209 /* Try to write the pid file */
3210 fp
= fopen(server
.pidfile
,"w");
3212 fprintf(fp
,"%d\n",getpid());
3217 int main(int argc
, char **argv
) {
3220 ResetServerSaveParams();
3221 loadServerConfig(argv
[1]);
3222 } else if (argc
> 2) {
3223 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
3227 if (server
.daemonize
) daemonize();
3228 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
3229 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
3230 redisLog(REDIS_NOTICE
,"DB loaded from disk");
3231 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
3232 acceptHandler
, NULL
, NULL
) == AE_ERR
) oom("creating file event");
3233 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
3235 aeDeleteEventLoop(server
.el
);