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_ENCVAL 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
,2,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
;
1675 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
1676 type
= (buf
[0]&0xC0)>>6;
1677 if (type
== REDIS_RDB_6BITLEN
) {
1678 /* Read a 6 bit len */
1680 } else if (type
== REDIS_RDB_14BITLEN
) {
1681 /* Read a 14 bit len */
1682 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
1683 return ((buf
[0]&0x3F)<<8)|buf
[1];
1685 /* Read a 32 bit len */
1686 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
1692 static robj
*rdbLoadStringObject(FILE*fp
,int rdbver
) {
1693 uint32_t len
= rdbLoadLen(fp
,rdbver
);
1696 if (len
== REDIS_RDB_LENERR
) return NULL
;
1697 val
= sdsnewlen(NULL
,len
);
1698 if (len
&& fread(val
,len
,1,fp
) == 0) {
1702 return tryObjectSharing(createObject(REDIS_STRING
,val
));
1705 static int rdbLoad(char *filename
) {
1707 robj
*keyobj
= NULL
;
1711 dict
*d
= server
.dict
[0];
1714 fp
= fopen(filename
,"r");
1715 if (!fp
) return REDIS_ERR
;
1716 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
1718 if (memcmp(buf
,"REDIS",5) != 0) {
1720 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
1723 rdbver
= atoi(buf
+5);
1726 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
1733 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
1734 if (type
== REDIS_EOF
) break;
1735 /* Handle SELECT DB opcode as a special case */
1736 if (type
== REDIS_SELECTDB
) {
1737 if ((dbid
= rdbLoadLen(fp
,rdbver
)) == REDIS_RDB_LENERR
) goto eoferr
;
1738 if (dbid
>= (unsigned)server
.dbnum
) {
1739 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
1742 d
= server
.dict
[dbid
];
1746 if ((keyobj
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1748 if (type
== REDIS_STRING
) {
1749 /* Read string value */
1750 if ((o
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1751 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
1752 /* Read list/set value */
1755 if ((listlen
= rdbLoadLen(fp
,rdbver
)) == REDIS_RDB_LENERR
)
1757 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
1758 /* Load every single element of the list/set */
1762 if ((ele
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1763 if (type
== REDIS_LIST
) {
1764 if (!listAddNodeTail((list
*)o
->ptr
,ele
))
1765 oom("listAddNodeTail");
1767 if (dictAdd((dict
*)o
->ptr
,ele
,NULL
) == DICT_ERR
)
1774 /* Add the new object in the hash table */
1775 retval
= dictAdd(d
,keyobj
,o
);
1776 if (retval
== DICT_ERR
) {
1777 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
1785 eoferr
: /* unexpected end of file is handled here with a fatal exit */
1786 decrRefCount(keyobj
);
1787 redisLog(REDIS_WARNING
,"Short read loading DB. Unrecoverable error, exiting now.");
1789 return REDIS_ERR
; /* Just to avoid warning */
1792 /*================================== Commands =============================== */
1794 static void authCommand(redisClient
*c
) {
1795 if (!strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1796 c
->authenticated
= 1;
1797 addReply(c
,shared
.ok
);
1799 c
->authenticated
= 0;
1800 addReply(c
,shared
.err
);
1804 static void pingCommand(redisClient
*c
) {
1805 addReply(c
,shared
.pong
);
1808 static void echoCommand(redisClient
*c
) {
1809 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
1810 (int)sdslen(c
->argv
[1]->ptr
)));
1811 addReply(c
,c
->argv
[1]);
1812 addReply(c
,shared
.crlf
);
1815 /*=================================== Strings =============================== */
1817 static void setGenericCommand(redisClient
*c
, int nx
) {
1820 retval
= dictAdd(c
->dict
,c
->argv
[1],c
->argv
[2]);
1821 if (retval
== DICT_ERR
) {
1823 dictReplace(c
->dict
,c
->argv
[1],c
->argv
[2]);
1824 incrRefCount(c
->argv
[2]);
1826 addReply(c
,shared
.czero
);
1830 incrRefCount(c
->argv
[1]);
1831 incrRefCount(c
->argv
[2]);
1834 addReply(c
, nx
? shared
.cone
: shared
.ok
);
1837 static void setCommand(redisClient
*c
) {
1838 setGenericCommand(c
,0);
1841 static void setnxCommand(redisClient
*c
) {
1842 setGenericCommand(c
,1);
1845 static void getCommand(redisClient
*c
) {
1848 de
= dictFind(c
->dict
,c
->argv
[1]);
1850 addReply(c
,shared
.nullbulk
);
1852 robj
*o
= dictGetEntryVal(de
);
1854 if (o
->type
!= REDIS_STRING
) {
1855 addReply(c
,shared
.wrongtypeerr
);
1857 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o
->ptr
)));
1859 addReply(c
,shared
.crlf
);
1864 static void mgetCommand(redisClient
*c
) {
1868 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
1869 for (j
= 1; j
< c
->argc
; j
++) {
1870 de
= dictFind(c
->dict
,c
->argv
[j
]);
1872 addReply(c
,shared
.nullbulk
);
1874 robj
*o
= dictGetEntryVal(de
);
1876 if (o
->type
!= REDIS_STRING
) {
1877 addReply(c
,shared
.nullbulk
);
1879 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o
->ptr
)));
1881 addReply(c
,shared
.crlf
);
1887 static void incrDecrCommand(redisClient
*c
, int incr
) {
1893 de
= dictFind(c
->dict
,c
->argv
[1]);
1897 robj
*o
= dictGetEntryVal(de
);
1899 if (o
->type
!= REDIS_STRING
) {
1904 value
= strtoll(o
->ptr
, &eptr
, 10);
1909 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
1910 retval
= dictAdd(c
->dict
,c
->argv
[1],o
);
1911 if (retval
== DICT_ERR
) {
1912 dictReplace(c
->dict
,c
->argv
[1],o
);
1914 incrRefCount(c
->argv
[1]);
1917 addReply(c
,shared
.colon
);
1919 addReply(c
,shared
.crlf
);
1922 static void incrCommand(redisClient
*c
) {
1923 incrDecrCommand(c
,1);
1926 static void decrCommand(redisClient
*c
) {
1927 incrDecrCommand(c
,-1);
1930 static void incrbyCommand(redisClient
*c
) {
1931 int incr
= atoi(c
->argv
[2]->ptr
);
1932 incrDecrCommand(c
,incr
);
1935 static void decrbyCommand(redisClient
*c
) {
1936 int incr
= atoi(c
->argv
[2]->ptr
);
1937 incrDecrCommand(c
,-incr
);
1940 /* ========================= Type agnostic commands ========================= */
1942 static void delCommand(redisClient
*c
) {
1943 if (dictDelete(c
->dict
,c
->argv
[1]) == DICT_OK
) {
1945 addReply(c
,shared
.cone
);
1947 addReply(c
,shared
.czero
);
1951 static void existsCommand(redisClient
*c
) {
1954 de
= dictFind(c
->dict
,c
->argv
[1]);
1956 addReply(c
,shared
.czero
);
1958 addReply(c
,shared
.cone
);
1961 static void selectCommand(redisClient
*c
) {
1962 int id
= atoi(c
->argv
[1]->ptr
);
1964 if (selectDb(c
,id
) == REDIS_ERR
) {
1965 addReplySds(c
,"-ERR invalid DB index\r\n");
1967 addReply(c
,shared
.ok
);
1971 static void randomkeyCommand(redisClient
*c
) {
1974 de
= dictGetRandomKey(c
->dict
);
1976 addReply(c
,shared
.crlf
);
1978 addReply(c
,shared
.plus
);
1979 addReply(c
,dictGetEntryKey(de
));
1980 addReply(c
,shared
.crlf
);
1984 static void keysCommand(redisClient
*c
) {
1987 sds pattern
= c
->argv
[1]->ptr
;
1988 int plen
= sdslen(pattern
);
1989 int numkeys
= 0, keyslen
= 0;
1990 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
1992 di
= dictGetIterator(c
->dict
);
1993 if (!di
) oom("dictGetIterator");
1995 decrRefCount(lenobj
);
1996 while((de
= dictNext(di
)) != NULL
) {
1997 robj
*keyobj
= dictGetEntryKey(de
);
1998 sds key
= keyobj
->ptr
;
1999 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
2000 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
2002 addReply(c
,shared
.space
);
2005 keyslen
+= sdslen(key
);
2008 dictReleaseIterator(di
);
2009 lenobj
->ptr
= sdscatprintf(sdsempty(),"$%lu\r\n",keyslen
+(numkeys
? (numkeys
-1) : 0));
2010 addReply(c
,shared
.crlf
);
2013 static void dbsizeCommand(redisClient
*c
) {
2015 sdscatprintf(sdsempty(),":%lu\r\n",dictGetHashTableUsed(c
->dict
)));
2018 static void lastsaveCommand(redisClient
*c
) {
2020 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
2023 static void typeCommand(redisClient
*c
) {
2027 de
= dictFind(c
->dict
,c
->argv
[1]);
2031 robj
*o
= dictGetEntryVal(de
);
2034 case REDIS_STRING
: type
= "+string"; break;
2035 case REDIS_LIST
: type
= "+list"; break;
2036 case REDIS_SET
: type
= "+set"; break;
2037 default: type
= "unknown"; break;
2040 addReplySds(c
,sdsnew(type
));
2041 addReply(c
,shared
.crlf
);
2044 static void saveCommand(redisClient
*c
) {
2045 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
2046 addReply(c
,shared
.ok
);
2048 addReply(c
,shared
.err
);
2052 static void bgsaveCommand(redisClient
*c
) {
2053 if (server
.bgsaveinprogress
) {
2054 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
2057 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
2058 addReply(c
,shared
.ok
);
2060 addReply(c
,shared
.err
);
2064 static void shutdownCommand(redisClient
*c
) {
2065 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
2066 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
2067 if (server
.daemonize
) {
2068 unlink(server
.pidfile
);
2070 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
2073 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
2074 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
2078 static void renameGenericCommand(redisClient
*c
, int nx
) {
2082 /* To use the same key as src and dst is probably an error */
2083 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
2084 addReply(c
,shared
.sameobjecterr
);
2088 de
= dictFind(c
->dict
,c
->argv
[1]);
2090 addReply(c
,shared
.nokeyerr
);
2093 o
= dictGetEntryVal(de
);
2095 if (dictAdd(c
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
2098 addReply(c
,shared
.czero
);
2101 dictReplace(c
->dict
,c
->argv
[2],o
);
2103 incrRefCount(c
->argv
[2]);
2105 dictDelete(c
->dict
,c
->argv
[1]);
2107 addReply(c
,nx
? shared
.cone
: shared
.ok
);
2110 static void renameCommand(redisClient
*c
) {
2111 renameGenericCommand(c
,0);
2114 static void renamenxCommand(redisClient
*c
) {
2115 renameGenericCommand(c
,1);
2118 static void moveCommand(redisClient
*c
) {
2124 /* Obtain source and target DB pointers */
2127 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
2128 addReply(c
,shared
.outofrangeerr
);
2135 /* If the user is moving using as target the same
2136 * DB as the source DB it is probably an error. */
2138 addReply(c
,shared
.sameobjecterr
);
2142 /* Check if the element exists and get a reference */
2143 de
= dictFind(c
->dict
,c
->argv
[1]);
2145 addReply(c
,shared
.czero
);
2149 /* Try to add the element to the target DB */
2150 key
= dictGetEntryKey(de
);
2151 o
= dictGetEntryVal(de
);
2152 if (dictAdd(dst
,key
,o
) == DICT_ERR
) {
2153 addReply(c
,shared
.czero
);
2159 /* OK! key moved, free the entry in the source DB */
2160 dictDelete(src
,c
->argv
[1]);
2162 addReply(c
,shared
.cone
);
2165 /* =================================== Lists ================================ */
2166 static void pushGenericCommand(redisClient
*c
, int where
) {
2171 de
= dictFind(c
->dict
,c
->argv
[1]);
2173 lobj
= createListObject();
2175 if (where
== REDIS_HEAD
) {
2176 if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead");
2178 if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail");
2180 dictAdd(c
->dict
,c
->argv
[1],lobj
);
2181 incrRefCount(c
->argv
[1]);
2182 incrRefCount(c
->argv
[2]);
2184 lobj
= dictGetEntryVal(de
);
2185 if (lobj
->type
!= REDIS_LIST
) {
2186 addReply(c
,shared
.wrongtypeerr
);
2190 if (where
== REDIS_HEAD
) {
2191 if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead");
2193 if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail");
2195 incrRefCount(c
->argv
[2]);
2198 addReply(c
,shared
.ok
);
2201 static void lpushCommand(redisClient
*c
) {
2202 pushGenericCommand(c
,REDIS_HEAD
);
2205 static void rpushCommand(redisClient
*c
) {
2206 pushGenericCommand(c
,REDIS_TAIL
);
2209 static void llenCommand(redisClient
*c
) {
2213 de
= dictFind(c
->dict
,c
->argv
[1]);
2215 addReply(c
,shared
.czero
);
2218 robj
*o
= dictGetEntryVal(de
);
2219 if (o
->type
!= REDIS_LIST
) {
2220 addReply(c
,shared
.wrongtypeerr
);
2223 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
)));
2228 static void lindexCommand(redisClient
*c
) {
2230 int index
= atoi(c
->argv
[2]->ptr
);
2232 de
= dictFind(c
->dict
,c
->argv
[1]);
2234 addReply(c
,shared
.nullbulk
);
2236 robj
*o
= dictGetEntryVal(de
);
2238 if (o
->type
!= REDIS_LIST
) {
2239 addReply(c
,shared
.wrongtypeerr
);
2241 list
*list
= o
->ptr
;
2244 ln
= listIndex(list
, index
);
2246 addReply(c
,shared
.nullbulk
);
2248 robj
*ele
= listNodeValue(ln
);
2249 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2251 addReply(c
,shared
.crlf
);
2257 static void lsetCommand(redisClient
*c
) {
2259 int index
= atoi(c
->argv
[2]->ptr
);
2261 de
= dictFind(c
->dict
,c
->argv
[1]);
2263 addReply(c
,shared
.nokeyerr
);
2265 robj
*o
= dictGetEntryVal(de
);
2267 if (o
->type
!= REDIS_LIST
) {
2268 addReply(c
,shared
.wrongtypeerr
);
2270 list
*list
= o
->ptr
;
2273 ln
= listIndex(list
, index
);
2275 addReply(c
,shared
.outofrangeerr
);
2277 robj
*ele
= listNodeValue(ln
);
2280 listNodeValue(ln
) = c
->argv
[3];
2281 incrRefCount(c
->argv
[3]);
2282 addReply(c
,shared
.ok
);
2289 static void popGenericCommand(redisClient
*c
, int where
) {
2292 de
= dictFind(c
->dict
,c
->argv
[1]);
2294 addReply(c
,shared
.nullbulk
);
2296 robj
*o
= dictGetEntryVal(de
);
2298 if (o
->type
!= REDIS_LIST
) {
2299 addReply(c
,shared
.wrongtypeerr
);
2301 list
*list
= o
->ptr
;
2304 if (where
== REDIS_HEAD
)
2305 ln
= listFirst(list
);
2307 ln
= listLast(list
);
2310 addReply(c
,shared
.nullbulk
);
2312 robj
*ele
= listNodeValue(ln
);
2313 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2315 addReply(c
,shared
.crlf
);
2316 listDelNode(list
,ln
);
2323 static void lpopCommand(redisClient
*c
) {
2324 popGenericCommand(c
,REDIS_HEAD
);
2327 static void rpopCommand(redisClient
*c
) {
2328 popGenericCommand(c
,REDIS_TAIL
);
2331 static void lrangeCommand(redisClient
*c
) {
2333 int start
= atoi(c
->argv
[2]->ptr
);
2334 int end
= atoi(c
->argv
[3]->ptr
);
2336 de
= dictFind(c
->dict
,c
->argv
[1]);
2338 addReply(c
,shared
.nullmultibulk
);
2340 robj
*o
= dictGetEntryVal(de
);
2342 if (o
->type
!= REDIS_LIST
) {
2343 addReply(c
,shared
.wrongtypeerr
);
2345 list
*list
= o
->ptr
;
2347 int llen
= listLength(list
);
2351 /* convert negative indexes */
2352 if (start
< 0) start
= llen
+start
;
2353 if (end
< 0) end
= llen
+end
;
2354 if (start
< 0) start
= 0;
2355 if (end
< 0) end
= 0;
2357 /* indexes sanity checks */
2358 if (start
> end
|| start
>= llen
) {
2359 /* Out of range start or start > end result in empty list */
2360 addReply(c
,shared
.emptymultibulk
);
2363 if (end
>= llen
) end
= llen
-1;
2364 rangelen
= (end
-start
)+1;
2366 /* Return the result in form of a multi-bulk reply */
2367 ln
= listIndex(list
, start
);
2368 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
2369 for (j
= 0; j
< rangelen
; j
++) {
2370 ele
= listNodeValue(ln
);
2371 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2373 addReply(c
,shared
.crlf
);
2380 static void ltrimCommand(redisClient
*c
) {
2382 int start
= atoi(c
->argv
[2]->ptr
);
2383 int end
= atoi(c
->argv
[3]->ptr
);
2385 de
= dictFind(c
->dict
,c
->argv
[1]);
2387 addReply(c
,shared
.nokeyerr
);
2389 robj
*o
= dictGetEntryVal(de
);
2391 if (o
->type
!= REDIS_LIST
) {
2392 addReply(c
,shared
.wrongtypeerr
);
2394 list
*list
= o
->ptr
;
2396 int llen
= listLength(list
);
2397 int j
, ltrim
, rtrim
;
2399 /* convert negative indexes */
2400 if (start
< 0) start
= llen
+start
;
2401 if (end
< 0) end
= llen
+end
;
2402 if (start
< 0) start
= 0;
2403 if (end
< 0) end
= 0;
2405 /* indexes sanity checks */
2406 if (start
> end
|| start
>= llen
) {
2407 /* Out of range start or start > end result in empty list */
2411 if (end
>= llen
) end
= llen
-1;
2416 /* Remove list elements to perform the trim */
2417 for (j
= 0; j
< ltrim
; j
++) {
2418 ln
= listFirst(list
);
2419 listDelNode(list
,ln
);
2421 for (j
= 0; j
< rtrim
; j
++) {
2422 ln
= listLast(list
);
2423 listDelNode(list
,ln
);
2425 addReply(c
,shared
.ok
);
2431 static void lremCommand(redisClient
*c
) {
2434 de
= dictFind(c
->dict
,c
->argv
[1]);
2436 addReply(c
,shared
.nokeyerr
);
2438 robj
*o
= dictGetEntryVal(de
);
2440 if (o
->type
!= REDIS_LIST
) {
2441 addReply(c
,shared
.wrongtypeerr
);
2443 list
*list
= o
->ptr
;
2444 listNode
*ln
, *next
;
2445 int toremove
= atoi(c
->argv
[2]->ptr
);
2450 toremove
= -toremove
;
2453 ln
= fromtail
? list
->tail
: list
->head
;
2455 robj
*ele
= listNodeValue(ln
);
2457 next
= fromtail
? ln
->prev
: ln
->next
;
2458 if (sdscmp(ele
->ptr
,c
->argv
[3]->ptr
) == 0) {
2459 listDelNode(list
,ln
);
2462 if (toremove
&& removed
== toremove
) break;
2466 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
2471 /* ==================================== Sets ================================ */
2473 static void saddCommand(redisClient
*c
) {
2477 de
= dictFind(c
->dict
,c
->argv
[1]);
2479 set
= createSetObject();
2480 dictAdd(c
->dict
,c
->argv
[1],set
);
2481 incrRefCount(c
->argv
[1]);
2483 set
= dictGetEntryVal(de
);
2484 if (set
->type
!= REDIS_SET
) {
2485 addReply(c
,shared
.wrongtypeerr
);
2489 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
2490 incrRefCount(c
->argv
[2]);
2492 addReply(c
,shared
.cone
);
2494 addReply(c
,shared
.czero
);
2498 static void sremCommand(redisClient
*c
) {
2501 de
= dictFind(c
->dict
,c
->argv
[1]);
2503 addReply(c
,shared
.czero
);
2507 set
= dictGetEntryVal(de
);
2508 if (set
->type
!= REDIS_SET
) {
2509 addReply(c
,shared
.wrongtypeerr
);
2512 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
2514 addReply(c
,shared
.cone
);
2516 addReply(c
,shared
.czero
);
2521 static void sismemberCommand(redisClient
*c
) {
2524 de
= dictFind(c
->dict
,c
->argv
[1]);
2526 addReply(c
,shared
.czero
);
2530 set
= dictGetEntryVal(de
);
2531 if (set
->type
!= REDIS_SET
) {
2532 addReply(c
,shared
.wrongtypeerr
);
2535 if (dictFind(set
->ptr
,c
->argv
[2]))
2536 addReply(c
,shared
.cone
);
2538 addReply(c
,shared
.czero
);
2542 static void scardCommand(redisClient
*c
) {
2546 de
= dictFind(c
->dict
,c
->argv
[1]);
2548 addReply(c
,shared
.czero
);
2551 robj
*o
= dictGetEntryVal(de
);
2552 if (o
->type
!= REDIS_SET
) {
2553 addReply(c
,shared
.wrongtypeerr
);
2556 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",
2557 dictGetHashTableUsed(s
)));
2562 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
2563 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
2565 return dictGetHashTableUsed(*d1
)-dictGetHashTableUsed(*d2
);
2568 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
) {
2569 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
2572 robj
*lenobj
= NULL
, *dstset
= NULL
;
2573 int j
, cardinality
= 0;
2575 if (!dv
) oom("sinterCommand");
2576 for (j
= 0; j
< setsnum
; j
++) {
2580 de
= dictFind(c
->dict
,setskeys
[j
]);
2583 addReply(c
,shared
.nokeyerr
);
2586 setobj
= dictGetEntryVal(de
);
2587 if (setobj
->type
!= REDIS_SET
) {
2589 addReply(c
,shared
.wrongtypeerr
);
2592 dv
[j
] = setobj
->ptr
;
2594 /* Sort sets from the smallest to largest, this will improve our
2595 * algorithm's performace */
2596 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
2598 /* The first thing we should output is the total number of elements...
2599 * since this is a multi-bulk write, but at this stage we don't know
2600 * the intersection set size, so we use a trick, append an empty object
2601 * to the output list and save the pointer to later modify it with the
2604 lenobj
= createObject(REDIS_STRING
,NULL
);
2606 decrRefCount(lenobj
);
2608 /* If we have a target key where to store the resulting set
2609 * create this key with an empty set inside */
2610 dstset
= createSetObject();
2611 dictDelete(c
->dict
,dstkey
);
2612 dictAdd(c
->dict
,dstkey
,dstset
);
2613 incrRefCount(dstkey
);
2616 /* Iterate all the elements of the first (smallest) set, and test
2617 * the element against all the other sets, if at least one set does
2618 * not include the element it is discarded */
2619 di
= dictGetIterator(dv
[0]);
2620 if (!di
) oom("dictGetIterator");
2622 while((de
= dictNext(di
)) != NULL
) {
2625 for (j
= 1; j
< setsnum
; j
++)
2626 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
2628 continue; /* at least one set does not contain the member */
2629 ele
= dictGetEntryKey(de
);
2631 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(ele
->ptr
)));
2633 addReply(c
,shared
.crlf
);
2636 dictAdd(dstset
->ptr
,ele
,NULL
);
2640 dictReleaseIterator(di
);
2643 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",cardinality
);
2645 addReply(c
,shared
.ok
);
2649 static void sinterCommand(redisClient
*c
) {
2650 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
2653 static void sinterstoreCommand(redisClient
*c
) {
2654 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
2657 static void flushdbCommand(redisClient
*c
) {
2659 addReply(c
,shared
.ok
);
2660 rdbSave(server
.dbfilename
);
2663 static void flushallCommand(redisClient
*c
) {
2665 addReply(c
,shared
.ok
);
2666 rdbSave(server
.dbfilename
);
2669 redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
2670 redisSortOperation
*so
= zmalloc(sizeof(*so
));
2671 if (!so
) oom("createSortOperation");
2673 so
->pattern
= pattern
;
2677 /* Return the value associated to the key with a name obtained
2678 * substituting the first occurence of '*' in 'pattern' with 'subst' */
2679 robj
*lookupKeyByPattern(dict
*dict
, robj
*pattern
, robj
*subst
) {
2683 int prefixlen
, sublen
, postfixlen
;
2685 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
2689 char buf
[REDIS_SORTKEY_MAX
+1];
2693 spat
= pattern
->ptr
;
2695 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
2696 p
= strchr(spat
,'*');
2697 if (!p
) return NULL
;
2700 sublen
= sdslen(ssub
);
2701 postfixlen
= sdslen(spat
)-(prefixlen
+1);
2702 memcpy(keyname
.buf
,spat
,prefixlen
);
2703 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
2704 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
2705 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
2706 keyname
.len
= prefixlen
+sublen
+postfixlen
;
2708 keyobj
.refcount
= 1;
2709 keyobj
.type
= REDIS_STRING
;
2710 keyobj
.ptr
= ((char*)&keyname
)+(sizeof(long)*2);
2712 de
= dictFind(dict
,&keyobj
);
2713 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
2714 if (!de
) return NULL
;
2715 return dictGetEntryVal(de
);
2718 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
2719 * the additional parameter is not standard but a BSD-specific we have to
2720 * pass sorting parameters via the global 'server' structure */
2721 static int sortCompare(const void *s1
, const void *s2
) {
2722 const redisSortObject
*so1
= s1
, *so2
= s2
;
2725 if (!server
.sort_alpha
) {
2726 /* Numeric sorting. Here it's trivial as we precomputed scores */
2727 if (so1
->u
.score
> so2
->u
.score
) {
2729 } else if (so1
->u
.score
< so2
->u
.score
) {
2735 /* Alphanumeric sorting */
2736 if (server
.sort_bypattern
) {
2737 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
2738 /* At least one compare object is NULL */
2739 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
2741 else if (so1
->u
.cmpobj
== NULL
)
2746 /* We have both the objects, use strcoll */
2747 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
2750 /* Compare elements directly */
2751 cmp
= strcoll(so1
->obj
->ptr
,so2
->obj
->ptr
);
2754 return server
.sort_desc
? -cmp
: cmp
;
2757 /* The SORT command is the most complex command in Redis. Warning: this code
2758 * is optimized for speed and a bit less for readability */
2759 static void sortCommand(redisClient
*c
) {
2763 int desc
= 0, alpha
= 0;
2764 int limit_start
= 0, limit_count
= -1, start
, end
;
2765 int j
, dontsort
= 0, vectorlen
;
2766 int getop
= 0; /* GET operation counter */
2767 robj
*sortval
, *sortby
= NULL
;
2768 redisSortObject
*vector
; /* Resulting vector to sort */
2770 /* Lookup the key to sort. It must be of the right types */
2771 de
= dictFind(c
->dict
,c
->argv
[1]);
2773 addReply(c
,shared
.nokeyerr
);
2776 sortval
= dictGetEntryVal(de
);
2777 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
) {
2778 addReply(c
,shared
.wrongtypeerr
);
2782 /* Create a list of operations to perform for every sorted element.
2783 * Operations can be GET/DEL/INCR/DECR */
2784 operations
= listCreate();
2785 listSetFreeMethod(operations
,zfree
);
2788 /* Now we need to protect sortval incrementing its count, in the future
2789 * SORT may have options able to overwrite/delete keys during the sorting
2790 * and the sorted key itself may get destroied */
2791 incrRefCount(sortval
);
2793 /* The SORT command has an SQL-alike syntax, parse it */
2794 while(j
< c
->argc
) {
2795 int leftargs
= c
->argc
-j
-1;
2796 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
2798 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
2800 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
2802 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
2803 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
2804 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
2806 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
2807 sortby
= c
->argv
[j
+1];
2808 /* If the BY pattern does not contain '*', i.e. it is constant,
2809 * we don't need to sort nor to lookup the weight keys. */
2810 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
2812 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
2813 listAddNodeTail(operations
,createSortOperation(
2814 REDIS_SORT_GET
,c
->argv
[j
+1]));
2817 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"del") && leftargs
>= 1) {
2818 listAddNodeTail(operations
,createSortOperation(
2819 REDIS_SORT_DEL
,c
->argv
[j
+1]));
2821 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"incr") && leftargs
>= 1) {
2822 listAddNodeTail(operations
,createSortOperation(
2823 REDIS_SORT_INCR
,c
->argv
[j
+1]));
2825 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
2826 listAddNodeTail(operations
,createSortOperation(
2827 REDIS_SORT_DECR
,c
->argv
[j
+1]));
2830 decrRefCount(sortval
);
2831 listRelease(operations
);
2832 addReply(c
,shared
.syntaxerr
);
2838 /* Load the sorting vector with all the objects to sort */
2839 vectorlen
= (sortval
->type
== REDIS_LIST
) ?
2840 listLength((list
*)sortval
->ptr
) :
2841 dictGetHashTableUsed((dict
*)sortval
->ptr
);
2842 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
2843 if (!vector
) oom("allocating objects vector for SORT");
2845 if (sortval
->type
== REDIS_LIST
) {
2846 list
*list
= sortval
->ptr
;
2847 listNode
*ln
= list
->head
;
2849 robj
*ele
= ln
->value
;
2850 vector
[j
].obj
= ele
;
2851 vector
[j
].u
.score
= 0;
2852 vector
[j
].u
.cmpobj
= NULL
;
2857 dict
*set
= sortval
->ptr
;
2861 di
= dictGetIterator(set
);
2862 if (!di
) oom("dictGetIterator");
2863 while((setele
= dictNext(di
)) != NULL
) {
2864 vector
[j
].obj
= dictGetEntryKey(setele
);
2865 vector
[j
].u
.score
= 0;
2866 vector
[j
].u
.cmpobj
= NULL
;
2869 dictReleaseIterator(di
);
2871 assert(j
== vectorlen
);
2873 /* Now it's time to load the right scores in the sorting vector */
2874 if (dontsort
== 0) {
2875 for (j
= 0; j
< vectorlen
; j
++) {
2879 byval
= lookupKeyByPattern(c
->dict
,sortby
,vector
[j
].obj
);
2880 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
2882 vector
[j
].u
.cmpobj
= byval
;
2883 incrRefCount(byval
);
2885 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
2888 if (!alpha
) vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
2893 /* We are ready to sort the vector... perform a bit of sanity check
2894 * on the LIMIT option too. We'll use a partial version of quicksort. */
2895 start
= (limit_start
< 0) ? 0 : limit_start
;
2896 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
2897 if (start
>= vectorlen
) {
2898 start
= vectorlen
-1;
2901 if (end
>= vectorlen
) end
= vectorlen
-1;
2903 if (dontsort
== 0) {
2904 server
.sort_desc
= desc
;
2905 server
.sort_alpha
= alpha
;
2906 server
.sort_bypattern
= sortby
? 1 : 0;
2907 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
2910 /* Send command output to the output buffer, performing the specified
2911 * GET/DEL/INCR/DECR operations if any. */
2912 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
2913 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
2914 for (j
= start
; j
<= end
; j
++) {
2915 listNode
*ln
= operations
->head
;
2917 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
2918 sdslen(vector
[j
].obj
->ptr
)));
2919 addReply(c
,vector
[j
].obj
);
2920 addReply(c
,shared
.crlf
);
2923 redisSortOperation
*sop
= ln
->value
;
2924 robj
*val
= lookupKeyByPattern(c
->dict
,sop
->pattern
,
2927 if (sop
->type
== REDIS_SORT_GET
) {
2928 if (!val
|| val
->type
!= REDIS_STRING
) {
2929 addReply(c
,shared
.nullbulk
);
2931 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
2934 addReply(c
,shared
.crlf
);
2936 } else if (sop
->type
== REDIS_SORT_DEL
) {
2944 decrRefCount(sortval
);
2945 listRelease(operations
);
2946 for (j
= 0; j
< vectorlen
; j
++) {
2947 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
2948 decrRefCount(vector
[j
].u
.cmpobj
);
2953 static void infoCommand(redisClient
*c
) {
2955 time_t uptime
= time(NULL
)-server
.stat_starttime
;
2957 info
= sdscatprintf(sdsempty(),
2958 "redis_version:%s\r\n"
2959 "connected_clients:%d\r\n"
2960 "connected_slaves:%d\r\n"
2961 "used_memory:%d\r\n"
2962 "changes_since_last_save:%lld\r\n"
2963 "last_save_time:%d\r\n"
2964 "total_connections_received:%lld\r\n"
2965 "total_commands_processed:%lld\r\n"
2966 "uptime_in_seconds:%d\r\n"
2967 "uptime_in_days:%d\r\n"
2969 listLength(server
.clients
)-listLength(server
.slaves
),
2970 listLength(server
.slaves
),
2974 server
.stat_numconnections
,
2975 server
.stat_numcommands
,
2979 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(info
)));
2980 addReplySds(c
,info
);
2981 addReply(c
,shared
.crlf
);
2984 /* =============================== Replication ============================= */
2986 /* Send the whole output buffer syncronously to the slave. This a general operation in theory, but it is actually useful only for replication. */
2987 static int flushClientOutput(redisClient
*c
) {
2989 time_t start
= time(NULL
);
2991 while(listLength(c
->reply
)) {
2992 if (time(NULL
)-start
> 5) return REDIS_ERR
; /* 5 seconds timeout */
2993 retval
= aeWait(c
->fd
,AE_WRITABLE
,1000);
2996 } else if (retval
& AE_WRITABLE
) {
2997 sendReplyToClient(NULL
, c
->fd
, c
, AE_WRITABLE
);
3003 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
3004 ssize_t nwritten
, ret
= size
;
3005 time_t start
= time(NULL
);
3009 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
3010 nwritten
= write(fd
,ptr
,size
);
3011 if (nwritten
== -1) return -1;
3015 if ((time(NULL
)-start
) > timeout
) {
3023 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
3024 ssize_t nread
, totread
= 0;
3025 time_t start
= time(NULL
);
3029 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
3030 nread
= read(fd
,ptr
,size
);
3031 if (nread
== -1) return -1;
3036 if ((time(NULL
)-start
) > timeout
) {
3044 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
3051 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
3054 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
3065 static void syncCommand(redisClient
*c
) {
3068 time_t start
= time(NULL
);
3071 /* ignore SYNC if aleady slave or in monitor mode */
3072 if (c
->flags
& REDIS_SLAVE
) return;
3074 redisLog(REDIS_NOTICE
,"Slave ask for syncronization");
3075 if (flushClientOutput(c
) == REDIS_ERR
||
3076 rdbSave(server
.dbfilename
) != REDIS_OK
)
3079 fd
= open(server
.dbfilename
, O_RDONLY
);
3080 if (fd
== -1 || fstat(fd
,&sb
) == -1) goto closeconn
;
3083 snprintf(sizebuf
,32,"$%d\r\n",len
);
3084 if (syncWrite(c
->fd
,sizebuf
,strlen(sizebuf
),5) == -1) goto closeconn
;
3089 if (time(NULL
)-start
> REDIS_MAX_SYNC_TIME
) goto closeconn
;
3090 nread
= read(fd
,buf
,1024);
3091 if (nread
== -1) goto closeconn
;
3093 if (syncWrite(c
->fd
,buf
,nread
,5) == -1) goto closeconn
;
3095 if (syncWrite(c
->fd
,"\r\n",2,5) == -1) goto closeconn
;
3097 c
->flags
|= REDIS_SLAVE
;
3099 if (!listAddNodeTail(server
.slaves
,c
)) oom("listAddNodeTail");
3100 redisLog(REDIS_NOTICE
,"Syncronization with slave succeeded");
3104 if (fd
!= -1) close(fd
);
3105 c
->flags
|= REDIS_CLOSE
;
3106 redisLog(REDIS_WARNING
,"Syncronization with slave failed");
3110 static int syncWithMaster(void) {
3111 char buf
[1024], tmpfile
[256];
3113 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
3117 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
3121 /* Issue the SYNC command */
3122 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
3124 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
3128 /* Read the bulk write count */
3129 if (syncReadLine(fd
,buf
,1024,5) == -1) {
3131 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
3135 dumpsize
= atoi(buf
+1);
3136 redisLog(REDIS_NOTICE
,"Receiving %d bytes data dump from MASTER",dumpsize
);
3137 /* Read the bulk write data on a temp file */
3138 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
3139 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644);
3142 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
3146 int nread
, nwritten
;
3148 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
3150 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
3156 nwritten
= write(dfd
,buf
,nread
);
3157 if (nwritten
== -1) {
3158 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
3166 if (rename(tmpfile
,server
.dbfilename
) == -1) {
3167 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
3173 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
3174 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
3178 server
.master
= createClient(fd
);
3179 server
.master
->flags
|= REDIS_MASTER
;
3180 server
.replstate
= REDIS_REPL_CONNECTED
;
3184 static void monitorCommand(redisClient
*c
) {
3185 /* ignore MONITOR if aleady slave or in monitor mode */
3186 if (c
->flags
& REDIS_SLAVE
) return;
3188 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
3190 if (!listAddNodeTail(server
.monitors
,c
)) oom("listAddNodeTail");
3191 addReply(c
,shared
.ok
);
3194 /* =================================== Main! ================================ */
3196 static void daemonize(void) {
3200 if (fork() != 0) exit(0); /* parent exits */
3201 setsid(); /* create a new session */
3203 /* Every output goes to /dev/null. If Redis is daemonized but
3204 * the 'logfile' is set to 'stdout' in the configuration file
3205 * it will not log at all. */
3206 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
3207 dup2(fd
, STDIN_FILENO
);
3208 dup2(fd
, STDOUT_FILENO
);
3209 dup2(fd
, STDERR_FILENO
);
3210 if (fd
> STDERR_FILENO
) close(fd
);
3212 /* Try to write the pid file */
3213 fp
= fopen(server
.pidfile
,"w");
3215 fprintf(fp
,"%d\n",getpid());
3220 int main(int argc
, char **argv
) {
3223 ResetServerSaveParams();
3224 loadServerConfig(argv
[1]);
3225 } else if (argc
> 2) {
3226 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
3230 if (server
.daemonize
) daemonize();
3231 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
3232 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
3233 redisLog(REDIS_NOTICE
,"DB loaded from disk");
3234 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
3235 acceptHandler
, NULL
, NULL
) == AE_ERR
) oom("creating file event");
3236 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
3238 aeDeleteEventLoop(server
.el
);