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 reserved for future uses
100 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
101 * values, will fit inside. */
102 #define REDIS_RDB_6BITLEN 0
103 #define REDIS_RDB_14BITLEN 1
104 #define REDIS_RDB_32BITLEN 2
105 #define REDIS_RDB_64BITLEN 3
106 #define REDIS_RDB_LENERR UINT_MAX
109 #define REDIS_CLOSE 1 /* This client connection should be closed ASAP */
110 #define REDIS_SLAVE 2 /* This client is a slave server */
111 #define REDIS_MASTER 4 /* This client is a master server */
112 #define REDIS_MONITOR 8 /* This client is a slave monitor, see MONITOR */
114 /* Server replication state */
115 #define REDIS_REPL_NONE 0 /* No active replication */
116 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
117 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
119 /* List related stuff */
123 /* Sort operations */
124 #define REDIS_SORT_GET 0
125 #define REDIS_SORT_DEL 1
126 #define REDIS_SORT_INCR 2
127 #define REDIS_SORT_DECR 3
128 #define REDIS_SORT_ASC 4
129 #define REDIS_SORT_DESC 5
130 #define REDIS_SORTKEY_MAX 1024
133 #define REDIS_DEBUG 0
134 #define REDIS_NOTICE 1
135 #define REDIS_WARNING 2
137 /* Anti-warning macro... */
138 #define REDIS_NOTUSED(V) ((void) V)
140 /*================================= Data types ============================== */
142 /* A redis object, that is a type able to hold a string / list / set */
143 typedef struct redisObject
{
149 /* With multiplexing we need to take per-clinet state.
150 * Clients are taken in a liked list. */
151 typedef struct redisClient
{
156 robj
*argv
[REDIS_MAX_ARGS
];
158 int bulklen
; /* bulk read len. -1 if not in bulk read mode */
161 time_t lastinteraction
; /* time of the last interaction, used for timeout */
162 int flags
; /* REDIS_CLOSE | REDIS_SLAVE | REDIS_MONITOR */
163 int slaveseldb
; /* slave selected db, if this client is a slave */
171 /* Global server state structure */
177 unsigned int sharingpoolsize
;
178 long long dirty
; /* changes to DB from the last save */
180 list
*slaves
, *monitors
;
181 char neterr
[ANET_ERR_LEN
];
183 int cronloops
; /* number of times the cron function run */
184 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
185 time_t lastsave
; /* Unix time of last save succeeede */
186 int usedmemory
; /* Used memory in megabytes */
187 /* Fields used only for stats */
188 time_t stat_starttime
; /* server start time */
189 long long stat_numcommands
; /* number of processed commands */
190 long long stat_numconnections
; /* number of connections received */
198 int bgsaveinprogress
;
199 struct saveparam
*saveparams
;
205 /* Replication related */
211 /* Sort parameters - qsort_r() is only available under BSD so we
212 * have to take this state global, in order to pass it to sortCompare() */
218 typedef void redisCommandProc(redisClient
*c
);
219 struct redisCommand
{
221 redisCommandProc
*proc
;
226 typedef struct _redisSortObject
{
234 typedef struct _redisSortOperation
{
237 } redisSortOperation
;
239 struct sharedObjectsStruct
{
240 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
241 *colon
, *nullbulk
, *nullmultibulk
,
242 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
243 *outofrangeerr
, *plus
,
244 *select0
, *select1
, *select2
, *select3
, *select4
,
245 *select5
, *select6
, *select7
, *select8
, *select9
;
248 /*================================ Prototypes =============================== */
250 static void freeStringObject(robj
*o
);
251 static void freeListObject(robj
*o
);
252 static void freeSetObject(robj
*o
);
253 static void decrRefCount(void *o
);
254 static robj
*createObject(int type
, void *ptr
);
255 static void freeClient(redisClient
*c
);
256 static int rdbLoad(char *filename
);
257 static void addReply(redisClient
*c
, robj
*obj
);
258 static void addReplySds(redisClient
*c
, sds s
);
259 static void incrRefCount(robj
*o
);
260 static int rdbSaveBackground(char *filename
);
261 static robj
*createStringObject(char *ptr
, size_t len
);
262 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
263 static int syncWithMaster(void);
264 static robj
*tryObjectSharing(robj
*o
);
266 static void pingCommand(redisClient
*c
);
267 static void echoCommand(redisClient
*c
);
268 static void setCommand(redisClient
*c
);
269 static void setnxCommand(redisClient
*c
);
270 static void getCommand(redisClient
*c
);
271 static void delCommand(redisClient
*c
);
272 static void existsCommand(redisClient
*c
);
273 static void incrCommand(redisClient
*c
);
274 static void decrCommand(redisClient
*c
);
275 static void incrbyCommand(redisClient
*c
);
276 static void decrbyCommand(redisClient
*c
);
277 static void selectCommand(redisClient
*c
);
278 static void randomkeyCommand(redisClient
*c
);
279 static void keysCommand(redisClient
*c
);
280 static void dbsizeCommand(redisClient
*c
);
281 static void lastsaveCommand(redisClient
*c
);
282 static void saveCommand(redisClient
*c
);
283 static void bgsaveCommand(redisClient
*c
);
284 static void shutdownCommand(redisClient
*c
);
285 static void moveCommand(redisClient
*c
);
286 static void renameCommand(redisClient
*c
);
287 static void renamenxCommand(redisClient
*c
);
288 static void lpushCommand(redisClient
*c
);
289 static void rpushCommand(redisClient
*c
);
290 static void lpopCommand(redisClient
*c
);
291 static void rpopCommand(redisClient
*c
);
292 static void llenCommand(redisClient
*c
);
293 static void lindexCommand(redisClient
*c
);
294 static void lrangeCommand(redisClient
*c
);
295 static void ltrimCommand(redisClient
*c
);
296 static void typeCommand(redisClient
*c
);
297 static void lsetCommand(redisClient
*c
);
298 static void saddCommand(redisClient
*c
);
299 static void sremCommand(redisClient
*c
);
300 static void sismemberCommand(redisClient
*c
);
301 static void scardCommand(redisClient
*c
);
302 static void sinterCommand(redisClient
*c
);
303 static void sinterstoreCommand(redisClient
*c
);
304 static void syncCommand(redisClient
*c
);
305 static void flushdbCommand(redisClient
*c
);
306 static void flushallCommand(redisClient
*c
);
307 static void sortCommand(redisClient
*c
);
308 static void lremCommand(redisClient
*c
);
309 static void infoCommand(redisClient
*c
);
310 static void mgetCommand(redisClient
*c
);
311 static void monitorCommand(redisClient
*c
);
313 /*================================= Globals ================================= */
316 static struct redisServer server
; /* server global state */
317 static struct redisCommand cmdTable
[] = {
318 {"get",getCommand
,2,REDIS_CMD_INLINE
},
319 {"set",setCommand
,3,REDIS_CMD_BULK
},
320 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
},
321 {"del",delCommand
,2,REDIS_CMD_INLINE
},
322 {"exists",existsCommand
,2,REDIS_CMD_INLINE
},
323 {"incr",incrCommand
,2,REDIS_CMD_INLINE
},
324 {"decr",decrCommand
,2,REDIS_CMD_INLINE
},
325 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
},
326 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
},
327 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
},
328 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
},
329 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
},
330 {"llen",llenCommand
,2,REDIS_CMD_INLINE
},
331 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
},
332 {"lset",lsetCommand
,4,REDIS_CMD_BULK
},
333 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
},
334 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
},
335 {"lrem",lremCommand
,4,REDIS_CMD_BULK
},
336 {"sadd",saddCommand
,3,REDIS_CMD_BULK
},
337 {"srem",sremCommand
,3,REDIS_CMD_BULK
},
338 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
},
339 {"scard",scardCommand
,2,REDIS_CMD_INLINE
},
340 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
},
341 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
},
342 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
},
343 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
},
344 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
},
345 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
},
346 {"select",selectCommand
,2,REDIS_CMD_INLINE
},
347 {"move",moveCommand
,3,REDIS_CMD_INLINE
},
348 {"rename",renameCommand
,3,REDIS_CMD_INLINE
},
349 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
},
350 {"keys",keysCommand
,2,REDIS_CMD_INLINE
},
351 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
},
352 {"ping",pingCommand
,1,REDIS_CMD_INLINE
},
353 {"echo",echoCommand
,2,REDIS_CMD_BULK
},
354 {"save",saveCommand
,1,REDIS_CMD_INLINE
},
355 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
},
356 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
},
357 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
},
358 {"type",typeCommand
,2,REDIS_CMD_INLINE
},
359 {"sync",syncCommand
,1,REDIS_CMD_INLINE
},
360 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
},
361 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
},
362 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
},
363 {"info",infoCommand
,1,REDIS_CMD_INLINE
},
364 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
},
368 /*============================ Utility functions ============================ */
370 /* Glob-style pattern matching. */
371 int stringmatchlen(const char *pattern
, int patternLen
,
372 const char *string
, int stringLen
, int nocase
)
377 while (pattern
[1] == '*') {
382 return 1; /* match */
384 if (stringmatchlen(pattern
+1, patternLen
-1,
385 string
, stringLen
, nocase
))
386 return 1; /* match */
390 return 0; /* no match */
394 return 0; /* no match */
404 not = pattern
[0] == '^';
411 if (pattern
[0] == '\\') {
414 if (pattern
[0] == string
[0])
416 } else if (pattern
[0] == ']') {
418 } else if (patternLen
== 0) {
422 } else if (pattern
[1] == '-' && patternLen
>= 3) {
423 int start
= pattern
[0];
424 int end
= pattern
[2];
432 start
= tolower(start
);
438 if (c
>= start
&& c
<= end
)
442 if (pattern
[0] == string
[0])
445 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
455 return 0; /* no match */
461 if (patternLen
>= 2) {
468 if (pattern
[0] != string
[0])
469 return 0; /* no match */
471 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
472 return 0; /* no match */
480 if (stringLen
== 0) {
481 while(*pattern
== '*') {
488 if (patternLen
== 0 && stringLen
== 0)
493 void redisLog(int level
, const char *fmt
, ...)
498 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
502 if (level
>= server
.verbosity
) {
504 fprintf(fp
,"%c ",c
[level
]);
505 vfprintf(fp
, fmt
, ap
);
511 if (server
.logfile
) fclose(fp
);
514 /*====================== Hash table type implementation ==================== */
516 /* This is an hash table type that uses the SDS dynamic strings libary as
517 * keys and radis objects as values (objects can hold SDS strings,
520 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
524 DICT_NOTUSED(privdata
);
526 l1
= sdslen((sds
)key1
);
527 l2
= sdslen((sds
)key2
);
528 if (l1
!= l2
) return 0;
529 return memcmp(key1
, key2
, l1
) == 0;
532 static void dictRedisObjectDestructor(void *privdata
, void *val
)
534 DICT_NOTUSED(privdata
);
539 static int dictSdsKeyCompare(void *privdata
, const void *key1
,
542 const robj
*o1
= key1
, *o2
= key2
;
543 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
546 static unsigned int dictSdsHash(const void *key
) {
548 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
551 static dictType setDictType
= {
552 dictSdsHash
, /* hash function */
555 dictSdsKeyCompare
, /* key compare */
556 dictRedisObjectDestructor
, /* key destructor */
557 NULL
/* val destructor */
560 static dictType hashDictType
= {
561 dictSdsHash
, /* hash function */
564 dictSdsKeyCompare
, /* key compare */
565 dictRedisObjectDestructor
, /* key destructor */
566 dictRedisObjectDestructor
/* val destructor */
569 /* ========================= Random utility functions ======================= */
571 /* Redis generally does not try to recover from out of memory conditions
572 * when allocating objects or strings, it is not clear if it will be possible
573 * to report this condition to the client since the networking layer itself
574 * is based on heap allocation for send buffers, so we simply abort.
575 * At least the code will be simpler to read... */
576 static void oom(const char *msg
) {
577 fprintf(stderr
, "%s: Out of memory\n",msg
);
583 /* ====================== Redis server networking stuff ===================== */
584 void closeTimedoutClients(void) {
588 time_t now
= time(NULL
);
590 li
= listGetIterator(server
.clients
,AL_START_HEAD
);
592 while ((ln
= listNextElement(li
)) != NULL
) {
593 c
= listNodeValue(ln
);
594 if (!(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
595 (now
- c
->lastinteraction
> server
.maxidletime
)) {
596 redisLog(REDIS_DEBUG
,"Closing idle client");
600 listReleaseIterator(li
);
603 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
604 int j
, size
, used
, loops
= server
.cronloops
++;
605 REDIS_NOTUSED(eventLoop
);
607 REDIS_NOTUSED(clientData
);
609 /* Update the global state with the amount of used memory */
610 server
.usedmemory
= zmalloc_used_memory();
612 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
613 * we resize the hash table to save memory */
614 for (j
= 0; j
< server
.dbnum
; j
++) {
615 size
= dictGetHashTableSize(server
.dict
[j
]);
616 used
= dictGetHashTableUsed(server
.dict
[j
]);
617 if (!(loops
% 5) && used
> 0) {
618 redisLog(REDIS_DEBUG
,"DB %d: %d keys in %d slots HT.",j
,used
,size
);
619 // dictPrintStats(server.dict);
621 if (size
&& used
&& size
> REDIS_HT_MINSLOTS
&&
622 (used
*100/size
< REDIS_HT_MINFILL
)) {
623 redisLog(REDIS_NOTICE
,"The hash table %d is too sparse, resize it...",j
);
624 dictResize(server
.dict
[j
]);
625 redisLog(REDIS_NOTICE
,"Hash table %d resized.",j
);
629 /* Show information about connected clients */
631 redisLog(REDIS_DEBUG
,"%d clients connected (%d slaves), %d bytes in use",
632 listLength(server
.clients
)-listLength(server
.slaves
),
633 listLength(server
.slaves
),
635 dictGetHashTableUsed(server
.sharingpool
));
638 /* Close connections of timedout clients */
640 closeTimedoutClients();
642 /* Check if a background saving in progress terminated */
643 if (server
.bgsaveinprogress
) {
645 if (wait4(-1,&statloc
,WNOHANG
,NULL
)) {
646 int exitcode
= WEXITSTATUS(statloc
);
648 redisLog(REDIS_NOTICE
,
649 "Background saving terminated with success");
651 server
.lastsave
= time(NULL
);
653 redisLog(REDIS_WARNING
,
654 "Background saving error");
656 server
.bgsaveinprogress
= 0;
659 /* If there is not a background saving in progress check if
660 * we have to save now */
661 time_t now
= time(NULL
);
662 for (j
= 0; j
< server
.saveparamslen
; j
++) {
663 struct saveparam
*sp
= server
.saveparams
+j
;
665 if (server
.dirty
>= sp
->changes
&&
666 now
-server
.lastsave
> sp
->seconds
) {
667 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
668 sp
->changes
, sp
->seconds
);
669 rdbSaveBackground(server
.dbfilename
);
674 /* Check if we should connect to a MASTER */
675 if (server
.replstate
== REDIS_REPL_CONNECT
) {
676 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
677 if (syncWithMaster() == REDIS_OK
) {
678 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
684 static void createSharedObjects(void) {
685 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
686 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
687 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
688 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
689 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
690 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
691 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
692 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
693 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
695 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
696 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
697 "-ERR Operation against a key holding the wrong kind of value\r\n"));
698 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
699 "-ERR no such key\r\n"));
700 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
701 "-ERR syntax error\r\n"));
702 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
703 "-ERR source and destination objects are the same\r\n"));
704 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
705 "-ERR index out of range\r\n"));
706 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
707 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
708 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
709 shared
.select0
= createStringObject("select 0\r\n",10);
710 shared
.select1
= createStringObject("select 1\r\n",10);
711 shared
.select2
= createStringObject("select 2\r\n",10);
712 shared
.select3
= createStringObject("select 3\r\n",10);
713 shared
.select4
= createStringObject("select 4\r\n",10);
714 shared
.select5
= createStringObject("select 5\r\n",10);
715 shared
.select6
= createStringObject("select 6\r\n",10);
716 shared
.select7
= createStringObject("select 7\r\n",10);
717 shared
.select8
= createStringObject("select 8\r\n",10);
718 shared
.select9
= createStringObject("select 9\r\n",10);
721 static void appendServerSaveParams(time_t seconds
, int changes
) {
722 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
723 if (server
.saveparams
== NULL
) oom("appendServerSaveParams");
724 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
725 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
726 server
.saveparamslen
++;
729 static void ResetServerSaveParams() {
730 zfree(server
.saveparams
);
731 server
.saveparams
= NULL
;
732 server
.saveparamslen
= 0;
735 static void initServerConfig() {
736 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
737 server
.port
= REDIS_SERVERPORT
;
738 server
.verbosity
= REDIS_DEBUG
;
739 server
.maxidletime
= REDIS_MAXIDLETIME
;
740 server
.saveparams
= NULL
;
741 server
.logfile
= NULL
; /* NULL = log on standard output */
742 server
.bindaddr
= NULL
;
743 server
.glueoutputbuf
= 1;
744 server
.daemonize
= 0;
745 server
.pidfile
= "/var/run/redis.pid";
746 server
.dbfilename
= "dump.rdb";
747 server
.shareobjects
= 0;
748 ResetServerSaveParams();
750 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
751 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
752 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
753 /* Replication related */
755 server
.masterhost
= NULL
;
756 server
.masterport
= 6379;
757 server
.master
= NULL
;
758 server
.replstate
= REDIS_REPL_NONE
;
761 static void initServer() {
764 signal(SIGHUP
, SIG_IGN
);
765 signal(SIGPIPE
, SIG_IGN
);
767 server
.clients
= listCreate();
768 server
.slaves
= listCreate();
769 server
.monitors
= listCreate();
770 server
.objfreelist
= listCreate();
771 createSharedObjects();
772 server
.el
= aeCreateEventLoop();
773 server
.dict
= zmalloc(sizeof(dict
*)*server
.dbnum
);
774 server
.sharingpool
= dictCreate(&setDictType
,NULL
);
775 server
.sharingpoolsize
= 1024;
776 if (!server
.dict
|| !server
.clients
|| !server
.slaves
|| !server
.monitors
|| !server
.el
|| !server
.objfreelist
)
777 oom("server initialization"); /* Fatal OOM */
778 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
779 if (server
.fd
== -1) {
780 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
783 for (j
= 0; j
< server
.dbnum
; j
++)
784 server
.dict
[j
] = dictCreate(&hashDictType
,NULL
);
785 server
.cronloops
= 0;
786 server
.bgsaveinprogress
= 0;
787 server
.lastsave
= time(NULL
);
789 server
.usedmemory
= 0;
790 server
.stat_numcommands
= 0;
791 server
.stat_numconnections
= 0;
792 server
.stat_starttime
= time(NULL
);
793 aeCreateTimeEvent(server
.el
, 1000, serverCron
, NULL
, NULL
);
796 /* Empty the whole database */
797 static void emptyDb() {
800 for (j
= 0; j
< server
.dbnum
; j
++)
801 dictEmpty(server
.dict
[j
]);
804 /* I agree, this is a very rudimental way to load a configuration...
805 will improve later if the config gets more complex */
806 static void loadServerConfig(char *filename
) {
807 FILE *fp
= fopen(filename
,"r");
808 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
813 redisLog(REDIS_WARNING
,"Fatal error, can't open config file");
816 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
822 line
= sdstrim(line
," \t\r\n");
824 /* Skip comments and blank lines*/
825 if (line
[0] == '#' || line
[0] == '\0') {
830 /* Split into arguments */
831 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
834 /* Execute config directives */
835 if (!strcmp(argv
[0],"timeout") && argc
== 2) {
836 server
.maxidletime
= atoi(argv
[1]);
837 if (server
.maxidletime
< 1) {
838 err
= "Invalid timeout value"; goto loaderr
;
840 } else if (!strcmp(argv
[0],"port") && argc
== 2) {
841 server
.port
= atoi(argv
[1]);
842 if (server
.port
< 1 || server
.port
> 65535) {
843 err
= "Invalid port"; goto loaderr
;
845 } else if (!strcmp(argv
[0],"bind") && argc
== 2) {
846 server
.bindaddr
= zstrdup(argv
[1]);
847 } else if (!strcmp(argv
[0],"save") && argc
== 3) {
848 int seconds
= atoi(argv
[1]);
849 int changes
= atoi(argv
[2]);
850 if (seconds
< 1 || changes
< 0) {
851 err
= "Invalid save parameters"; goto loaderr
;
853 appendServerSaveParams(seconds
,changes
);
854 } else if (!strcmp(argv
[0],"dir") && argc
== 2) {
855 if (chdir(argv
[1]) == -1) {
856 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
857 argv
[1], strerror(errno
));
860 } else if (!strcmp(argv
[0],"loglevel") && argc
== 2) {
861 if (!strcmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
862 else if (!strcmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
863 else if (!strcmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
865 err
= "Invalid log level. Must be one of debug, notice, warning";
868 } else if (!strcmp(argv
[0],"logfile") && argc
== 2) {
871 server
.logfile
= zstrdup(argv
[1]);
872 if (!strcmp(server
.logfile
,"stdout")) {
873 zfree(server
.logfile
);
874 server
.logfile
= NULL
;
876 if (server
.logfile
) {
877 /* Test if we are able to open the file. The server will not
878 * be able to abort just for this problem later... */
879 fp
= fopen(server
.logfile
,"a");
881 err
= sdscatprintf(sdsempty(),
882 "Can't open the log file: %s", strerror(errno
));
887 } else if (!strcmp(argv
[0],"databases") && argc
== 2) {
888 server
.dbnum
= atoi(argv
[1]);
889 if (server
.dbnum
< 1) {
890 err
= "Invalid number of databases"; goto loaderr
;
892 } else if (!strcmp(argv
[0],"slaveof") && argc
== 3) {
893 server
.masterhost
= sdsnew(argv
[1]);
894 server
.masterport
= atoi(argv
[2]);
895 server
.replstate
= REDIS_REPL_CONNECT
;
896 } else if (!strcmp(argv
[0],"glueoutputbuf") && argc
== 2) {
898 if (!strcmp(argv
[1],"yes")) server
.glueoutputbuf
= 1;
899 else if (!strcmp(argv
[1],"no")) server
.glueoutputbuf
= 0;
901 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
903 } else if (!strcmp(argv
[0],"shareobjects") && argc
== 2) {
905 if (!strcmp(argv
[1],"yes")) server
.shareobjects
= 1;
906 else if (!strcmp(argv
[1],"no")) server
.shareobjects
= 0;
908 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
910 } else if (!strcmp(argv
[0],"daemonize") && argc
== 2) {
912 if (!strcmp(argv
[1],"yes")) server
.daemonize
= 1;
913 else if (!strcmp(argv
[1],"no")) server
.daemonize
= 0;
915 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
917 } else if (!strcmp(argv
[0],"pidfile") && argc
== 2) {
918 server
.pidfile
= zstrdup(argv
[1]);
920 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
922 for (j
= 0; j
< argc
; j
++)
931 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
932 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
933 fprintf(stderr
, ">>> '%s'\n", line
);
934 fprintf(stderr
, "%s\n", err
);
938 static void freeClientArgv(redisClient
*c
) {
941 for (j
= 0; j
< c
->argc
; j
++)
942 decrRefCount(c
->argv
[j
]);
946 static void freeClient(redisClient
*c
) {
949 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
950 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
951 sdsfree(c
->querybuf
);
952 listRelease(c
->reply
);
955 ln
= listSearchKey(server
.clients
,c
);
957 listDelNode(server
.clients
,ln
);
958 if (c
->flags
& REDIS_SLAVE
) {
959 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
960 ln
= listSearchKey(l
,c
);
964 if (c
->flags
& REDIS_MASTER
) {
965 server
.master
= NULL
;
966 server
.replstate
= REDIS_REPL_CONNECT
;
971 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
973 listNode
*ln
= c
->reply
->head
, *next
;
978 totlen
+= sdslen(o
->ptr
);
980 /* This optimization makes more sense if we don't have to copy
982 if (totlen
> 1024) return;
992 memcpy(buf
+copylen
,o
->ptr
,sdslen(o
->ptr
));
993 copylen
+= sdslen(o
->ptr
);
994 listDelNode(c
->reply
,ln
);
997 /* Now the output buffer is empty, add the new single element */
998 addReplySds(c
,sdsnewlen(buf
,totlen
));
1002 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1003 redisClient
*c
= privdata
;
1004 int nwritten
= 0, totwritten
= 0, objlen
;
1007 REDIS_NOTUSED(mask
);
1009 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
1010 glueReplyBuffersIfNeeded(c
);
1011 while(listLength(c
->reply
)) {
1012 o
= listNodeValue(listFirst(c
->reply
));
1013 objlen
= sdslen(o
->ptr
);
1016 listDelNode(c
->reply
,listFirst(c
->reply
));
1020 if (c
->flags
& REDIS_MASTER
) {
1021 nwritten
= objlen
- c
->sentlen
;
1023 nwritten
= write(fd
, o
->ptr
+c
->sentlen
, objlen
- c
->sentlen
);
1024 if (nwritten
<= 0) break;
1026 c
->sentlen
+= nwritten
;
1027 totwritten
+= nwritten
;
1028 /* If we fully sent the object on head go to the next one */
1029 if (c
->sentlen
== objlen
) {
1030 listDelNode(c
->reply
,listFirst(c
->reply
));
1034 if (nwritten
== -1) {
1035 if (errno
== EAGAIN
) {
1038 redisLog(REDIS_DEBUG
,
1039 "Error writing to client: %s", strerror(errno
));
1044 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
1045 if (listLength(c
->reply
) == 0) {
1047 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1051 static struct redisCommand
*lookupCommand(char *name
) {
1053 while(cmdTable
[j
].name
!= NULL
) {
1054 if (!strcmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
1060 /* resetClient prepare the client to process the next command */
1061 static void resetClient(redisClient
*c
) {
1066 /* If this function gets called we already read a whole
1067 * command, argments are in the client argv/argc fields.
1068 * processCommand() execute the command or prepare the
1069 * server for a bulk read from the client.
1071 * If 1 is returned the client is still alive and valid and
1072 * and other operations can be performed by the caller. Otherwise
1073 * if 0 is returned the client was destroied (i.e. after QUIT). */
1074 static int processCommand(redisClient
*c
) {
1075 struct redisCommand
*cmd
;
1078 sdstolower(c
->argv
[0]->ptr
);
1079 /* The QUIT command is handled as a special case. Normal command
1080 * procs are unable to close the client connection safely */
1081 if (!strcmp(c
->argv
[0]->ptr
,"quit")) {
1085 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1087 addReplySds(c
,sdsnew("-ERR unknown command\r\n"));
1090 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
1091 (c
->argc
< -cmd
->arity
)) {
1092 addReplySds(c
,sdsnew("-ERR wrong number of arguments\r\n"));
1095 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
1096 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
1098 decrRefCount(c
->argv
[c
->argc
-1]);
1099 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1101 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1106 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1107 /* It is possible that the bulk read is already in the
1108 * buffer. Check this condition and handle it accordingly */
1109 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
1110 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
1112 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
1117 /* Let's try to share objects on the command arguments vector */
1118 if (server
.shareobjects
) {
1120 for(j
= 1; j
< c
->argc
; j
++)
1121 c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]);
1123 /* Exec the command */
1124 dirty
= server
.dirty
;
1126 if (server
.dirty
-dirty
!= 0 && listLength(server
.slaves
))
1127 replicationFeedSlaves(server
.slaves
,cmd
,c
->dictid
,c
->argv
,c
->argc
);
1128 if (listLength(server
.monitors
))
1129 replicationFeedSlaves(server
.monitors
,cmd
,c
->dictid
,c
->argv
,c
->argc
);
1130 server
.stat_numcommands
++;
1132 /* Prepare the client for the next command */
1133 if (c
->flags
& REDIS_CLOSE
) {
1141 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
1142 listNode
*ln
= slaves
->head
;
1143 robj
*outv
[REDIS_MAX_ARGS
*4]; /* enough room for args, spaces, newlines */
1146 for (j
= 0; j
< argc
; j
++) {
1147 if (j
!= 0) outv
[outc
++] = shared
.space
;
1148 if ((cmd
->flags
& REDIS_CMD_BULK
) && j
== argc
-1) {
1151 lenobj
= createObject(REDIS_STRING
,
1152 sdscatprintf(sdsempty(),"%d\r\n",sdslen(argv
[j
]->ptr
)));
1153 lenobj
->refcount
= 0;
1154 outv
[outc
++] = lenobj
;
1156 outv
[outc
++] = argv
[j
];
1158 outv
[outc
++] = shared
.crlf
;
1161 redisClient
*slave
= ln
->value
;
1162 if (slave
->slaveseldb
!= dictid
) {
1166 case 0: selectcmd
= shared
.select0
; break;
1167 case 1: selectcmd
= shared
.select1
; break;
1168 case 2: selectcmd
= shared
.select2
; break;
1169 case 3: selectcmd
= shared
.select3
; break;
1170 case 4: selectcmd
= shared
.select4
; break;
1171 case 5: selectcmd
= shared
.select5
; break;
1172 case 6: selectcmd
= shared
.select6
; break;
1173 case 7: selectcmd
= shared
.select7
; break;
1174 case 8: selectcmd
= shared
.select8
; break;
1175 case 9: selectcmd
= shared
.select9
; break;
1177 selectcmd
= createObject(REDIS_STRING
,
1178 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
1179 selectcmd
->refcount
= 0;
1182 addReply(slave
,selectcmd
);
1183 slave
->slaveseldb
= dictid
;
1185 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
1190 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1191 redisClient
*c
= (redisClient
*) privdata
;
1192 char buf
[REDIS_QUERYBUF_LEN
];
1195 REDIS_NOTUSED(mask
);
1197 nread
= read(fd
, buf
, REDIS_QUERYBUF_LEN
);
1199 if (errno
== EAGAIN
) {
1202 redisLog(REDIS_DEBUG
, "Reading from client: %s",strerror(errno
));
1206 } else if (nread
== 0) {
1207 redisLog(REDIS_DEBUG
, "Client closed connection");
1212 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
1213 c
->lastinteraction
= time(NULL
);
1219 if (c
->bulklen
== -1) {
1220 /* Read the first line of the query */
1221 char *p
= strchr(c
->querybuf
,'\n');
1227 query
= c
->querybuf
;
1228 c
->querybuf
= sdsempty();
1229 querylen
= 1+(p
-(query
));
1230 if (sdslen(query
) > querylen
) {
1231 /* leave data after the first line of the query in the buffer */
1232 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
1234 *p
= '\0'; /* remove "\n" */
1235 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
1236 sdsupdatelen(query
);
1238 /* Now we can split the query in arguments */
1239 if (sdslen(query
) == 0) {
1240 /* Ignore empty query */
1244 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
1246 if (argv
== NULL
) oom("sdssplitlen");
1247 for (j
= 0; j
< argc
&& j
< REDIS_MAX_ARGS
; j
++) {
1248 if (sdslen(argv
[j
])) {
1249 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
1256 /* Execute the command. If the client is still valid
1257 * after processCommand() return and there is something
1258 * on the query buffer try to process the next command. */
1259 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
1261 } else if (sdslen(c
->querybuf
) >= 1024) {
1262 redisLog(REDIS_DEBUG
, "Client protocol error");
1267 /* Bulk read handling. Note that if we are at this point
1268 the client already sent a command terminated with a newline,
1269 we are reading the bulk data that is actually the last
1270 argument of the command. */
1271 int qbl
= sdslen(c
->querybuf
);
1273 if (c
->bulklen
<= qbl
) {
1274 /* Copy everything but the final CRLF as final argument */
1275 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
1277 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
1284 static int selectDb(redisClient
*c
, int id
) {
1285 if (id
< 0 || id
>= server
.dbnum
)
1287 c
->dict
= server
.dict
[id
];
1292 static redisClient
*createClient(int fd
) {
1293 redisClient
*c
= zmalloc(sizeof(*c
));
1295 anetNonBlock(NULL
,fd
);
1296 anetTcpNoDelay(NULL
,fd
);
1297 if (!c
) return NULL
;
1300 c
->querybuf
= sdsempty();
1305 c
->lastinteraction
= time(NULL
);
1306 if ((c
->reply
= listCreate()) == NULL
) oom("listCreate");
1307 listSetFreeMethod(c
->reply
,decrRefCount
);
1308 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
1309 readQueryFromClient
, c
, NULL
) == AE_ERR
) {
1313 if (!listAddNodeTail(server
.clients
,c
)) oom("listAddNodeTail");
1317 static void addReply(redisClient
*c
, robj
*obj
) {
1318 if (listLength(c
->reply
) == 0 &&
1319 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
1320 sendReplyToClient
, c
, NULL
) == AE_ERR
) return;
1321 if (!listAddNodeTail(c
->reply
,obj
)) oom("listAddNodeTail");
1325 static void addReplySds(redisClient
*c
, sds s
) {
1326 robj
*o
= createObject(REDIS_STRING
,s
);
1331 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1335 REDIS_NOTUSED(mask
);
1336 REDIS_NOTUSED(privdata
);
1338 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
1339 if (cfd
== AE_ERR
) {
1340 redisLog(REDIS_DEBUG
,"Accepting client connection: %s", server
.neterr
);
1343 redisLog(REDIS_DEBUG
,"Accepted %s:%d", cip
, cport
);
1344 if (createClient(cfd
) == NULL
) {
1345 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
1346 close(cfd
); /* May be already closed, just ingore errors */
1349 server
.stat_numconnections
++;
1352 /* ======================= Redis objects implementation ===================== */
1354 static robj
*createObject(int type
, void *ptr
) {
1357 if (listLength(server
.objfreelist
)) {
1358 listNode
*head
= listFirst(server
.objfreelist
);
1359 o
= listNodeValue(head
);
1360 listDelNode(server
.objfreelist
,head
);
1362 o
= zmalloc(sizeof(*o
));
1364 if (!o
) oom("createObject");
1371 static robj
*createStringObject(char *ptr
, size_t len
) {
1372 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
1375 static robj
*createListObject(void) {
1376 list
*l
= listCreate();
1378 if (!l
) oom("listCreate");
1379 listSetFreeMethod(l
,decrRefCount
);
1380 return createObject(REDIS_LIST
,l
);
1383 static robj
*createSetObject(void) {
1384 dict
*d
= dictCreate(&setDictType
,NULL
);
1385 if (!d
) oom("dictCreate");
1386 return createObject(REDIS_SET
,d
);
1390 static robj
*createHashObject(void) {
1391 dict
*d
= dictCreate(&hashDictType
,NULL
);
1392 if (!d
) oom("dictCreate");
1393 return createObject(REDIS_SET
,d
);
1397 static void freeStringObject(robj
*o
) {
1401 static void freeListObject(robj
*o
) {
1402 listRelease((list
*) o
->ptr
);
1405 static void freeSetObject(robj
*o
) {
1406 dictRelease((dict
*) o
->ptr
);
1409 static void freeHashObject(robj
*o
) {
1410 dictRelease((dict
*) o
->ptr
);
1413 static void incrRefCount(robj
*o
) {
1417 static void decrRefCount(void *obj
) {
1419 if (--(o
->refcount
) == 0) {
1421 case REDIS_STRING
: freeStringObject(o
); break;
1422 case REDIS_LIST
: freeListObject(o
); break;
1423 case REDIS_SET
: freeSetObject(o
); break;
1424 case REDIS_HASH
: freeHashObject(o
); break;
1425 default: assert(0 != 0); break;
1427 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
1428 !listAddNodeHead(server
.objfreelist
,o
))
1433 /* Try to share an object against the shared objects pool */
1434 static robj
*tryObjectSharing(robj
*o
) {
1435 struct dictEntry
*de
;
1438 if (server
.shareobjects
== 0) return o
;
1440 assert(o
->type
== REDIS_STRING
);
1441 de
= dictFind(server
.sharingpool
,o
);
1443 robj
*shared
= dictGetEntryKey(de
);
1445 c
= ((unsigned long) dictGetEntryVal(de
))+1;
1446 dictGetEntryVal(de
) = (void*) c
;
1447 incrRefCount(shared
);
1451 /* Here we are using a stream algorihtm: Every time an object is
1452 * shared we increment its count, everytime there is a miss we
1453 * recrement the counter of a random object. If this object reaches
1454 * zero we remove the object and put the current object instead. */
1455 if (dictGetHashTableUsed(server
.sharingpool
) >=
1456 server
.sharingpoolsize
) {
1457 de
= dictGetRandomKey(server
.sharingpool
);
1459 c
= ((unsigned long) dictGetEntryVal(de
))-1;
1460 dictGetEntryVal(de
) = (void*) c
;
1462 dictDelete(server
.sharingpool
,de
->key
);
1465 c
= 0; /* If the pool is empty we want to add this object */
1470 retval
= dictAdd(server
.sharingpool
,o
,(void*)1);
1471 assert(retval
== DICT_OK
);
1478 /*============================ DB saving/loading ============================ */
1480 static int rdbSaveType(FILE *fp
, unsigned char type
) {
1481 if (fwrite(&type
,1,1,fp
) == 0) return -1;
1485 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
1486 unsigned char buf
[2];
1489 /* Save a 6 bit len */
1490 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
1491 if (fwrite(buf
,1,1,fp
) == 0) return -1;
1492 } else if (len
< (1<<14)) {
1493 /* Save a 14 bit len */
1494 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
1496 if (fwrite(buf
,4,1,fp
) == 0) return -1;
1498 /* Save a 32 bit len */
1499 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
1500 if (fwrite(buf
,1,1,fp
) == 0) return -1;
1502 if (fwrite(&len
,4,1,fp
) == 0) return -1;
1507 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
1508 size_t len
= sdslen(obj
->ptr
);
1510 if (rdbSaveLen(fp
,len
) == -1) return -1;
1511 if (len
&& fwrite(obj
->ptr
,len
,1,fp
) == 0) return -1;
1515 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
1516 static int rdbSave(char *filename
) {
1517 dictIterator
*di
= NULL
;
1523 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
1524 fp
= fopen(tmpfile
,"w");
1526 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
1529 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
1530 for (j
= 0; j
< server
.dbnum
; j
++) {
1531 dict
*d
= server
.dict
[j
];
1532 if (dictGetHashTableUsed(d
) == 0) continue;
1533 di
= dictGetIterator(d
);
1539 /* Write the SELECT DB opcode */
1540 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
1541 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
1543 /* Iterate this DB writing every entry */
1544 while((de
= dictNext(di
)) != NULL
) {
1545 robj
*key
= dictGetEntryKey(de
);
1546 robj
*o
= dictGetEntryVal(de
);
1548 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
1549 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
1550 if (o
->type
== REDIS_STRING
) {
1551 /* Save a string value */
1552 if (rdbSaveStringObject(fp
,o
) == -1) goto werr
;
1553 } else if (o
->type
== REDIS_LIST
) {
1554 /* Save a list value */
1555 list
*list
= o
->ptr
;
1556 listNode
*ln
= list
->head
;
1558 if (rdbSaveLen(fp
,listLength(list
)) == -1) goto werr
;
1560 robj
*eleobj
= listNodeValue(ln
);
1562 if (rdbSaveStringObject(fp
,eleobj
) == -1) goto werr
;
1565 } else if (o
->type
== REDIS_SET
) {
1566 /* Save a set value */
1568 dictIterator
*di
= dictGetIterator(set
);
1571 if (!set
) oom("dictGetIteraotr");
1572 if (rdbSaveLen(fp
,dictGetHashTableUsed(set
)) == -1) goto werr
;
1573 while((de
= dictNext(di
)) != NULL
) {
1574 robj
*eleobj
= dictGetEntryKey(de
);
1576 if (rdbSaveStringObject(fp
,eleobj
) == -1) goto werr
;
1578 dictReleaseIterator(di
);
1583 dictReleaseIterator(di
);
1586 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
1588 /* Make sure data will not remain on the OS's output buffers */
1593 /* Use RENAME to make sure the DB file is changed atomically only
1594 * if the generate DB file is ok. */
1595 if (rename(tmpfile
,filename
) == -1) {
1596 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destionation: %s", strerror(errno
));
1600 redisLog(REDIS_NOTICE
,"DB saved on disk");
1602 server
.lastsave
= time(NULL
);
1608 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
1609 if (di
) dictReleaseIterator(di
);
1613 static int rdbSaveBackground(char *filename
) {
1616 if (server
.bgsaveinprogress
) return REDIS_ERR
;
1617 if ((childpid
= fork()) == 0) {
1620 if (rdbSave(filename
) == REDIS_OK
) {
1627 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
1628 server
.bgsaveinprogress
= 1;
1631 return REDIS_OK
; /* unreached */
1634 static int rdbLoadType(FILE *fp
) {
1636 if (fread(&type
,1,1,fp
) == 0) return -1;
1640 static uint32_t rdbLoadLen(FILE *fp
, int rdbver
) {
1641 unsigned char buf
[2];
1645 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
1648 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
1649 if ((buf
[0]&0xC0) == REDIS_RDB_6BITLEN
) {
1650 /* Read a 6 bit len */
1652 } else if ((buf
[0]&0xC0) == REDIS_RDB_14BITLEN
) {
1653 /* Read a 14 bit len */
1654 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
1655 return ((buf
[0]&0x3F)<<8)|buf
[1];
1657 /* Read a 32 bit len */
1658 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
1664 static robj
*rdbLoadStringObject(FILE*fp
,int rdbver
) {
1665 uint32_t len
= rdbLoadLen(fp
,rdbver
);
1668 if (len
== REDIS_RDB_LENERR
) return NULL
;
1669 val
= sdsnewlen(NULL
,len
);
1670 if (len
&& fread(val
,len
,1,fp
) == 0) {
1674 return tryObjectSharing(createObject(REDIS_STRING
,val
));
1677 static int rdbLoad(char *filename
) {
1679 robj
*keyobj
= NULL
;
1683 dict
*d
= server
.dict
[0];
1686 fp
= fopen(filename
,"r");
1687 if (!fp
) return REDIS_ERR
;
1688 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
1690 if (memcmp(buf
,"REDIS",5) != 0) {
1692 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
1695 rdbver
= atoi(buf
+5);
1698 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
1705 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
1706 if (type
== REDIS_EOF
) break;
1707 /* Handle SELECT DB opcode as a special case */
1708 if (type
== REDIS_SELECTDB
) {
1709 if ((dbid
= rdbLoadLen(fp
,rdbver
)) == REDIS_RDB_LENERR
) goto eoferr
;
1710 if (dbid
>= (unsigned)server
.dbnum
) {
1711 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
1714 d
= server
.dict
[dbid
];
1718 if ((keyobj
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1720 if (type
== REDIS_STRING
) {
1721 /* Read string value */
1722 if ((o
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1723 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
1724 /* Read list/set value */
1727 if ((listlen
= rdbLoadLen(fp
,rdbver
)) == REDIS_RDB_LENERR
)
1729 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
1730 /* Load every single element of the list/set */
1734 if ((ele
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1735 if (type
== REDIS_LIST
) {
1736 if (!listAddNodeTail((list
*)o
->ptr
,ele
))
1737 oom("listAddNodeTail");
1739 if (dictAdd((dict
*)o
->ptr
,ele
,NULL
) == DICT_ERR
)
1746 /* Add the new object in the hash table */
1747 retval
= dictAdd(d
,keyobj
,o
);
1748 if (retval
== DICT_ERR
) {
1749 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
1757 eoferr
: /* unexpected end of file is handled here with a fatal exit */
1758 decrRefCount(keyobj
);
1759 redisLog(REDIS_WARNING
,"Short read loading DB. Unrecoverable error, exiting now.");
1761 return REDIS_ERR
; /* Just to avoid warning */
1764 /*================================== Commands =============================== */
1766 static void pingCommand(redisClient
*c
) {
1767 addReply(c
,shared
.pong
);
1770 static void echoCommand(redisClient
*c
) {
1771 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
1772 (int)sdslen(c
->argv
[1]->ptr
)));
1773 addReply(c
,c
->argv
[1]);
1774 addReply(c
,shared
.crlf
);
1777 /*=================================== Strings =============================== */
1779 static void setGenericCommand(redisClient
*c
, int nx
) {
1782 retval
= dictAdd(c
->dict
,c
->argv
[1],c
->argv
[2]);
1783 if (retval
== DICT_ERR
) {
1785 dictReplace(c
->dict
,c
->argv
[1],c
->argv
[2]);
1786 incrRefCount(c
->argv
[2]);
1788 addReply(c
,shared
.czero
);
1792 incrRefCount(c
->argv
[1]);
1793 incrRefCount(c
->argv
[2]);
1796 addReply(c
, nx
? shared
.cone
: shared
.ok
);
1799 static void setCommand(redisClient
*c
) {
1800 return setGenericCommand(c
,0);
1803 static void setnxCommand(redisClient
*c
) {
1804 return setGenericCommand(c
,1);
1807 static void getCommand(redisClient
*c
) {
1810 de
= dictFind(c
->dict
,c
->argv
[1]);
1812 addReply(c
,shared
.nullbulk
);
1814 robj
*o
= dictGetEntryVal(de
);
1816 if (o
->type
!= REDIS_STRING
) {
1817 addReply(c
,shared
.wrongtypeerr
);
1819 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o
->ptr
)));
1821 addReply(c
,shared
.crlf
);
1826 static void mgetCommand(redisClient
*c
) {
1830 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
1831 for (j
= 1; j
< c
->argc
; j
++) {
1832 de
= dictFind(c
->dict
,c
->argv
[j
]);
1834 addReply(c
,shared
.nullbulk
);
1836 robj
*o
= dictGetEntryVal(de
);
1838 if (o
->type
!= REDIS_STRING
) {
1839 addReply(c
,shared
.nullbulk
);
1841 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o
->ptr
)));
1843 addReply(c
,shared
.crlf
);
1849 static void incrDecrCommand(redisClient
*c
, int incr
) {
1855 de
= dictFind(c
->dict
,c
->argv
[1]);
1859 robj
*o
= dictGetEntryVal(de
);
1861 if (o
->type
!= REDIS_STRING
) {
1866 value
= strtoll(o
->ptr
, &eptr
, 10);
1871 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
1872 retval
= dictAdd(c
->dict
,c
->argv
[1],o
);
1873 if (retval
== DICT_ERR
) {
1874 dictReplace(c
->dict
,c
->argv
[1],o
);
1876 incrRefCount(c
->argv
[1]);
1879 addReply(c
,shared
.colon
);
1881 addReply(c
,shared
.crlf
);
1884 static void incrCommand(redisClient
*c
) {
1885 return incrDecrCommand(c
,1);
1888 static void decrCommand(redisClient
*c
) {
1889 return incrDecrCommand(c
,-1);
1892 static void incrbyCommand(redisClient
*c
) {
1893 int incr
= atoi(c
->argv
[2]->ptr
);
1894 return incrDecrCommand(c
,incr
);
1897 static void decrbyCommand(redisClient
*c
) {
1898 int incr
= atoi(c
->argv
[2]->ptr
);
1899 return incrDecrCommand(c
,-incr
);
1902 /* ========================= Type agnostic commands ========================= */
1904 static void delCommand(redisClient
*c
) {
1905 if (dictDelete(c
->dict
,c
->argv
[1]) == DICT_OK
) {
1907 addReply(c
,shared
.cone
);
1909 addReply(c
,shared
.czero
);
1913 static void existsCommand(redisClient
*c
) {
1916 de
= dictFind(c
->dict
,c
->argv
[1]);
1918 addReply(c
,shared
.czero
);
1920 addReply(c
,shared
.cone
);
1923 static void selectCommand(redisClient
*c
) {
1924 int id
= atoi(c
->argv
[1]->ptr
);
1926 if (selectDb(c
,id
) == REDIS_ERR
) {
1927 addReplySds(c
,"-ERR invalid DB index\r\n");
1929 addReply(c
,shared
.ok
);
1933 static void randomkeyCommand(redisClient
*c
) {
1936 de
= dictGetRandomKey(c
->dict
);
1938 addReply(c
,shared
.crlf
);
1940 addReply(c
,shared
.plus
);
1941 addReply(c
,dictGetEntryKey(de
));
1942 addReply(c
,shared
.crlf
);
1946 static void keysCommand(redisClient
*c
) {
1949 sds pattern
= c
->argv
[1]->ptr
;
1950 int plen
= sdslen(pattern
);
1951 int numkeys
= 0, keyslen
= 0;
1952 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
1954 di
= dictGetIterator(c
->dict
);
1955 if (!di
) oom("dictGetIterator");
1957 decrRefCount(lenobj
);
1958 while((de
= dictNext(di
)) != NULL
) {
1959 robj
*keyobj
= dictGetEntryKey(de
);
1960 sds key
= keyobj
->ptr
;
1961 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
1962 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
1964 addReply(c
,shared
.space
);
1967 keyslen
+= sdslen(key
);
1970 dictReleaseIterator(di
);
1971 lenobj
->ptr
= sdscatprintf(sdsempty(),"$%lu\r\n",keyslen
+(numkeys
? (numkeys
-1) : 0));
1972 addReply(c
,shared
.crlf
);
1975 static void dbsizeCommand(redisClient
*c
) {
1977 sdscatprintf(sdsempty(),":%lu\r\n",dictGetHashTableUsed(c
->dict
)));
1980 static void lastsaveCommand(redisClient
*c
) {
1982 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
1985 static void typeCommand(redisClient
*c
) {
1989 de
= dictFind(c
->dict
,c
->argv
[1]);
1993 robj
*o
= dictGetEntryVal(de
);
1996 case REDIS_STRING
: type
= "+string"; break;
1997 case REDIS_LIST
: type
= "+list"; break;
1998 case REDIS_SET
: type
= "+set"; break;
1999 default: type
= "unknown"; break;
2002 addReplySds(c
,sdsnew(type
));
2003 addReply(c
,shared
.crlf
);
2006 static void saveCommand(redisClient
*c
) {
2007 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
2008 addReply(c
,shared
.ok
);
2010 addReply(c
,shared
.err
);
2014 static void bgsaveCommand(redisClient
*c
) {
2015 if (server
.bgsaveinprogress
) {
2016 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
2019 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
2020 addReply(c
,shared
.ok
);
2022 addReply(c
,shared
.err
);
2026 static void shutdownCommand(redisClient
*c
) {
2027 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
2028 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
2029 if (server
.daemonize
) {
2030 unlink(server
.pidfile
);
2032 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
2035 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
2036 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
2040 static void renameGenericCommand(redisClient
*c
, int nx
) {
2044 /* To use the same key as src and dst is probably an error */
2045 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
2046 addReply(c
,shared
.sameobjecterr
);
2050 de
= dictFind(c
->dict
,c
->argv
[1]);
2052 addReply(c
,shared
.nokeyerr
);
2055 o
= dictGetEntryVal(de
);
2057 if (dictAdd(c
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
2060 addReply(c
,shared
.czero
);
2063 dictReplace(c
->dict
,c
->argv
[2],o
);
2065 incrRefCount(c
->argv
[2]);
2067 dictDelete(c
->dict
,c
->argv
[1]);
2069 addReply(c
,nx
? shared
.cone
: shared
.ok
);
2072 static void renameCommand(redisClient
*c
) {
2073 renameGenericCommand(c
,0);
2076 static void renamenxCommand(redisClient
*c
) {
2077 renameGenericCommand(c
,1);
2080 static void moveCommand(redisClient
*c
) {
2086 /* Obtain source and target DB pointers */
2089 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
2090 addReply(c
,shared
.outofrangeerr
);
2097 /* If the user is moving using as target the same
2098 * DB as the source DB it is probably an error. */
2100 addReply(c
,shared
.sameobjecterr
);
2104 /* Check if the element exists and get a reference */
2105 de
= dictFind(c
->dict
,c
->argv
[1]);
2107 addReply(c
,shared
.czero
);
2111 /* Try to add the element to the target DB */
2112 key
= dictGetEntryKey(de
);
2113 o
= dictGetEntryVal(de
);
2114 if (dictAdd(dst
,key
,o
) == DICT_ERR
) {
2115 addReply(c
,shared
.czero
);
2121 /* OK! key moved, free the entry in the source DB */
2122 dictDelete(src
,c
->argv
[1]);
2124 addReply(c
,shared
.cone
);
2127 /* =================================== Lists ================================ */
2128 static void pushGenericCommand(redisClient
*c
, int where
) {
2133 de
= dictFind(c
->dict
,c
->argv
[1]);
2135 lobj
= createListObject();
2137 if (where
== REDIS_HEAD
) {
2138 if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead");
2140 if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail");
2142 dictAdd(c
->dict
,c
->argv
[1],lobj
);
2143 incrRefCount(c
->argv
[1]);
2144 incrRefCount(c
->argv
[2]);
2146 lobj
= dictGetEntryVal(de
);
2147 if (lobj
->type
!= REDIS_LIST
) {
2148 addReply(c
,shared
.wrongtypeerr
);
2152 if (where
== REDIS_HEAD
) {
2153 if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead");
2155 if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail");
2157 incrRefCount(c
->argv
[2]);
2160 addReply(c
,shared
.ok
);
2163 static void lpushCommand(redisClient
*c
) {
2164 pushGenericCommand(c
,REDIS_HEAD
);
2167 static void rpushCommand(redisClient
*c
) {
2168 pushGenericCommand(c
,REDIS_TAIL
);
2171 static void llenCommand(redisClient
*c
) {
2175 de
= dictFind(c
->dict
,c
->argv
[1]);
2177 addReply(c
,shared
.czero
);
2180 robj
*o
= dictGetEntryVal(de
);
2181 if (o
->type
!= REDIS_LIST
) {
2182 addReply(c
,shared
.wrongtypeerr
);
2185 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
)));
2190 static void lindexCommand(redisClient
*c
) {
2192 int index
= atoi(c
->argv
[2]->ptr
);
2194 de
= dictFind(c
->dict
,c
->argv
[1]);
2196 addReply(c
,shared
.nullbulk
);
2198 robj
*o
= dictGetEntryVal(de
);
2200 if (o
->type
!= REDIS_LIST
) {
2201 addReply(c
,shared
.wrongtypeerr
);
2203 list
*list
= o
->ptr
;
2206 ln
= listIndex(list
, index
);
2208 addReply(c
,shared
.nullbulk
);
2210 robj
*ele
= listNodeValue(ln
);
2211 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2213 addReply(c
,shared
.crlf
);
2219 static void lsetCommand(redisClient
*c
) {
2221 int index
= atoi(c
->argv
[2]->ptr
);
2223 de
= dictFind(c
->dict
,c
->argv
[1]);
2225 addReply(c
,shared
.nokeyerr
);
2227 robj
*o
= dictGetEntryVal(de
);
2229 if (o
->type
!= REDIS_LIST
) {
2230 addReply(c
,shared
.wrongtypeerr
);
2232 list
*list
= o
->ptr
;
2235 ln
= listIndex(list
, index
);
2237 addReply(c
,shared
.outofrangeerr
);
2239 robj
*ele
= listNodeValue(ln
);
2242 listNodeValue(ln
) = c
->argv
[3];
2243 incrRefCount(c
->argv
[3]);
2244 addReply(c
,shared
.ok
);
2251 static void popGenericCommand(redisClient
*c
, int where
) {
2254 de
= dictFind(c
->dict
,c
->argv
[1]);
2256 addReply(c
,shared
.nullbulk
);
2258 robj
*o
= dictGetEntryVal(de
);
2260 if (o
->type
!= REDIS_LIST
) {
2261 addReply(c
,shared
.wrongtypeerr
);
2263 list
*list
= o
->ptr
;
2266 if (where
== REDIS_HEAD
)
2267 ln
= listFirst(list
);
2269 ln
= listLast(list
);
2272 addReply(c
,shared
.nullbulk
);
2274 robj
*ele
= listNodeValue(ln
);
2275 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2277 addReply(c
,shared
.crlf
);
2278 listDelNode(list
,ln
);
2285 static void lpopCommand(redisClient
*c
) {
2286 popGenericCommand(c
,REDIS_HEAD
);
2289 static void rpopCommand(redisClient
*c
) {
2290 popGenericCommand(c
,REDIS_TAIL
);
2293 static void lrangeCommand(redisClient
*c
) {
2295 int start
= atoi(c
->argv
[2]->ptr
);
2296 int end
= atoi(c
->argv
[3]->ptr
);
2298 de
= dictFind(c
->dict
,c
->argv
[1]);
2300 addReply(c
,shared
.nullmultibulk
);
2302 robj
*o
= dictGetEntryVal(de
);
2304 if (o
->type
!= REDIS_LIST
) {
2305 addReply(c
,shared
.wrongtypeerr
);
2307 list
*list
= o
->ptr
;
2309 int llen
= listLength(list
);
2313 /* convert negative indexes */
2314 if (start
< 0) start
= llen
+start
;
2315 if (end
< 0) end
= llen
+end
;
2316 if (start
< 0) start
= 0;
2317 if (end
< 0) end
= 0;
2319 /* indexes sanity checks */
2320 if (start
> end
|| start
>= llen
) {
2321 /* Out of range start or start > end result in empty list */
2322 addReply(c
,shared
.emptymultibulk
);
2325 if (end
>= llen
) end
= llen
-1;
2326 rangelen
= (end
-start
)+1;
2328 /* Return the result in form of a multi-bulk reply */
2329 ln
= listIndex(list
, start
);
2330 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
2331 for (j
= 0; j
< rangelen
; j
++) {
2332 ele
= listNodeValue(ln
);
2333 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2335 addReply(c
,shared
.crlf
);
2342 static void ltrimCommand(redisClient
*c
) {
2344 int start
= atoi(c
->argv
[2]->ptr
);
2345 int end
= atoi(c
->argv
[3]->ptr
);
2347 de
= dictFind(c
->dict
,c
->argv
[1]);
2349 addReply(c
,shared
.nokeyerr
);
2351 robj
*o
= dictGetEntryVal(de
);
2353 if (o
->type
!= REDIS_LIST
) {
2354 addReply(c
,shared
.wrongtypeerr
);
2356 list
*list
= o
->ptr
;
2358 int llen
= listLength(list
);
2359 int j
, ltrim
, rtrim
;
2361 /* convert negative indexes */
2362 if (start
< 0) start
= llen
+start
;
2363 if (end
< 0) end
= llen
+end
;
2364 if (start
< 0) start
= 0;
2365 if (end
< 0) end
= 0;
2367 /* indexes sanity checks */
2368 if (start
> end
|| start
>= llen
) {
2369 /* Out of range start or start > end result in empty list */
2373 if (end
>= llen
) end
= llen
-1;
2378 /* Remove list elements to perform the trim */
2379 for (j
= 0; j
< ltrim
; j
++) {
2380 ln
= listFirst(list
);
2381 listDelNode(list
,ln
);
2383 for (j
= 0; j
< rtrim
; j
++) {
2384 ln
= listLast(list
);
2385 listDelNode(list
,ln
);
2387 addReply(c
,shared
.ok
);
2393 static void lremCommand(redisClient
*c
) {
2396 de
= dictFind(c
->dict
,c
->argv
[1]);
2398 addReply(c
,shared
.nokeyerr
);
2400 robj
*o
= dictGetEntryVal(de
);
2402 if (o
->type
!= REDIS_LIST
) {
2403 addReply(c
,shared
.wrongtypeerr
);
2405 list
*list
= o
->ptr
;
2406 listNode
*ln
, *next
;
2407 int toremove
= atoi(c
->argv
[2]->ptr
);
2412 toremove
= -toremove
;
2415 ln
= fromtail
? list
->tail
: list
->head
;
2417 next
= fromtail
? ln
->prev
: ln
->next
;
2418 robj
*ele
= listNodeValue(ln
);
2419 if (sdscmp(ele
->ptr
,c
->argv
[3]->ptr
) == 0) {
2420 listDelNode(list
,ln
);
2423 if (toremove
&& removed
== toremove
) break;
2427 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
2432 /* ==================================== Sets ================================ */
2434 static void saddCommand(redisClient
*c
) {
2438 de
= dictFind(c
->dict
,c
->argv
[1]);
2440 set
= createSetObject();
2441 dictAdd(c
->dict
,c
->argv
[1],set
);
2442 incrRefCount(c
->argv
[1]);
2444 set
= dictGetEntryVal(de
);
2445 if (set
->type
!= REDIS_SET
) {
2446 addReply(c
,shared
.wrongtypeerr
);
2450 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
2451 incrRefCount(c
->argv
[2]);
2453 addReply(c
,shared
.cone
);
2455 addReply(c
,shared
.czero
);
2459 static void sremCommand(redisClient
*c
) {
2462 de
= dictFind(c
->dict
,c
->argv
[1]);
2464 addReply(c
,shared
.czero
);
2468 set
= dictGetEntryVal(de
);
2469 if (set
->type
!= REDIS_SET
) {
2470 addReply(c
,shared
.wrongtypeerr
);
2473 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
2475 addReply(c
,shared
.cone
);
2477 addReply(c
,shared
.czero
);
2482 static void sismemberCommand(redisClient
*c
) {
2485 de
= dictFind(c
->dict
,c
->argv
[1]);
2487 addReply(c
,shared
.czero
);
2491 set
= dictGetEntryVal(de
);
2492 if (set
->type
!= REDIS_SET
) {
2493 addReply(c
,shared
.wrongtypeerr
);
2496 if (dictFind(set
->ptr
,c
->argv
[2]))
2497 addReply(c
,shared
.cone
);
2499 addReply(c
,shared
.czero
);
2503 static void scardCommand(redisClient
*c
) {
2507 de
= dictFind(c
->dict
,c
->argv
[1]);
2509 addReply(c
,shared
.czero
);
2512 robj
*o
= dictGetEntryVal(de
);
2513 if (o
->type
!= REDIS_SET
) {
2514 addReply(c
,shared
.wrongtypeerr
);
2517 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",
2518 dictGetHashTableUsed(s
)));
2523 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
2524 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
2526 return dictGetHashTableUsed(*d1
)-dictGetHashTableUsed(*d2
);
2529 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
) {
2530 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
2533 robj
*lenobj
= NULL
, *dstset
= NULL
;
2534 int j
, cardinality
= 0;
2536 if (!dv
) oom("sinterCommand");
2537 for (j
= 0; j
< setsnum
; j
++) {
2541 de
= dictFind(c
->dict
,setskeys
[j
]);
2544 addReply(c
,shared
.nokeyerr
);
2547 setobj
= dictGetEntryVal(de
);
2548 if (setobj
->type
!= REDIS_SET
) {
2550 addReply(c
,shared
.wrongtypeerr
);
2553 dv
[j
] = setobj
->ptr
;
2555 /* Sort sets from the smallest to largest, this will improve our
2556 * algorithm's performace */
2557 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
2559 /* The first thing we should output is the total number of elements...
2560 * since this is a multi-bulk write, but at this stage we don't know
2561 * the intersection set size, so we use a trick, append an empty object
2562 * to the output list and save the pointer to later modify it with the
2565 lenobj
= createObject(REDIS_STRING
,NULL
);
2567 decrRefCount(lenobj
);
2569 /* If we have a target key where to store the resulting set
2570 * create this key with an empty set inside */
2571 dstset
= createSetObject();
2572 dictDelete(c
->dict
,dstkey
);
2573 dictAdd(c
->dict
,dstkey
,dstset
);
2574 incrRefCount(dstkey
);
2577 /* Iterate all the elements of the first (smallest) set, and test
2578 * the element against all the other sets, if at least one set does
2579 * not include the element it is discarded */
2580 di
= dictGetIterator(dv
[0]);
2581 if (!di
) oom("dictGetIterator");
2583 while((de
= dictNext(di
)) != NULL
) {
2586 for (j
= 1; j
< setsnum
; j
++)
2587 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
2589 continue; /* at least one set does not contain the member */
2590 ele
= dictGetEntryKey(de
);
2592 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(ele
->ptr
)));
2594 addReply(c
,shared
.crlf
);
2597 dictAdd(dstset
->ptr
,ele
,NULL
);
2601 dictReleaseIterator(di
);
2604 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",cardinality
);
2606 addReply(c
,shared
.ok
);
2610 static void sinterCommand(redisClient
*c
) {
2611 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
2614 static void sinterstoreCommand(redisClient
*c
) {
2615 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
2618 static void flushdbCommand(redisClient
*c
) {
2620 addReply(c
,shared
.ok
);
2621 rdbSave(server
.dbfilename
);
2624 static void flushallCommand(redisClient
*c
) {
2626 addReply(c
,shared
.ok
);
2627 rdbSave(server
.dbfilename
);
2630 redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
2631 redisSortOperation
*so
= zmalloc(sizeof(*so
));
2632 if (!so
) oom("createSortOperation");
2634 so
->pattern
= pattern
;
2638 /* Return the value associated to the key with a name obtained
2639 * substituting the first occurence of '*' in 'pattern' with 'subst' */
2640 robj
*lookupKeyByPattern(dict
*dict
, robj
*pattern
, robj
*subst
) {
2644 int prefixlen
, sublen
, postfixlen
;
2646 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
2650 char buf
[REDIS_SORTKEY_MAX
+1];
2654 spat
= pattern
->ptr
;
2656 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
2657 p
= strchr(spat
,'*');
2658 if (!p
) return NULL
;
2661 sublen
= sdslen(ssub
);
2662 postfixlen
= sdslen(spat
)-(prefixlen
+1);
2663 memcpy(keyname
.buf
,spat
,prefixlen
);
2664 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
2665 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
2666 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
2667 keyname
.len
= prefixlen
+sublen
+postfixlen
;
2669 keyobj
.refcount
= 1;
2670 keyobj
.type
= REDIS_STRING
;
2671 keyobj
.ptr
= ((char*)&keyname
)+(sizeof(long)*2);
2673 de
= dictFind(dict
,&keyobj
);
2674 // printf("lookup '%s' => %p\n", keyname.buf,de);
2675 if (!de
) return NULL
;
2676 return dictGetEntryVal(de
);
2679 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
2680 * the additional parameter is not standard but a BSD-specific we have to
2681 * pass sorting parameters via the global 'server' structure */
2682 static int sortCompare(const void *s1
, const void *s2
) {
2683 const redisSortObject
*so1
= s1
, *so2
= s2
;
2686 if (!server
.sort_alpha
) {
2687 /* Numeric sorting. Here it's trivial as we precomputed scores */
2688 if (so1
->u
.score
> so2
->u
.score
) {
2690 } else if (so1
->u
.score
< so2
->u
.score
) {
2696 /* Alphanumeric sorting */
2697 if (server
.sort_bypattern
) {
2698 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
2699 /* At least one compare object is NULL */
2700 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
2702 else if (so1
->u
.cmpobj
== NULL
)
2707 /* We have both the objects, use strcoll */
2708 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
2711 /* Compare elements directly */
2712 cmp
= strcoll(so1
->obj
->ptr
,so2
->obj
->ptr
);
2715 return server
.sort_desc
? -cmp
: cmp
;
2718 /* The SORT command is the most complex command in Redis. Warning: this code
2719 * is optimized for speed and a bit less for readability */
2720 static void sortCommand(redisClient
*c
) {
2724 int desc
= 0, alpha
= 0;
2725 int limit_start
= 0, limit_count
= -1, start
, end
;
2726 int j
, dontsort
= 0, vectorlen
;
2727 int getop
= 0; /* GET operation counter */
2728 robj
*sortval
, *sortby
= NULL
;
2729 redisSortObject
*vector
; /* Resulting vector to sort */
2731 /* Lookup the key to sort. It must be of the right types */
2732 de
= dictFind(c
->dict
,c
->argv
[1]);
2734 addReply(c
,shared
.nokeyerr
);
2737 sortval
= dictGetEntryVal(de
);
2738 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
) {
2739 addReply(c
,shared
.wrongtypeerr
);
2743 /* Create a list of operations to perform for every sorted element.
2744 * Operations can be GET/DEL/INCR/DECR */
2745 operations
= listCreate();
2746 listSetFreeMethod(operations
,zfree
);
2749 /* Now we need to protect sortval incrementing its count, in the future
2750 * SORT may have options able to overwrite/delete keys during the sorting
2751 * and the sorted key itself may get destroied */
2752 incrRefCount(sortval
);
2754 /* The SORT command has an SQL-alike syntax, parse it */
2755 while(j
< c
->argc
) {
2756 int leftargs
= c
->argc
-j
-1;
2757 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
2759 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
2761 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
2763 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
2764 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
2765 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
2767 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
2768 sortby
= c
->argv
[j
+1];
2769 /* If the BY pattern does not contain '*', i.e. it is constant,
2770 * we don't need to sort nor to lookup the weight keys. */
2771 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
2773 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
2774 listAddNodeTail(operations
,createSortOperation(
2775 REDIS_SORT_GET
,c
->argv
[j
+1]));
2778 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"del") && leftargs
>= 1) {
2779 listAddNodeTail(operations
,createSortOperation(
2780 REDIS_SORT_DEL
,c
->argv
[j
+1]));
2782 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"incr") && leftargs
>= 1) {
2783 listAddNodeTail(operations
,createSortOperation(
2784 REDIS_SORT_INCR
,c
->argv
[j
+1]));
2786 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
2787 listAddNodeTail(operations
,createSortOperation(
2788 REDIS_SORT_DECR
,c
->argv
[j
+1]));
2791 decrRefCount(sortval
);
2792 listRelease(operations
);
2793 addReply(c
,shared
.syntaxerr
);
2799 /* Load the sorting vector with all the objects to sort */
2800 vectorlen
= (sortval
->type
== REDIS_LIST
) ?
2801 listLength((list
*)sortval
->ptr
) :
2802 dictGetHashTableUsed((dict
*)sortval
->ptr
);
2803 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
2804 if (!vector
) oom("allocating objects vector for SORT");
2806 if (sortval
->type
== REDIS_LIST
) {
2807 list
*list
= sortval
->ptr
;
2808 listNode
*ln
= list
->head
;
2810 robj
*ele
= ln
->value
;
2811 vector
[j
].obj
= ele
;
2812 vector
[j
].u
.score
= 0;
2813 vector
[j
].u
.cmpobj
= NULL
;
2818 dict
*set
= sortval
->ptr
;
2822 di
= dictGetIterator(set
);
2823 if (!di
) oom("dictGetIterator");
2824 while((setele
= dictNext(di
)) != NULL
) {
2825 vector
[j
].obj
= dictGetEntryKey(setele
);
2826 vector
[j
].u
.score
= 0;
2827 vector
[j
].u
.cmpobj
= NULL
;
2830 dictReleaseIterator(di
);
2832 assert(j
== vectorlen
);
2834 /* Now it's time to load the right scores in the sorting vector */
2835 if (dontsort
== 0) {
2836 for (j
= 0; j
< vectorlen
; j
++) {
2840 byval
= lookupKeyByPattern(c
->dict
,sortby
,vector
[j
].obj
);
2841 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
2843 vector
[j
].u
.cmpobj
= byval
;
2844 incrRefCount(byval
);
2846 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
2849 if (!alpha
) vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
2854 /* We are ready to sort the vector... perform a bit of sanity check
2855 * on the LIMIT option too. We'll use a partial version of quicksort. */
2856 start
= (limit_start
< 0) ? 0 : limit_start
;
2857 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
2858 if (start
>= vectorlen
) {
2859 start
= vectorlen
-1;
2862 if (end
>= vectorlen
) end
= vectorlen
-1;
2864 if (dontsort
== 0) {
2865 server
.sort_desc
= desc
;
2866 server
.sort_alpha
= alpha
;
2867 server
.sort_bypattern
= sortby
? 1 : 0;
2868 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
2871 /* Send command output to the output buffer, performing the specified
2872 * GET/DEL/INCR/DECR operations if any. */
2873 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
2874 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
2875 for (j
= start
; j
<= end
; j
++) {
2876 listNode
*ln
= operations
->head
;
2878 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
2879 sdslen(vector
[j
].obj
->ptr
)));
2880 addReply(c
,vector
[j
].obj
);
2881 addReply(c
,shared
.crlf
);
2884 redisSortOperation
*sop
= ln
->value
;
2885 robj
*val
= lookupKeyByPattern(c
->dict
,sop
->pattern
,
2888 if (sop
->type
== REDIS_SORT_GET
) {
2889 if (!val
|| val
->type
!= REDIS_STRING
) {
2890 addReply(c
,shared
.nullbulk
);
2892 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
2895 addReply(c
,shared
.crlf
);
2897 } else if (sop
->type
== REDIS_SORT_DEL
) {
2905 decrRefCount(sortval
);
2906 listRelease(operations
);
2907 for (j
= 0; j
< vectorlen
; j
++) {
2908 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
2909 decrRefCount(vector
[j
].u
.cmpobj
);
2914 static void infoCommand(redisClient
*c
) {
2916 time_t uptime
= time(NULL
)-server
.stat_starttime
;
2918 info
= sdscatprintf(sdsempty(),
2919 "redis_version:%s\r\n"
2920 "connected_clients:%d\r\n"
2921 "connected_slaves:%d\r\n"
2922 "used_memory:%d\r\n"
2923 "changes_since_last_save:%lld\r\n"
2924 "last_save_time:%d\r\n"
2925 "total_connections_received:%lld\r\n"
2926 "total_commands_processed:%lld\r\n"
2927 "uptime_in_seconds:%d\r\n"
2928 "uptime_in_days:%d\r\n"
2930 listLength(server
.clients
)-listLength(server
.slaves
),
2931 listLength(server
.slaves
),
2935 server
.stat_numconnections
,
2936 server
.stat_numcommands
,
2940 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(info
)));
2941 addReplySds(c
,info
);
2942 addReply(c
,shared
.crlf
);
2945 /* =============================== Replication ============================= */
2947 /* Send the whole output buffer syncronously to the slave. This a general operation in theory, but it is actually useful only for replication. */
2948 static int flushClientOutput(redisClient
*c
) {
2950 time_t start
= time(NULL
);
2952 while(listLength(c
->reply
)) {
2953 if (time(NULL
)-start
> 5) return REDIS_ERR
; /* 5 seconds timeout */
2954 retval
= aeWait(c
->fd
,AE_WRITABLE
,1000);
2957 } else if (retval
& AE_WRITABLE
) {
2958 sendReplyToClient(NULL
, c
->fd
, c
, AE_WRITABLE
);
2964 static int syncWrite(int fd
, void *ptr
, ssize_t size
, int timeout
) {
2965 ssize_t nwritten
, ret
= size
;
2966 time_t start
= time(NULL
);
2970 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
2971 nwritten
= write(fd
,ptr
,size
);
2972 if (nwritten
== -1) return -1;
2976 if ((time(NULL
)-start
) > timeout
) {
2984 static int syncRead(int fd
, void *ptr
, ssize_t size
, int timeout
) {
2985 ssize_t nread
, totread
= 0;
2986 time_t start
= time(NULL
);
2990 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
2991 nread
= read(fd
,ptr
,size
);
2992 if (nread
== -1) return -1;
2997 if ((time(NULL
)-start
) > timeout
) {
3005 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
3012 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
3015 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
3026 static void syncCommand(redisClient
*c
) {
3029 time_t start
= time(NULL
);
3032 /* ignore SYNC if aleady slave or in monitor mode */
3033 if (c
->flags
& REDIS_SLAVE
) return;
3035 redisLog(REDIS_NOTICE
,"Slave ask for syncronization");
3036 if (flushClientOutput(c
) == REDIS_ERR
||
3037 rdbSave(server
.dbfilename
) != REDIS_OK
)
3040 fd
= open(server
.dbfilename
, O_RDONLY
);
3041 if (fd
== -1 || fstat(fd
,&sb
) == -1) goto closeconn
;
3044 snprintf(sizebuf
,32,"$%d\r\n",len
);
3045 if (syncWrite(c
->fd
,sizebuf
,strlen(sizebuf
),5) == -1) goto closeconn
;
3050 if (time(NULL
)-start
> REDIS_MAX_SYNC_TIME
) goto closeconn
;
3051 nread
= read(fd
,buf
,1024);
3052 if (nread
== -1) goto closeconn
;
3054 if (syncWrite(c
->fd
,buf
,nread
,5) == -1) goto closeconn
;
3056 if (syncWrite(c
->fd
,"\r\n",2,5) == -1) goto closeconn
;
3058 c
->flags
|= REDIS_SLAVE
;
3060 if (!listAddNodeTail(server
.slaves
,c
)) oom("listAddNodeTail");
3061 redisLog(REDIS_NOTICE
,"Syncronization with slave succeeded");
3065 if (fd
!= -1) close(fd
);
3066 c
->flags
|= REDIS_CLOSE
;
3067 redisLog(REDIS_WARNING
,"Syncronization with slave failed");
3071 static int syncWithMaster(void) {
3072 char buf
[1024], tmpfile
[256];
3074 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
3078 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
3082 /* Issue the SYNC command */
3083 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
3085 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
3089 /* Read the bulk write count */
3090 if (syncReadLine(fd
,buf
,1024,5) == -1) {
3092 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
3096 dumpsize
= atoi(buf
+1);
3097 redisLog(REDIS_NOTICE
,"Receiving %d bytes data dump from MASTER",dumpsize
);
3098 /* Read the bulk write data on a temp file */
3099 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
3100 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644);
3103 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
3107 int nread
, nwritten
;
3109 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
3111 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
3117 nwritten
= write(dfd
,buf
,nread
);
3118 if (nwritten
== -1) {
3119 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
3127 if (rename(tmpfile
,server
.dbfilename
) == -1) {
3128 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
3134 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
3135 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
3139 server
.master
= createClient(fd
);
3140 server
.master
->flags
|= REDIS_MASTER
;
3141 server
.replstate
= REDIS_REPL_CONNECTED
;
3145 static void monitorCommand(redisClient
*c
) {
3146 /* ignore MONITOR if aleady slave or in monitor mode */
3147 if (c
->flags
& REDIS_SLAVE
) return;
3149 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
3151 if (!listAddNodeTail(server
.monitors
,c
)) oom("listAddNodeTail");
3152 addReply(c
,shared
.ok
);
3155 /* =================================== Main! ================================ */
3157 static void daemonize(void) {
3161 if (fork() != 0) exit(0); /* parent exits */
3162 setsid(); /* create a new session */
3164 /* Every output goes to /dev/null. If Redis is daemonized but
3165 * the 'logfile' is set to 'stdout' in the configuration file
3166 * it will not log at all. */
3167 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
3168 dup2(fd
, STDIN_FILENO
);
3169 dup2(fd
, STDOUT_FILENO
);
3170 dup2(fd
, STDERR_FILENO
);
3171 if (fd
> STDERR_FILENO
) close(fd
);
3173 /* Try to write the pid file */
3174 fp
= fopen(server
.pidfile
,"w");
3176 fprintf(fp
,"%d\n",getpid());
3181 int main(int argc
, char **argv
) {
3184 ResetServerSaveParams();
3185 loadServerConfig(argv
[1]);
3186 } else if (argc
> 2) {
3187 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
3191 if (server
.daemonize
) daemonize();
3192 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
3193 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
3194 redisLog(REDIS_NOTICE
,"DB loaded from disk");
3195 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
3196 acceptHandler
, NULL
, NULL
) == AE_ERR
) oom("creating file event");
3197 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
3199 aeDeleteEventLoop(server
.el
);