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 */
164 int authenticated
; /* when requirepass is non-NULL */
172 /* Global server state structure */
178 unsigned int sharingpoolsize
;
179 long long dirty
; /* changes to DB from the last save */
181 list
*slaves
, *monitors
;
182 char neterr
[ANET_ERR_LEN
];
184 int cronloops
; /* number of times the cron function run */
185 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
186 time_t lastsave
; /* Unix time of last save succeeede */
187 int usedmemory
; /* Used memory in megabytes */
188 /* Fields used only for stats */
189 time_t stat_starttime
; /* server start time */
190 long long stat_numcommands
; /* number of processed commands */
191 long long stat_numconnections
; /* number of connections received */
199 int bgsaveinprogress
;
200 struct saveparam
*saveparams
;
207 /* Replication related */
213 /* Sort parameters - qsort_r() is only available under BSD so we
214 * have to take this state global, in order to pass it to sortCompare() */
220 typedef void redisCommandProc(redisClient
*c
);
221 struct redisCommand
{
223 redisCommandProc
*proc
;
228 typedef struct _redisSortObject
{
236 typedef struct _redisSortOperation
{
239 } redisSortOperation
;
241 struct sharedObjectsStruct
{
242 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
243 *colon
, *nullbulk
, *nullmultibulk
,
244 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
245 *outofrangeerr
, *plus
,
246 *select0
, *select1
, *select2
, *select3
, *select4
,
247 *select5
, *select6
, *select7
, *select8
, *select9
;
250 /*================================ Prototypes =============================== */
252 static void freeStringObject(robj
*o
);
253 static void freeListObject(robj
*o
);
254 static void freeSetObject(robj
*o
);
255 static void decrRefCount(void *o
);
256 static robj
*createObject(int type
, void *ptr
);
257 static void freeClient(redisClient
*c
);
258 static int rdbLoad(char *filename
);
259 static void addReply(redisClient
*c
, robj
*obj
);
260 static void addReplySds(redisClient
*c
, sds s
);
261 static void incrRefCount(robj
*o
);
262 static int rdbSaveBackground(char *filename
);
263 static robj
*createStringObject(char *ptr
, size_t len
);
264 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
265 static int syncWithMaster(void);
266 static robj
*tryObjectSharing(robj
*o
);
268 static void authCommand(redisClient
*c
);
269 static void pingCommand(redisClient
*c
);
270 static void echoCommand(redisClient
*c
);
271 static void setCommand(redisClient
*c
);
272 static void setnxCommand(redisClient
*c
);
273 static void getCommand(redisClient
*c
);
274 static void delCommand(redisClient
*c
);
275 static void existsCommand(redisClient
*c
);
276 static void incrCommand(redisClient
*c
);
277 static void decrCommand(redisClient
*c
);
278 static void incrbyCommand(redisClient
*c
);
279 static void decrbyCommand(redisClient
*c
);
280 static void selectCommand(redisClient
*c
);
281 static void randomkeyCommand(redisClient
*c
);
282 static void keysCommand(redisClient
*c
);
283 static void dbsizeCommand(redisClient
*c
);
284 static void lastsaveCommand(redisClient
*c
);
285 static void saveCommand(redisClient
*c
);
286 static void bgsaveCommand(redisClient
*c
);
287 static void shutdownCommand(redisClient
*c
);
288 static void moveCommand(redisClient
*c
);
289 static void renameCommand(redisClient
*c
);
290 static void renamenxCommand(redisClient
*c
);
291 static void lpushCommand(redisClient
*c
);
292 static void rpushCommand(redisClient
*c
);
293 static void lpopCommand(redisClient
*c
);
294 static void rpopCommand(redisClient
*c
);
295 static void llenCommand(redisClient
*c
);
296 static void lindexCommand(redisClient
*c
);
297 static void lrangeCommand(redisClient
*c
);
298 static void ltrimCommand(redisClient
*c
);
299 static void typeCommand(redisClient
*c
);
300 static void lsetCommand(redisClient
*c
);
301 static void saddCommand(redisClient
*c
);
302 static void sremCommand(redisClient
*c
);
303 static void sismemberCommand(redisClient
*c
);
304 static void scardCommand(redisClient
*c
);
305 static void sinterCommand(redisClient
*c
);
306 static void sinterstoreCommand(redisClient
*c
);
307 static void syncCommand(redisClient
*c
);
308 static void flushdbCommand(redisClient
*c
);
309 static void flushallCommand(redisClient
*c
);
310 static void sortCommand(redisClient
*c
);
311 static void lremCommand(redisClient
*c
);
312 static void infoCommand(redisClient
*c
);
313 static void mgetCommand(redisClient
*c
);
314 static void monitorCommand(redisClient
*c
);
316 /*================================= Globals ================================= */
319 static struct redisServer server
; /* server global state */
320 static struct redisCommand cmdTable
[] = {
321 {"get",getCommand
,2,REDIS_CMD_INLINE
},
322 {"set",setCommand
,3,REDIS_CMD_BULK
},
323 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
},
324 {"del",delCommand
,2,REDIS_CMD_INLINE
},
325 {"exists",existsCommand
,2,REDIS_CMD_INLINE
},
326 {"incr",incrCommand
,2,REDIS_CMD_INLINE
},
327 {"decr",decrCommand
,2,REDIS_CMD_INLINE
},
328 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
},
329 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
},
330 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
},
331 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
},
332 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
},
333 {"llen",llenCommand
,2,REDIS_CMD_INLINE
},
334 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
},
335 {"lset",lsetCommand
,4,REDIS_CMD_BULK
},
336 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
},
337 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
},
338 {"lrem",lremCommand
,4,REDIS_CMD_BULK
},
339 {"sadd",saddCommand
,3,REDIS_CMD_BULK
},
340 {"srem",sremCommand
,3,REDIS_CMD_BULK
},
341 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
},
342 {"scard",scardCommand
,2,REDIS_CMD_INLINE
},
343 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
},
344 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
},
345 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
},
346 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
},
347 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
},
348 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
},
349 {"select",selectCommand
,2,REDIS_CMD_INLINE
},
350 {"move",moveCommand
,3,REDIS_CMD_INLINE
},
351 {"rename",renameCommand
,3,REDIS_CMD_INLINE
},
352 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
},
353 {"keys",keysCommand
,2,REDIS_CMD_INLINE
},
354 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
},
355 {"auth",authCommand
,2,REDIS_CMD_INLINE
},
356 {"ping",pingCommand
,1,REDIS_CMD_INLINE
},
357 {"echo",echoCommand
,2,REDIS_CMD_BULK
},
358 {"save",saveCommand
,1,REDIS_CMD_INLINE
},
359 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
},
360 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
},
361 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
},
362 {"type",typeCommand
,2,REDIS_CMD_INLINE
},
363 {"sync",syncCommand
,1,REDIS_CMD_INLINE
},
364 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
},
365 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
},
366 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
},
367 {"info",infoCommand
,1,REDIS_CMD_INLINE
},
368 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
},
372 /*============================ Utility functions ============================ */
374 /* Glob-style pattern matching. */
375 int stringmatchlen(const char *pattern
, int patternLen
,
376 const char *string
, int stringLen
, int nocase
)
381 while (pattern
[1] == '*') {
386 return 1; /* match */
388 if (stringmatchlen(pattern
+1, patternLen
-1,
389 string
, stringLen
, nocase
))
390 return 1; /* match */
394 return 0; /* no match */
398 return 0; /* no match */
408 not = pattern
[0] == '^';
415 if (pattern
[0] == '\\') {
418 if (pattern
[0] == string
[0])
420 } else if (pattern
[0] == ']') {
422 } else if (patternLen
== 0) {
426 } else if (pattern
[1] == '-' && patternLen
>= 3) {
427 int start
= pattern
[0];
428 int end
= pattern
[2];
436 start
= tolower(start
);
442 if (c
>= start
&& c
<= end
)
446 if (pattern
[0] == string
[0])
449 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
459 return 0; /* no match */
465 if (patternLen
>= 2) {
472 if (pattern
[0] != string
[0])
473 return 0; /* no match */
475 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
476 return 0; /* no match */
484 if (stringLen
== 0) {
485 while(*pattern
== '*') {
492 if (patternLen
== 0 && stringLen
== 0)
497 void redisLog(int level
, const char *fmt
, ...)
502 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
506 if (level
>= server
.verbosity
) {
508 fprintf(fp
,"%c ",c
[level
]);
509 vfprintf(fp
, fmt
, ap
);
515 if (server
.logfile
) fclose(fp
);
518 /*====================== Hash table type implementation ==================== */
520 /* This is an hash table type that uses the SDS dynamic strings libary as
521 * keys and radis objects as values (objects can hold SDS strings,
524 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
528 DICT_NOTUSED(privdata
);
530 l1
= sdslen((sds
)key1
);
531 l2
= sdslen((sds
)key2
);
532 if (l1
!= l2
) return 0;
533 return memcmp(key1
, key2
, l1
) == 0;
536 static void dictRedisObjectDestructor(void *privdata
, void *val
)
538 DICT_NOTUSED(privdata
);
543 static int dictSdsKeyCompare(void *privdata
, const void *key1
,
546 const robj
*o1
= key1
, *o2
= key2
;
547 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
550 static unsigned int dictSdsHash(const void *key
) {
552 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
555 static dictType setDictType
= {
556 dictSdsHash
, /* hash function */
559 dictSdsKeyCompare
, /* key compare */
560 dictRedisObjectDestructor
, /* key destructor */
561 NULL
/* val destructor */
564 static dictType hashDictType
= {
565 dictSdsHash
, /* hash function */
568 dictSdsKeyCompare
, /* key compare */
569 dictRedisObjectDestructor
, /* key destructor */
570 dictRedisObjectDestructor
/* val destructor */
573 /* ========================= Random utility functions ======================= */
575 /* Redis generally does not try to recover from out of memory conditions
576 * when allocating objects or strings, it is not clear if it will be possible
577 * to report this condition to the client since the networking layer itself
578 * is based on heap allocation for send buffers, so we simply abort.
579 * At least the code will be simpler to read... */
580 static void oom(const char *msg
) {
581 fprintf(stderr
, "%s: Out of memory\n",msg
);
587 /* ====================== Redis server networking stuff ===================== */
588 void closeTimedoutClients(void) {
592 time_t now
= time(NULL
);
594 li
= listGetIterator(server
.clients
,AL_START_HEAD
);
596 while ((ln
= listNextElement(li
)) != NULL
) {
597 c
= listNodeValue(ln
);
598 if (!(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
599 (now
- c
->lastinteraction
> server
.maxidletime
)) {
600 redisLog(REDIS_DEBUG
,"Closing idle client");
604 listReleaseIterator(li
);
607 int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
608 int j
, size
, used
, loops
= server
.cronloops
++;
609 REDIS_NOTUSED(eventLoop
);
611 REDIS_NOTUSED(clientData
);
613 /* Update the global state with the amount of used memory */
614 server
.usedmemory
= zmalloc_used_memory();
616 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
617 * we resize the hash table to save memory */
618 for (j
= 0; j
< server
.dbnum
; j
++) {
619 size
= dictGetHashTableSize(server
.dict
[j
]);
620 used
= dictGetHashTableUsed(server
.dict
[j
]);
621 if (!(loops
% 5) && used
> 0) {
622 redisLog(REDIS_DEBUG
,"DB %d: %d keys in %d slots HT.",j
,used
,size
);
623 // dictPrintStats(server.dict);
625 if (size
&& used
&& size
> REDIS_HT_MINSLOTS
&&
626 (used
*100/size
< REDIS_HT_MINFILL
)) {
627 redisLog(REDIS_NOTICE
,"The hash table %d is too sparse, resize it...",j
);
628 dictResize(server
.dict
[j
]);
629 redisLog(REDIS_NOTICE
,"Hash table %d resized.",j
);
633 /* Show information about connected clients */
635 redisLog(REDIS_DEBUG
,"%d clients connected (%d slaves), %d bytes in use",
636 listLength(server
.clients
)-listLength(server
.slaves
),
637 listLength(server
.slaves
),
639 dictGetHashTableUsed(server
.sharingpool
));
642 /* Close connections of timedout clients */
644 closeTimedoutClients();
646 /* Check if a background saving in progress terminated */
647 if (server
.bgsaveinprogress
) {
649 if (wait4(-1,&statloc
,WNOHANG
,NULL
)) {
650 int exitcode
= WEXITSTATUS(statloc
);
652 redisLog(REDIS_NOTICE
,
653 "Background saving terminated with success");
655 server
.lastsave
= time(NULL
);
657 redisLog(REDIS_WARNING
,
658 "Background saving error");
660 server
.bgsaveinprogress
= 0;
663 /* If there is not a background saving in progress check if
664 * we have to save now */
665 time_t now
= time(NULL
);
666 for (j
= 0; j
< server
.saveparamslen
; j
++) {
667 struct saveparam
*sp
= server
.saveparams
+j
;
669 if (server
.dirty
>= sp
->changes
&&
670 now
-server
.lastsave
> sp
->seconds
) {
671 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
672 sp
->changes
, sp
->seconds
);
673 rdbSaveBackground(server
.dbfilename
);
678 /* Check if we should connect to a MASTER */
679 if (server
.replstate
== REDIS_REPL_CONNECT
) {
680 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
681 if (syncWithMaster() == REDIS_OK
) {
682 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
688 static void createSharedObjects(void) {
689 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
690 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
691 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
692 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
693 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
694 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
695 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
696 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
697 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
699 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
700 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
701 "-ERR Operation against a key holding the wrong kind of value\r\n"));
702 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
703 "-ERR no such key\r\n"));
704 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
705 "-ERR syntax error\r\n"));
706 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
707 "-ERR source and destination objects are the same\r\n"));
708 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
709 "-ERR index out of range\r\n"));
710 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
711 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
712 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
713 shared
.select0
= createStringObject("select 0\r\n",10);
714 shared
.select1
= createStringObject("select 1\r\n",10);
715 shared
.select2
= createStringObject("select 2\r\n",10);
716 shared
.select3
= createStringObject("select 3\r\n",10);
717 shared
.select4
= createStringObject("select 4\r\n",10);
718 shared
.select5
= createStringObject("select 5\r\n",10);
719 shared
.select6
= createStringObject("select 6\r\n",10);
720 shared
.select7
= createStringObject("select 7\r\n",10);
721 shared
.select8
= createStringObject("select 8\r\n",10);
722 shared
.select9
= createStringObject("select 9\r\n",10);
725 static void appendServerSaveParams(time_t seconds
, int changes
) {
726 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
727 if (server
.saveparams
== NULL
) oom("appendServerSaveParams");
728 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
729 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
730 server
.saveparamslen
++;
733 static void ResetServerSaveParams() {
734 zfree(server
.saveparams
);
735 server
.saveparams
= NULL
;
736 server
.saveparamslen
= 0;
739 static void initServerConfig() {
740 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
741 server
.port
= REDIS_SERVERPORT
;
742 server
.verbosity
= REDIS_DEBUG
;
743 server
.maxidletime
= REDIS_MAXIDLETIME
;
744 server
.saveparams
= NULL
;
745 server
.logfile
= NULL
; /* NULL = log on standard output */
746 server
.bindaddr
= NULL
;
747 server
.glueoutputbuf
= 1;
748 server
.daemonize
= 0;
749 server
.pidfile
= "/var/run/redis.pid";
750 server
.dbfilename
= "dump.rdb";
751 server
.requirepass
= NULL
;
752 server
.shareobjects
= 0;
753 ResetServerSaveParams();
755 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
756 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
757 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
758 /* Replication related */
760 server
.masterhost
= NULL
;
761 server
.masterport
= 6379;
762 server
.master
= NULL
;
763 server
.replstate
= REDIS_REPL_NONE
;
766 static void initServer() {
769 signal(SIGHUP
, SIG_IGN
);
770 signal(SIGPIPE
, SIG_IGN
);
772 server
.clients
= listCreate();
773 server
.slaves
= listCreate();
774 server
.monitors
= listCreate();
775 server
.objfreelist
= listCreate();
776 createSharedObjects();
777 server
.el
= aeCreateEventLoop();
778 server
.dict
= zmalloc(sizeof(dict
*)*server
.dbnum
);
779 server
.sharingpool
= dictCreate(&setDictType
,NULL
);
780 server
.sharingpoolsize
= 1024;
781 if (!server
.dict
|| !server
.clients
|| !server
.slaves
|| !server
.monitors
|| !server
.el
|| !server
.objfreelist
)
782 oom("server initialization"); /* Fatal OOM */
783 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
784 if (server
.fd
== -1) {
785 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
788 for (j
= 0; j
< server
.dbnum
; j
++)
789 server
.dict
[j
] = dictCreate(&hashDictType
,NULL
);
790 server
.cronloops
= 0;
791 server
.bgsaveinprogress
= 0;
792 server
.lastsave
= time(NULL
);
794 server
.usedmemory
= 0;
795 server
.stat_numcommands
= 0;
796 server
.stat_numconnections
= 0;
797 server
.stat_starttime
= time(NULL
);
798 aeCreateTimeEvent(server
.el
, 1000, serverCron
, NULL
, NULL
);
801 /* Empty the whole database */
802 static void emptyDb() {
805 for (j
= 0; j
< server
.dbnum
; j
++)
806 dictEmpty(server
.dict
[j
]);
809 /* I agree, this is a very rudimental way to load a configuration...
810 will improve later if the config gets more complex */
811 static void loadServerConfig(char *filename
) {
812 FILE *fp
= fopen(filename
,"r");
813 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
818 redisLog(REDIS_WARNING
,"Fatal error, can't open config file");
821 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
827 line
= sdstrim(line
," \t\r\n");
829 /* Skip comments and blank lines*/
830 if (line
[0] == '#' || line
[0] == '\0') {
835 /* Split into arguments */
836 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
839 /* Execute config directives */
840 if (!strcmp(argv
[0],"timeout") && argc
== 2) {
841 server
.maxidletime
= atoi(argv
[1]);
842 if (server
.maxidletime
< 1) {
843 err
= "Invalid timeout value"; goto loaderr
;
845 } else if (!strcmp(argv
[0],"port") && argc
== 2) {
846 server
.port
= atoi(argv
[1]);
847 if (server
.port
< 1 || server
.port
> 65535) {
848 err
= "Invalid port"; goto loaderr
;
850 } else if (!strcmp(argv
[0],"bind") && argc
== 2) {
851 server
.bindaddr
= zstrdup(argv
[1]);
852 } else if (!strcmp(argv
[0],"save") && argc
== 3) {
853 int seconds
= atoi(argv
[1]);
854 int changes
= atoi(argv
[2]);
855 if (seconds
< 1 || changes
< 0) {
856 err
= "Invalid save parameters"; goto loaderr
;
858 appendServerSaveParams(seconds
,changes
);
859 } else if (!strcmp(argv
[0],"dir") && argc
== 2) {
860 if (chdir(argv
[1]) == -1) {
861 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
862 argv
[1], strerror(errno
));
865 } else if (!strcmp(argv
[0],"loglevel") && argc
== 2) {
866 if (!strcmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
867 else if (!strcmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
868 else if (!strcmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
870 err
= "Invalid log level. Must be one of debug, notice, warning";
873 } else if (!strcmp(argv
[0],"logfile") && argc
== 2) {
876 server
.logfile
= zstrdup(argv
[1]);
877 if (!strcmp(server
.logfile
,"stdout")) {
878 zfree(server
.logfile
);
879 server
.logfile
= NULL
;
881 if (server
.logfile
) {
882 /* Test if we are able to open the file. The server will not
883 * be able to abort just for this problem later... */
884 fp
= fopen(server
.logfile
,"a");
886 err
= sdscatprintf(sdsempty(),
887 "Can't open the log file: %s", strerror(errno
));
892 } else if (!strcmp(argv
[0],"databases") && argc
== 2) {
893 server
.dbnum
= atoi(argv
[1]);
894 if (server
.dbnum
< 1) {
895 err
= "Invalid number of databases"; goto loaderr
;
897 } else if (!strcmp(argv
[0],"slaveof") && argc
== 3) {
898 server
.masterhost
= sdsnew(argv
[1]);
899 server
.masterport
= atoi(argv
[2]);
900 server
.replstate
= REDIS_REPL_CONNECT
;
901 } else if (!strcmp(argv
[0],"glueoutputbuf") && argc
== 2) {
903 if (!strcmp(argv
[1],"yes")) server
.glueoutputbuf
= 1;
904 else if (!strcmp(argv
[1],"no")) server
.glueoutputbuf
= 0;
906 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
908 } else if (!strcmp(argv
[0],"shareobjects") && argc
== 2) {
910 if (!strcmp(argv
[1],"yes")) server
.shareobjects
= 1;
911 else if (!strcmp(argv
[1],"no")) server
.shareobjects
= 0;
913 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
915 } else if (!strcmp(argv
[0],"daemonize") && argc
== 2) {
917 if (!strcmp(argv
[1],"yes")) server
.daemonize
= 1;
918 else if (!strcmp(argv
[1],"no")) server
.daemonize
= 0;
920 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
922 } else if (!strcmp(argv
[0],"requirepass") && argc
== 2) {
923 server
.requirepass
= zstrdup(argv
[1]);
924 } else if (!strcmp(argv
[0],"pidfile") && argc
== 2) {
925 server
.pidfile
= zstrdup(argv
[1]);
927 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
929 for (j
= 0; j
< argc
; j
++)
938 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
939 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
940 fprintf(stderr
, ">>> '%s'\n", line
);
941 fprintf(stderr
, "%s\n", err
);
945 static void freeClientArgv(redisClient
*c
) {
948 for (j
= 0; j
< c
->argc
; j
++)
949 decrRefCount(c
->argv
[j
]);
953 static void freeClient(redisClient
*c
) {
956 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
957 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
958 sdsfree(c
->querybuf
);
959 listRelease(c
->reply
);
962 ln
= listSearchKey(server
.clients
,c
);
964 listDelNode(server
.clients
,ln
);
965 if (c
->flags
& REDIS_SLAVE
) {
966 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
967 ln
= listSearchKey(l
,c
);
971 if (c
->flags
& REDIS_MASTER
) {
972 server
.master
= NULL
;
973 server
.replstate
= REDIS_REPL_CONNECT
;
978 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
980 listNode
*ln
= c
->reply
->head
, *next
;
985 totlen
+= sdslen(o
->ptr
);
987 /* This optimization makes more sense if we don't have to copy
989 if (totlen
> 1024) return;
999 memcpy(buf
+copylen
,o
->ptr
,sdslen(o
->ptr
));
1000 copylen
+= sdslen(o
->ptr
);
1001 listDelNode(c
->reply
,ln
);
1004 /* Now the output buffer is empty, add the new single element */
1005 addReplySds(c
,sdsnewlen(buf
,totlen
));
1009 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1010 redisClient
*c
= privdata
;
1011 int nwritten
= 0, totwritten
= 0, objlen
;
1014 REDIS_NOTUSED(mask
);
1016 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
1017 glueReplyBuffersIfNeeded(c
);
1018 while(listLength(c
->reply
)) {
1019 o
= listNodeValue(listFirst(c
->reply
));
1020 objlen
= sdslen(o
->ptr
);
1023 listDelNode(c
->reply
,listFirst(c
->reply
));
1027 if (c
->flags
& REDIS_MASTER
) {
1028 nwritten
= objlen
- c
->sentlen
;
1030 nwritten
= write(fd
, o
->ptr
+c
->sentlen
, objlen
- c
->sentlen
);
1031 if (nwritten
<= 0) break;
1033 c
->sentlen
+= nwritten
;
1034 totwritten
+= nwritten
;
1035 /* If we fully sent the object on head go to the next one */
1036 if (c
->sentlen
== objlen
) {
1037 listDelNode(c
->reply
,listFirst(c
->reply
));
1041 if (nwritten
== -1) {
1042 if (errno
== EAGAIN
) {
1045 redisLog(REDIS_DEBUG
,
1046 "Error writing to client: %s", strerror(errno
));
1051 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
1052 if (listLength(c
->reply
) == 0) {
1054 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1058 static struct redisCommand
*lookupCommand(char *name
) {
1060 while(cmdTable
[j
].name
!= NULL
) {
1061 if (!strcmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
1067 /* resetClient prepare the client to process the next command */
1068 static void resetClient(redisClient
*c
) {
1073 /* If this function gets called we already read a whole
1074 * command, argments are in the client argv/argc fields.
1075 * processCommand() execute the command or prepare the
1076 * server for a bulk read from the client.
1078 * If 1 is returned the client is still alive and valid and
1079 * and other operations can be performed by the caller. Otherwise
1080 * if 0 is returned the client was destroied (i.e. after QUIT). */
1081 static int processCommand(redisClient
*c
) {
1082 struct redisCommand
*cmd
;
1085 sdstolower(c
->argv
[0]->ptr
);
1086 /* The QUIT command is handled as a special case. Normal command
1087 * procs are unable to close the client connection safely */
1088 if (!strcmp(c
->argv
[0]->ptr
,"quit")) {
1092 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1094 addReplySds(c
,sdsnew("-ERR unknown command\r\n"));
1097 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
1098 (c
->argc
< -cmd
->arity
)) {
1099 addReplySds(c
,sdsnew("-ERR wrong number of arguments\r\n"));
1102 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
1103 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
1105 decrRefCount(c
->argv
[c
->argc
-1]);
1106 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1108 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1113 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1114 /* It is possible that the bulk read is already in the
1115 * buffer. Check this condition and handle it accordingly */
1116 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
1117 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
1119 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
1124 /* Let's try to share objects on the command arguments vector */
1125 if (server
.shareobjects
) {
1127 for(j
= 1; j
< c
->argc
; j
++)
1128 c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]);
1130 /* Check if the user is authenticated */
1131 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
1132 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
1137 /* Exec the command */
1138 dirty
= server
.dirty
;
1140 if (server
.dirty
-dirty
!= 0 && listLength(server
.slaves
))
1141 replicationFeedSlaves(server
.slaves
,cmd
,c
->dictid
,c
->argv
,c
->argc
);
1142 if (listLength(server
.monitors
))
1143 replicationFeedSlaves(server
.monitors
,cmd
,c
->dictid
,c
->argv
,c
->argc
);
1144 server
.stat_numcommands
++;
1146 /* Prepare the client for the next command */
1147 if (c
->flags
& REDIS_CLOSE
) {
1155 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
1156 listNode
*ln
= slaves
->head
;
1157 robj
*outv
[REDIS_MAX_ARGS
*4]; /* enough room for args, spaces, newlines */
1160 for (j
= 0; j
< argc
; j
++) {
1161 if (j
!= 0) outv
[outc
++] = shared
.space
;
1162 if ((cmd
->flags
& REDIS_CMD_BULK
) && j
== argc
-1) {
1165 lenobj
= createObject(REDIS_STRING
,
1166 sdscatprintf(sdsempty(),"%d\r\n",sdslen(argv
[j
]->ptr
)));
1167 lenobj
->refcount
= 0;
1168 outv
[outc
++] = lenobj
;
1170 outv
[outc
++] = argv
[j
];
1172 outv
[outc
++] = shared
.crlf
;
1175 redisClient
*slave
= ln
->value
;
1176 if (slave
->slaveseldb
!= dictid
) {
1180 case 0: selectcmd
= shared
.select0
; break;
1181 case 1: selectcmd
= shared
.select1
; break;
1182 case 2: selectcmd
= shared
.select2
; break;
1183 case 3: selectcmd
= shared
.select3
; break;
1184 case 4: selectcmd
= shared
.select4
; break;
1185 case 5: selectcmd
= shared
.select5
; break;
1186 case 6: selectcmd
= shared
.select6
; break;
1187 case 7: selectcmd
= shared
.select7
; break;
1188 case 8: selectcmd
= shared
.select8
; break;
1189 case 9: selectcmd
= shared
.select9
; break;
1191 selectcmd
= createObject(REDIS_STRING
,
1192 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
1193 selectcmd
->refcount
= 0;
1196 addReply(slave
,selectcmd
);
1197 slave
->slaveseldb
= dictid
;
1199 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
1204 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1205 redisClient
*c
= (redisClient
*) privdata
;
1206 char buf
[REDIS_QUERYBUF_LEN
];
1209 REDIS_NOTUSED(mask
);
1211 nread
= read(fd
, buf
, REDIS_QUERYBUF_LEN
);
1213 if (errno
== EAGAIN
) {
1216 redisLog(REDIS_DEBUG
, "Reading from client: %s",strerror(errno
));
1220 } else if (nread
== 0) {
1221 redisLog(REDIS_DEBUG
, "Client closed connection");
1226 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
1227 c
->lastinteraction
= time(NULL
);
1233 if (c
->bulklen
== -1) {
1234 /* Read the first line of the query */
1235 char *p
= strchr(c
->querybuf
,'\n');
1241 query
= c
->querybuf
;
1242 c
->querybuf
= sdsempty();
1243 querylen
= 1+(p
-(query
));
1244 if (sdslen(query
) > querylen
) {
1245 /* leave data after the first line of the query in the buffer */
1246 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
1248 *p
= '\0'; /* remove "\n" */
1249 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
1250 sdsupdatelen(query
);
1252 /* Now we can split the query in arguments */
1253 if (sdslen(query
) == 0) {
1254 /* Ignore empty query */
1258 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
1260 if (argv
== NULL
) oom("sdssplitlen");
1261 for (j
= 0; j
< argc
&& j
< REDIS_MAX_ARGS
; j
++) {
1262 if (sdslen(argv
[j
])) {
1263 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
1270 /* Execute the command. If the client is still valid
1271 * after processCommand() return and there is something
1272 * on the query buffer try to process the next command. */
1273 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
1275 } else if (sdslen(c
->querybuf
) >= 1024) {
1276 redisLog(REDIS_DEBUG
, "Client protocol error");
1281 /* Bulk read handling. Note that if we are at this point
1282 the client already sent a command terminated with a newline,
1283 we are reading the bulk data that is actually the last
1284 argument of the command. */
1285 int qbl
= sdslen(c
->querybuf
);
1287 if (c
->bulklen
<= qbl
) {
1288 /* Copy everything but the final CRLF as final argument */
1289 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
1291 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
1298 static int selectDb(redisClient
*c
, int id
) {
1299 if (id
< 0 || id
>= server
.dbnum
)
1301 c
->dict
= server
.dict
[id
];
1306 static redisClient
*createClient(int fd
) {
1307 redisClient
*c
= zmalloc(sizeof(*c
));
1309 anetNonBlock(NULL
,fd
);
1310 anetTcpNoDelay(NULL
,fd
);
1311 if (!c
) return NULL
;
1314 c
->querybuf
= sdsempty();
1319 c
->lastinteraction
= time(NULL
);
1320 c
->authenticated
= 0;
1321 if ((c
->reply
= listCreate()) == NULL
) oom("listCreate");
1322 listSetFreeMethod(c
->reply
,decrRefCount
);
1323 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
1324 readQueryFromClient
, c
, NULL
) == AE_ERR
) {
1328 if (!listAddNodeTail(server
.clients
,c
)) oom("listAddNodeTail");
1332 static void addReply(redisClient
*c
, robj
*obj
) {
1333 if (listLength(c
->reply
) == 0 &&
1334 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
1335 sendReplyToClient
, c
, NULL
) == AE_ERR
) return;
1336 if (!listAddNodeTail(c
->reply
,obj
)) oom("listAddNodeTail");
1340 static void addReplySds(redisClient
*c
, sds s
) {
1341 robj
*o
= createObject(REDIS_STRING
,s
);
1346 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1350 REDIS_NOTUSED(mask
);
1351 REDIS_NOTUSED(privdata
);
1353 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
1354 if (cfd
== AE_ERR
) {
1355 redisLog(REDIS_DEBUG
,"Accepting client connection: %s", server
.neterr
);
1358 redisLog(REDIS_DEBUG
,"Accepted %s:%d", cip
, cport
);
1359 if (createClient(cfd
) == NULL
) {
1360 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
1361 close(cfd
); /* May be already closed, just ingore errors */
1364 server
.stat_numconnections
++;
1367 /* ======================= Redis objects implementation ===================== */
1369 static robj
*createObject(int type
, void *ptr
) {
1372 if (listLength(server
.objfreelist
)) {
1373 listNode
*head
= listFirst(server
.objfreelist
);
1374 o
= listNodeValue(head
);
1375 listDelNode(server
.objfreelist
,head
);
1377 o
= zmalloc(sizeof(*o
));
1379 if (!o
) oom("createObject");
1386 static robj
*createStringObject(char *ptr
, size_t len
) {
1387 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
1390 static robj
*createListObject(void) {
1391 list
*l
= listCreate();
1393 if (!l
) oom("listCreate");
1394 listSetFreeMethod(l
,decrRefCount
);
1395 return createObject(REDIS_LIST
,l
);
1398 static robj
*createSetObject(void) {
1399 dict
*d
= dictCreate(&setDictType
,NULL
);
1400 if (!d
) oom("dictCreate");
1401 return createObject(REDIS_SET
,d
);
1405 static robj
*createHashObject(void) {
1406 dict
*d
= dictCreate(&hashDictType
,NULL
);
1407 if (!d
) oom("dictCreate");
1408 return createObject(REDIS_SET
,d
);
1412 static void freeStringObject(robj
*o
) {
1416 static void freeListObject(robj
*o
) {
1417 listRelease((list
*) o
->ptr
);
1420 static void freeSetObject(robj
*o
) {
1421 dictRelease((dict
*) o
->ptr
);
1424 static void freeHashObject(robj
*o
) {
1425 dictRelease((dict
*) o
->ptr
);
1428 static void incrRefCount(robj
*o
) {
1432 static void decrRefCount(void *obj
) {
1434 if (--(o
->refcount
) == 0) {
1436 case REDIS_STRING
: freeStringObject(o
); break;
1437 case REDIS_LIST
: freeListObject(o
); break;
1438 case REDIS_SET
: freeSetObject(o
); break;
1439 case REDIS_HASH
: freeHashObject(o
); break;
1440 default: assert(0 != 0); break;
1442 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
1443 !listAddNodeHead(server
.objfreelist
,o
))
1448 /* Try to share an object against the shared objects pool */
1449 static robj
*tryObjectSharing(robj
*o
) {
1450 struct dictEntry
*de
;
1453 if (server
.shareobjects
== 0) return o
;
1455 assert(o
->type
== REDIS_STRING
);
1456 de
= dictFind(server
.sharingpool
,o
);
1458 robj
*shared
= dictGetEntryKey(de
);
1460 c
= ((unsigned long) dictGetEntryVal(de
))+1;
1461 dictGetEntryVal(de
) = (void*) c
;
1462 incrRefCount(shared
);
1466 /* Here we are using a stream algorihtm: Every time an object is
1467 * shared we increment its count, everytime there is a miss we
1468 * recrement the counter of a random object. If this object reaches
1469 * zero we remove the object and put the current object instead. */
1470 if (dictGetHashTableUsed(server
.sharingpool
) >=
1471 server
.sharingpoolsize
) {
1472 de
= dictGetRandomKey(server
.sharingpool
);
1474 c
= ((unsigned long) dictGetEntryVal(de
))-1;
1475 dictGetEntryVal(de
) = (void*) c
;
1477 dictDelete(server
.sharingpool
,de
->key
);
1480 c
= 0; /* If the pool is empty we want to add this object */
1485 retval
= dictAdd(server
.sharingpool
,o
,(void*)1);
1486 assert(retval
== DICT_OK
);
1493 /*============================ DB saving/loading ============================ */
1495 static int rdbSaveType(FILE *fp
, unsigned char type
) {
1496 if (fwrite(&type
,1,1,fp
) == 0) return -1;
1500 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
1501 unsigned char buf
[2];
1504 /* Save a 6 bit len */
1505 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
1506 if (fwrite(buf
,1,1,fp
) == 0) return -1;
1507 } else if (len
< (1<<14)) {
1508 /* Save a 14 bit len */
1509 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
1511 if (fwrite(buf
,4,1,fp
) == 0) return -1;
1513 /* Save a 32 bit len */
1514 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
1515 if (fwrite(buf
,1,1,fp
) == 0) return -1;
1517 if (fwrite(&len
,4,1,fp
) == 0) return -1;
1522 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
1523 size_t len
= sdslen(obj
->ptr
);
1525 if (rdbSaveLen(fp
,len
) == -1) return -1;
1526 if (len
&& fwrite(obj
->ptr
,len
,1,fp
) == 0) return -1;
1530 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
1531 static int rdbSave(char *filename
) {
1532 dictIterator
*di
= NULL
;
1538 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
1539 fp
= fopen(tmpfile
,"w");
1541 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
1544 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
1545 for (j
= 0; j
< server
.dbnum
; j
++) {
1546 dict
*d
= server
.dict
[j
];
1547 if (dictGetHashTableUsed(d
) == 0) continue;
1548 di
= dictGetIterator(d
);
1554 /* Write the SELECT DB opcode */
1555 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
1556 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
1558 /* Iterate this DB writing every entry */
1559 while((de
= dictNext(di
)) != NULL
) {
1560 robj
*key
= dictGetEntryKey(de
);
1561 robj
*o
= dictGetEntryVal(de
);
1563 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
1564 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
1565 if (o
->type
== REDIS_STRING
) {
1566 /* Save a string value */
1567 if (rdbSaveStringObject(fp
,o
) == -1) goto werr
;
1568 } else if (o
->type
== REDIS_LIST
) {
1569 /* Save a list value */
1570 list
*list
= o
->ptr
;
1571 listNode
*ln
= list
->head
;
1573 if (rdbSaveLen(fp
,listLength(list
)) == -1) goto werr
;
1575 robj
*eleobj
= listNodeValue(ln
);
1577 if (rdbSaveStringObject(fp
,eleobj
) == -1) goto werr
;
1580 } else if (o
->type
== REDIS_SET
) {
1581 /* Save a set value */
1583 dictIterator
*di
= dictGetIterator(set
);
1586 if (!set
) oom("dictGetIteraotr");
1587 if (rdbSaveLen(fp
,dictGetHashTableUsed(set
)) == -1) goto werr
;
1588 while((de
= dictNext(di
)) != NULL
) {
1589 robj
*eleobj
= dictGetEntryKey(de
);
1591 if (rdbSaveStringObject(fp
,eleobj
) == -1) goto werr
;
1593 dictReleaseIterator(di
);
1598 dictReleaseIterator(di
);
1601 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
1603 /* Make sure data will not remain on the OS's output buffers */
1608 /* Use RENAME to make sure the DB file is changed atomically only
1609 * if the generate DB file is ok. */
1610 if (rename(tmpfile
,filename
) == -1) {
1611 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destionation: %s", strerror(errno
));
1615 redisLog(REDIS_NOTICE
,"DB saved on disk");
1617 server
.lastsave
= time(NULL
);
1623 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
1624 if (di
) dictReleaseIterator(di
);
1628 static int rdbSaveBackground(char *filename
) {
1631 if (server
.bgsaveinprogress
) return REDIS_ERR
;
1632 if ((childpid
= fork()) == 0) {
1635 if (rdbSave(filename
) == REDIS_OK
) {
1642 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
1643 server
.bgsaveinprogress
= 1;
1646 return REDIS_OK
; /* unreached */
1649 static int rdbLoadType(FILE *fp
) {
1651 if (fread(&type
,1,1,fp
) == 0) return -1;
1655 static uint32_t rdbLoadLen(FILE *fp
, int rdbver
) {
1656 unsigned char buf
[2];
1660 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
1663 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
1664 if ((buf
[0]&0xC0) == REDIS_RDB_6BITLEN
) {
1665 /* Read a 6 bit len */
1667 } else if ((buf
[0]&0xC0) == REDIS_RDB_14BITLEN
) {
1668 /* Read a 14 bit len */
1669 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
1670 return ((buf
[0]&0x3F)<<8)|buf
[1];
1672 /* Read a 32 bit len */
1673 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
1679 static robj
*rdbLoadStringObject(FILE*fp
,int rdbver
) {
1680 uint32_t len
= rdbLoadLen(fp
,rdbver
);
1683 if (len
== REDIS_RDB_LENERR
) return NULL
;
1684 val
= sdsnewlen(NULL
,len
);
1685 if (len
&& fread(val
,len
,1,fp
) == 0) {
1689 return tryObjectSharing(createObject(REDIS_STRING
,val
));
1692 static int rdbLoad(char *filename
) {
1694 robj
*keyobj
= NULL
;
1698 dict
*d
= server
.dict
[0];
1701 fp
= fopen(filename
,"r");
1702 if (!fp
) return REDIS_ERR
;
1703 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
1705 if (memcmp(buf
,"REDIS",5) != 0) {
1707 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
1710 rdbver
= atoi(buf
+5);
1713 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
1720 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
1721 if (type
== REDIS_EOF
) break;
1722 /* Handle SELECT DB opcode as a special case */
1723 if (type
== REDIS_SELECTDB
) {
1724 if ((dbid
= rdbLoadLen(fp
,rdbver
)) == REDIS_RDB_LENERR
) goto eoferr
;
1725 if (dbid
>= (unsigned)server
.dbnum
) {
1726 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
1729 d
= server
.dict
[dbid
];
1733 if ((keyobj
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1735 if (type
== REDIS_STRING
) {
1736 /* Read string value */
1737 if ((o
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1738 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
1739 /* Read list/set value */
1742 if ((listlen
= rdbLoadLen(fp
,rdbver
)) == REDIS_RDB_LENERR
)
1744 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
1745 /* Load every single element of the list/set */
1749 if ((ele
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1750 if (type
== REDIS_LIST
) {
1751 if (!listAddNodeTail((list
*)o
->ptr
,ele
))
1752 oom("listAddNodeTail");
1754 if (dictAdd((dict
*)o
->ptr
,ele
,NULL
) == DICT_ERR
)
1761 /* Add the new object in the hash table */
1762 retval
= dictAdd(d
,keyobj
,o
);
1763 if (retval
== DICT_ERR
) {
1764 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
1772 eoferr
: /* unexpected end of file is handled here with a fatal exit */
1773 decrRefCount(keyobj
);
1774 redisLog(REDIS_WARNING
,"Short read loading DB. Unrecoverable error, exiting now.");
1776 return REDIS_ERR
; /* Just to avoid warning */
1779 /*================================== Commands =============================== */
1781 static void authCommand(redisClient
*c
) {
1782 if (!strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1783 c
->authenticated
= 1;
1784 addReply(c
,shared
.ok
);
1786 c
->authenticated
= 0;
1787 addReply(c
,shared
.err
);
1791 static void pingCommand(redisClient
*c
) {
1792 addReply(c
,shared
.pong
);
1795 static void echoCommand(redisClient
*c
) {
1796 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
1797 (int)sdslen(c
->argv
[1]->ptr
)));
1798 addReply(c
,c
->argv
[1]);
1799 addReply(c
,shared
.crlf
);
1802 /*=================================== Strings =============================== */
1804 static void setGenericCommand(redisClient
*c
, int nx
) {
1807 retval
= dictAdd(c
->dict
,c
->argv
[1],c
->argv
[2]);
1808 if (retval
== DICT_ERR
) {
1810 dictReplace(c
->dict
,c
->argv
[1],c
->argv
[2]);
1811 incrRefCount(c
->argv
[2]);
1813 addReply(c
,shared
.czero
);
1817 incrRefCount(c
->argv
[1]);
1818 incrRefCount(c
->argv
[2]);
1821 addReply(c
, nx
? shared
.cone
: shared
.ok
);
1824 static void setCommand(redisClient
*c
) {
1825 return setGenericCommand(c
,0);
1828 static void setnxCommand(redisClient
*c
) {
1829 return setGenericCommand(c
,1);
1832 static void getCommand(redisClient
*c
) {
1835 de
= dictFind(c
->dict
,c
->argv
[1]);
1837 addReply(c
,shared
.nullbulk
);
1839 robj
*o
= dictGetEntryVal(de
);
1841 if (o
->type
!= REDIS_STRING
) {
1842 addReply(c
,shared
.wrongtypeerr
);
1844 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o
->ptr
)));
1846 addReply(c
,shared
.crlf
);
1851 static void mgetCommand(redisClient
*c
) {
1855 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
1856 for (j
= 1; j
< c
->argc
; j
++) {
1857 de
= dictFind(c
->dict
,c
->argv
[j
]);
1859 addReply(c
,shared
.nullbulk
);
1861 robj
*o
= dictGetEntryVal(de
);
1863 if (o
->type
!= REDIS_STRING
) {
1864 addReply(c
,shared
.nullbulk
);
1866 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o
->ptr
)));
1868 addReply(c
,shared
.crlf
);
1874 static void incrDecrCommand(redisClient
*c
, int incr
) {
1880 de
= dictFind(c
->dict
,c
->argv
[1]);
1884 robj
*o
= dictGetEntryVal(de
);
1886 if (o
->type
!= REDIS_STRING
) {
1891 value
= strtoll(o
->ptr
, &eptr
, 10);
1896 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
1897 retval
= dictAdd(c
->dict
,c
->argv
[1],o
);
1898 if (retval
== DICT_ERR
) {
1899 dictReplace(c
->dict
,c
->argv
[1],o
);
1901 incrRefCount(c
->argv
[1]);
1904 addReply(c
,shared
.colon
);
1906 addReply(c
,shared
.crlf
);
1909 static void incrCommand(redisClient
*c
) {
1910 return incrDecrCommand(c
,1);
1913 static void decrCommand(redisClient
*c
) {
1914 return incrDecrCommand(c
,-1);
1917 static void incrbyCommand(redisClient
*c
) {
1918 int incr
= atoi(c
->argv
[2]->ptr
);
1919 return incrDecrCommand(c
,incr
);
1922 static void decrbyCommand(redisClient
*c
) {
1923 int incr
= atoi(c
->argv
[2]->ptr
);
1924 return incrDecrCommand(c
,-incr
);
1927 /* ========================= Type agnostic commands ========================= */
1929 static void delCommand(redisClient
*c
) {
1930 if (dictDelete(c
->dict
,c
->argv
[1]) == DICT_OK
) {
1932 addReply(c
,shared
.cone
);
1934 addReply(c
,shared
.czero
);
1938 static void existsCommand(redisClient
*c
) {
1941 de
= dictFind(c
->dict
,c
->argv
[1]);
1943 addReply(c
,shared
.czero
);
1945 addReply(c
,shared
.cone
);
1948 static void selectCommand(redisClient
*c
) {
1949 int id
= atoi(c
->argv
[1]->ptr
);
1951 if (selectDb(c
,id
) == REDIS_ERR
) {
1952 addReplySds(c
,"-ERR invalid DB index\r\n");
1954 addReply(c
,shared
.ok
);
1958 static void randomkeyCommand(redisClient
*c
) {
1961 de
= dictGetRandomKey(c
->dict
);
1963 addReply(c
,shared
.crlf
);
1965 addReply(c
,shared
.plus
);
1966 addReply(c
,dictGetEntryKey(de
));
1967 addReply(c
,shared
.crlf
);
1971 static void keysCommand(redisClient
*c
) {
1974 sds pattern
= c
->argv
[1]->ptr
;
1975 int plen
= sdslen(pattern
);
1976 int numkeys
= 0, keyslen
= 0;
1977 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
1979 di
= dictGetIterator(c
->dict
);
1980 if (!di
) oom("dictGetIterator");
1982 decrRefCount(lenobj
);
1983 while((de
= dictNext(di
)) != NULL
) {
1984 robj
*keyobj
= dictGetEntryKey(de
);
1985 sds key
= keyobj
->ptr
;
1986 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
1987 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
1989 addReply(c
,shared
.space
);
1992 keyslen
+= sdslen(key
);
1995 dictReleaseIterator(di
);
1996 lenobj
->ptr
= sdscatprintf(sdsempty(),"$%lu\r\n",keyslen
+(numkeys
? (numkeys
-1) : 0));
1997 addReply(c
,shared
.crlf
);
2000 static void dbsizeCommand(redisClient
*c
) {
2002 sdscatprintf(sdsempty(),":%lu\r\n",dictGetHashTableUsed(c
->dict
)));
2005 static void lastsaveCommand(redisClient
*c
) {
2007 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
2010 static void typeCommand(redisClient
*c
) {
2014 de
= dictFind(c
->dict
,c
->argv
[1]);
2018 robj
*o
= dictGetEntryVal(de
);
2021 case REDIS_STRING
: type
= "+string"; break;
2022 case REDIS_LIST
: type
= "+list"; break;
2023 case REDIS_SET
: type
= "+set"; break;
2024 default: type
= "unknown"; break;
2027 addReplySds(c
,sdsnew(type
));
2028 addReply(c
,shared
.crlf
);
2031 static void saveCommand(redisClient
*c
) {
2032 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
2033 addReply(c
,shared
.ok
);
2035 addReply(c
,shared
.err
);
2039 static void bgsaveCommand(redisClient
*c
) {
2040 if (server
.bgsaveinprogress
) {
2041 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
2044 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
2045 addReply(c
,shared
.ok
);
2047 addReply(c
,shared
.err
);
2051 static void shutdownCommand(redisClient
*c
) {
2052 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
2053 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
2054 if (server
.daemonize
) {
2055 unlink(server
.pidfile
);
2057 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
2060 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
2061 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
2065 static void renameGenericCommand(redisClient
*c
, int nx
) {
2069 /* To use the same key as src and dst is probably an error */
2070 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
2071 addReply(c
,shared
.sameobjecterr
);
2075 de
= dictFind(c
->dict
,c
->argv
[1]);
2077 addReply(c
,shared
.nokeyerr
);
2080 o
= dictGetEntryVal(de
);
2082 if (dictAdd(c
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
2085 addReply(c
,shared
.czero
);
2088 dictReplace(c
->dict
,c
->argv
[2],o
);
2090 incrRefCount(c
->argv
[2]);
2092 dictDelete(c
->dict
,c
->argv
[1]);
2094 addReply(c
,nx
? shared
.cone
: shared
.ok
);
2097 static void renameCommand(redisClient
*c
) {
2098 renameGenericCommand(c
,0);
2101 static void renamenxCommand(redisClient
*c
) {
2102 renameGenericCommand(c
,1);
2105 static void moveCommand(redisClient
*c
) {
2111 /* Obtain source and target DB pointers */
2114 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
2115 addReply(c
,shared
.outofrangeerr
);
2122 /* If the user is moving using as target the same
2123 * DB as the source DB it is probably an error. */
2125 addReply(c
,shared
.sameobjecterr
);
2129 /* Check if the element exists and get a reference */
2130 de
= dictFind(c
->dict
,c
->argv
[1]);
2132 addReply(c
,shared
.czero
);
2136 /* Try to add the element to the target DB */
2137 key
= dictGetEntryKey(de
);
2138 o
= dictGetEntryVal(de
);
2139 if (dictAdd(dst
,key
,o
) == DICT_ERR
) {
2140 addReply(c
,shared
.czero
);
2146 /* OK! key moved, free the entry in the source DB */
2147 dictDelete(src
,c
->argv
[1]);
2149 addReply(c
,shared
.cone
);
2152 /* =================================== Lists ================================ */
2153 static void pushGenericCommand(redisClient
*c
, int where
) {
2158 de
= dictFind(c
->dict
,c
->argv
[1]);
2160 lobj
= createListObject();
2162 if (where
== REDIS_HEAD
) {
2163 if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead");
2165 if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail");
2167 dictAdd(c
->dict
,c
->argv
[1],lobj
);
2168 incrRefCount(c
->argv
[1]);
2169 incrRefCount(c
->argv
[2]);
2171 lobj
= dictGetEntryVal(de
);
2172 if (lobj
->type
!= REDIS_LIST
) {
2173 addReply(c
,shared
.wrongtypeerr
);
2177 if (where
== REDIS_HEAD
) {
2178 if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead");
2180 if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail");
2182 incrRefCount(c
->argv
[2]);
2185 addReply(c
,shared
.ok
);
2188 static void lpushCommand(redisClient
*c
) {
2189 pushGenericCommand(c
,REDIS_HEAD
);
2192 static void rpushCommand(redisClient
*c
) {
2193 pushGenericCommand(c
,REDIS_TAIL
);
2196 static void llenCommand(redisClient
*c
) {
2200 de
= dictFind(c
->dict
,c
->argv
[1]);
2202 addReply(c
,shared
.czero
);
2205 robj
*o
= dictGetEntryVal(de
);
2206 if (o
->type
!= REDIS_LIST
) {
2207 addReply(c
,shared
.wrongtypeerr
);
2210 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
)));
2215 static void lindexCommand(redisClient
*c
) {
2217 int index
= atoi(c
->argv
[2]->ptr
);
2219 de
= dictFind(c
->dict
,c
->argv
[1]);
2221 addReply(c
,shared
.nullbulk
);
2223 robj
*o
= dictGetEntryVal(de
);
2225 if (o
->type
!= REDIS_LIST
) {
2226 addReply(c
,shared
.wrongtypeerr
);
2228 list
*list
= o
->ptr
;
2231 ln
= listIndex(list
, index
);
2233 addReply(c
,shared
.nullbulk
);
2235 robj
*ele
= listNodeValue(ln
);
2236 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2238 addReply(c
,shared
.crlf
);
2244 static void lsetCommand(redisClient
*c
) {
2246 int index
= atoi(c
->argv
[2]->ptr
);
2248 de
= dictFind(c
->dict
,c
->argv
[1]);
2250 addReply(c
,shared
.nokeyerr
);
2252 robj
*o
= dictGetEntryVal(de
);
2254 if (o
->type
!= REDIS_LIST
) {
2255 addReply(c
,shared
.wrongtypeerr
);
2257 list
*list
= o
->ptr
;
2260 ln
= listIndex(list
, index
);
2262 addReply(c
,shared
.outofrangeerr
);
2264 robj
*ele
= listNodeValue(ln
);
2267 listNodeValue(ln
) = c
->argv
[3];
2268 incrRefCount(c
->argv
[3]);
2269 addReply(c
,shared
.ok
);
2276 static void popGenericCommand(redisClient
*c
, int where
) {
2279 de
= dictFind(c
->dict
,c
->argv
[1]);
2281 addReply(c
,shared
.nullbulk
);
2283 robj
*o
= dictGetEntryVal(de
);
2285 if (o
->type
!= REDIS_LIST
) {
2286 addReply(c
,shared
.wrongtypeerr
);
2288 list
*list
= o
->ptr
;
2291 if (where
== REDIS_HEAD
)
2292 ln
= listFirst(list
);
2294 ln
= listLast(list
);
2297 addReply(c
,shared
.nullbulk
);
2299 robj
*ele
= listNodeValue(ln
);
2300 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2302 addReply(c
,shared
.crlf
);
2303 listDelNode(list
,ln
);
2310 static void lpopCommand(redisClient
*c
) {
2311 popGenericCommand(c
,REDIS_HEAD
);
2314 static void rpopCommand(redisClient
*c
) {
2315 popGenericCommand(c
,REDIS_TAIL
);
2318 static void lrangeCommand(redisClient
*c
) {
2320 int start
= atoi(c
->argv
[2]->ptr
);
2321 int end
= atoi(c
->argv
[3]->ptr
);
2323 de
= dictFind(c
->dict
,c
->argv
[1]);
2325 addReply(c
,shared
.nullmultibulk
);
2327 robj
*o
= dictGetEntryVal(de
);
2329 if (o
->type
!= REDIS_LIST
) {
2330 addReply(c
,shared
.wrongtypeerr
);
2332 list
*list
= o
->ptr
;
2334 int llen
= listLength(list
);
2338 /* convert negative indexes */
2339 if (start
< 0) start
= llen
+start
;
2340 if (end
< 0) end
= llen
+end
;
2341 if (start
< 0) start
= 0;
2342 if (end
< 0) end
= 0;
2344 /* indexes sanity checks */
2345 if (start
> end
|| start
>= llen
) {
2346 /* Out of range start or start > end result in empty list */
2347 addReply(c
,shared
.emptymultibulk
);
2350 if (end
>= llen
) end
= llen
-1;
2351 rangelen
= (end
-start
)+1;
2353 /* Return the result in form of a multi-bulk reply */
2354 ln
= listIndex(list
, start
);
2355 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
2356 for (j
= 0; j
< rangelen
; j
++) {
2357 ele
= listNodeValue(ln
);
2358 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2360 addReply(c
,shared
.crlf
);
2367 static void ltrimCommand(redisClient
*c
) {
2369 int start
= atoi(c
->argv
[2]->ptr
);
2370 int end
= atoi(c
->argv
[3]->ptr
);
2372 de
= dictFind(c
->dict
,c
->argv
[1]);
2374 addReply(c
,shared
.nokeyerr
);
2376 robj
*o
= dictGetEntryVal(de
);
2378 if (o
->type
!= REDIS_LIST
) {
2379 addReply(c
,shared
.wrongtypeerr
);
2381 list
*list
= o
->ptr
;
2383 int llen
= listLength(list
);
2384 int j
, ltrim
, rtrim
;
2386 /* convert negative indexes */
2387 if (start
< 0) start
= llen
+start
;
2388 if (end
< 0) end
= llen
+end
;
2389 if (start
< 0) start
= 0;
2390 if (end
< 0) end
= 0;
2392 /* indexes sanity checks */
2393 if (start
> end
|| start
>= llen
) {
2394 /* Out of range start or start > end result in empty list */
2398 if (end
>= llen
) end
= llen
-1;
2403 /* Remove list elements to perform the trim */
2404 for (j
= 0; j
< ltrim
; j
++) {
2405 ln
= listFirst(list
);
2406 listDelNode(list
,ln
);
2408 for (j
= 0; j
< rtrim
; j
++) {
2409 ln
= listLast(list
);
2410 listDelNode(list
,ln
);
2412 addReply(c
,shared
.ok
);
2418 static void lremCommand(redisClient
*c
) {
2421 de
= dictFind(c
->dict
,c
->argv
[1]);
2423 addReply(c
,shared
.nokeyerr
);
2425 robj
*o
= dictGetEntryVal(de
);
2427 if (o
->type
!= REDIS_LIST
) {
2428 addReply(c
,shared
.wrongtypeerr
);
2430 list
*list
= o
->ptr
;
2431 listNode
*ln
, *next
;
2432 int toremove
= atoi(c
->argv
[2]->ptr
);
2437 toremove
= -toremove
;
2440 ln
= fromtail
? list
->tail
: list
->head
;
2442 next
= fromtail
? ln
->prev
: ln
->next
;
2443 robj
*ele
= listNodeValue(ln
);
2444 if (sdscmp(ele
->ptr
,c
->argv
[3]->ptr
) == 0) {
2445 listDelNode(list
,ln
);
2448 if (toremove
&& removed
== toremove
) break;
2452 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
2457 /* ==================================== Sets ================================ */
2459 static void saddCommand(redisClient
*c
) {
2463 de
= dictFind(c
->dict
,c
->argv
[1]);
2465 set
= createSetObject();
2466 dictAdd(c
->dict
,c
->argv
[1],set
);
2467 incrRefCount(c
->argv
[1]);
2469 set
= dictGetEntryVal(de
);
2470 if (set
->type
!= REDIS_SET
) {
2471 addReply(c
,shared
.wrongtypeerr
);
2475 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
2476 incrRefCount(c
->argv
[2]);
2478 addReply(c
,shared
.cone
);
2480 addReply(c
,shared
.czero
);
2484 static void sremCommand(redisClient
*c
) {
2487 de
= dictFind(c
->dict
,c
->argv
[1]);
2489 addReply(c
,shared
.czero
);
2493 set
= dictGetEntryVal(de
);
2494 if (set
->type
!= REDIS_SET
) {
2495 addReply(c
,shared
.wrongtypeerr
);
2498 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
2500 addReply(c
,shared
.cone
);
2502 addReply(c
,shared
.czero
);
2507 static void sismemberCommand(redisClient
*c
) {
2510 de
= dictFind(c
->dict
,c
->argv
[1]);
2512 addReply(c
,shared
.czero
);
2516 set
= dictGetEntryVal(de
);
2517 if (set
->type
!= REDIS_SET
) {
2518 addReply(c
,shared
.wrongtypeerr
);
2521 if (dictFind(set
->ptr
,c
->argv
[2]))
2522 addReply(c
,shared
.cone
);
2524 addReply(c
,shared
.czero
);
2528 static void scardCommand(redisClient
*c
) {
2532 de
= dictFind(c
->dict
,c
->argv
[1]);
2534 addReply(c
,shared
.czero
);
2537 robj
*o
= dictGetEntryVal(de
);
2538 if (o
->type
!= REDIS_SET
) {
2539 addReply(c
,shared
.wrongtypeerr
);
2542 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",
2543 dictGetHashTableUsed(s
)));
2548 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
2549 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
2551 return dictGetHashTableUsed(*d1
)-dictGetHashTableUsed(*d2
);
2554 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
) {
2555 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
2558 robj
*lenobj
= NULL
, *dstset
= NULL
;
2559 int j
, cardinality
= 0;
2561 if (!dv
) oom("sinterCommand");
2562 for (j
= 0; j
< setsnum
; j
++) {
2566 de
= dictFind(c
->dict
,setskeys
[j
]);
2569 addReply(c
,shared
.nokeyerr
);
2572 setobj
= dictGetEntryVal(de
);
2573 if (setobj
->type
!= REDIS_SET
) {
2575 addReply(c
,shared
.wrongtypeerr
);
2578 dv
[j
] = setobj
->ptr
;
2580 /* Sort sets from the smallest to largest, this will improve our
2581 * algorithm's performace */
2582 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
2584 /* The first thing we should output is the total number of elements...
2585 * since this is a multi-bulk write, but at this stage we don't know
2586 * the intersection set size, so we use a trick, append an empty object
2587 * to the output list and save the pointer to later modify it with the
2590 lenobj
= createObject(REDIS_STRING
,NULL
);
2592 decrRefCount(lenobj
);
2594 /* If we have a target key where to store the resulting set
2595 * create this key with an empty set inside */
2596 dstset
= createSetObject();
2597 dictDelete(c
->dict
,dstkey
);
2598 dictAdd(c
->dict
,dstkey
,dstset
);
2599 incrRefCount(dstkey
);
2602 /* Iterate all the elements of the first (smallest) set, and test
2603 * the element against all the other sets, if at least one set does
2604 * not include the element it is discarded */
2605 di
= dictGetIterator(dv
[0]);
2606 if (!di
) oom("dictGetIterator");
2608 while((de
= dictNext(di
)) != NULL
) {
2611 for (j
= 1; j
< setsnum
; j
++)
2612 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
2614 continue; /* at least one set does not contain the member */
2615 ele
= dictGetEntryKey(de
);
2617 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(ele
->ptr
)));
2619 addReply(c
,shared
.crlf
);
2622 dictAdd(dstset
->ptr
,ele
,NULL
);
2626 dictReleaseIterator(di
);
2629 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",cardinality
);
2631 addReply(c
,shared
.ok
);
2635 static void sinterCommand(redisClient
*c
) {
2636 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
2639 static void sinterstoreCommand(redisClient
*c
) {
2640 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
2643 static void flushdbCommand(redisClient
*c
) {
2645 addReply(c
,shared
.ok
);
2646 rdbSave(server
.dbfilename
);
2649 static void flushallCommand(redisClient
*c
) {
2651 addReply(c
,shared
.ok
);
2652 rdbSave(server
.dbfilename
);
2655 redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
2656 redisSortOperation
*so
= zmalloc(sizeof(*so
));
2657 if (!so
) oom("createSortOperation");
2659 so
->pattern
= pattern
;
2663 /* Return the value associated to the key with a name obtained
2664 * substituting the first occurence of '*' in 'pattern' with 'subst' */
2665 robj
*lookupKeyByPattern(dict
*dict
, robj
*pattern
, robj
*subst
) {
2669 int prefixlen
, sublen
, postfixlen
;
2671 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
2675 char buf
[REDIS_SORTKEY_MAX
+1];
2679 spat
= pattern
->ptr
;
2681 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
2682 p
= strchr(spat
,'*');
2683 if (!p
) return NULL
;
2686 sublen
= sdslen(ssub
);
2687 postfixlen
= sdslen(spat
)-(prefixlen
+1);
2688 memcpy(keyname
.buf
,spat
,prefixlen
);
2689 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
2690 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
2691 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
2692 keyname
.len
= prefixlen
+sublen
+postfixlen
;
2694 keyobj
.refcount
= 1;
2695 keyobj
.type
= REDIS_STRING
;
2696 keyobj
.ptr
= ((char*)&keyname
)+(sizeof(long)*2);
2698 de
= dictFind(dict
,&keyobj
);
2699 // printf("lookup '%s' => %p\n", keyname.buf,de);
2700 if (!de
) return NULL
;
2701 return dictGetEntryVal(de
);
2704 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
2705 * the additional parameter is not standard but a BSD-specific we have to
2706 * pass sorting parameters via the global 'server' structure */
2707 static int sortCompare(const void *s1
, const void *s2
) {
2708 const redisSortObject
*so1
= s1
, *so2
= s2
;
2711 if (!server
.sort_alpha
) {
2712 /* Numeric sorting. Here it's trivial as we precomputed scores */
2713 if (so1
->u
.score
> so2
->u
.score
) {
2715 } else if (so1
->u
.score
< so2
->u
.score
) {
2721 /* Alphanumeric sorting */
2722 if (server
.sort_bypattern
) {
2723 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
2724 /* At least one compare object is NULL */
2725 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
2727 else if (so1
->u
.cmpobj
== NULL
)
2732 /* We have both the objects, use strcoll */
2733 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
2736 /* Compare elements directly */
2737 cmp
= strcoll(so1
->obj
->ptr
,so2
->obj
->ptr
);
2740 return server
.sort_desc
? -cmp
: cmp
;
2743 /* The SORT command is the most complex command in Redis. Warning: this code
2744 * is optimized for speed and a bit less for readability */
2745 static void sortCommand(redisClient
*c
) {
2749 int desc
= 0, alpha
= 0;
2750 int limit_start
= 0, limit_count
= -1, start
, end
;
2751 int j
, dontsort
= 0, vectorlen
;
2752 int getop
= 0; /* GET operation counter */
2753 robj
*sortval
, *sortby
= NULL
;
2754 redisSortObject
*vector
; /* Resulting vector to sort */
2756 /* Lookup the key to sort. It must be of the right types */
2757 de
= dictFind(c
->dict
,c
->argv
[1]);
2759 addReply(c
,shared
.nokeyerr
);
2762 sortval
= dictGetEntryVal(de
);
2763 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
) {
2764 addReply(c
,shared
.wrongtypeerr
);
2768 /* Create a list of operations to perform for every sorted element.
2769 * Operations can be GET/DEL/INCR/DECR */
2770 operations
= listCreate();
2771 listSetFreeMethod(operations
,zfree
);
2774 /* Now we need to protect sortval incrementing its count, in the future
2775 * SORT may have options able to overwrite/delete keys during the sorting
2776 * and the sorted key itself may get destroied */
2777 incrRefCount(sortval
);
2779 /* The SORT command has an SQL-alike syntax, parse it */
2780 while(j
< c
->argc
) {
2781 int leftargs
= c
->argc
-j
-1;
2782 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
2784 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
2786 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
2788 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
2789 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
2790 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
2792 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
2793 sortby
= c
->argv
[j
+1];
2794 /* If the BY pattern does not contain '*', i.e. it is constant,
2795 * we don't need to sort nor to lookup the weight keys. */
2796 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
2798 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
2799 listAddNodeTail(operations
,createSortOperation(
2800 REDIS_SORT_GET
,c
->argv
[j
+1]));
2803 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"del") && leftargs
>= 1) {
2804 listAddNodeTail(operations
,createSortOperation(
2805 REDIS_SORT_DEL
,c
->argv
[j
+1]));
2807 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"incr") && leftargs
>= 1) {
2808 listAddNodeTail(operations
,createSortOperation(
2809 REDIS_SORT_INCR
,c
->argv
[j
+1]));
2811 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
2812 listAddNodeTail(operations
,createSortOperation(
2813 REDIS_SORT_DECR
,c
->argv
[j
+1]));
2816 decrRefCount(sortval
);
2817 listRelease(operations
);
2818 addReply(c
,shared
.syntaxerr
);
2824 /* Load the sorting vector with all the objects to sort */
2825 vectorlen
= (sortval
->type
== REDIS_LIST
) ?
2826 listLength((list
*)sortval
->ptr
) :
2827 dictGetHashTableUsed((dict
*)sortval
->ptr
);
2828 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
2829 if (!vector
) oom("allocating objects vector for SORT");
2831 if (sortval
->type
== REDIS_LIST
) {
2832 list
*list
= sortval
->ptr
;
2833 listNode
*ln
= list
->head
;
2835 robj
*ele
= ln
->value
;
2836 vector
[j
].obj
= ele
;
2837 vector
[j
].u
.score
= 0;
2838 vector
[j
].u
.cmpobj
= NULL
;
2843 dict
*set
= sortval
->ptr
;
2847 di
= dictGetIterator(set
);
2848 if (!di
) oom("dictGetIterator");
2849 while((setele
= dictNext(di
)) != NULL
) {
2850 vector
[j
].obj
= dictGetEntryKey(setele
);
2851 vector
[j
].u
.score
= 0;
2852 vector
[j
].u
.cmpobj
= NULL
;
2855 dictReleaseIterator(di
);
2857 assert(j
== vectorlen
);
2859 /* Now it's time to load the right scores in the sorting vector */
2860 if (dontsort
== 0) {
2861 for (j
= 0; j
< vectorlen
; j
++) {
2865 byval
= lookupKeyByPattern(c
->dict
,sortby
,vector
[j
].obj
);
2866 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
2868 vector
[j
].u
.cmpobj
= byval
;
2869 incrRefCount(byval
);
2871 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
2874 if (!alpha
) vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
2879 /* We are ready to sort the vector... perform a bit of sanity check
2880 * on the LIMIT option too. We'll use a partial version of quicksort. */
2881 start
= (limit_start
< 0) ? 0 : limit_start
;
2882 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
2883 if (start
>= vectorlen
) {
2884 start
= vectorlen
-1;
2887 if (end
>= vectorlen
) end
= vectorlen
-1;
2889 if (dontsort
== 0) {
2890 server
.sort_desc
= desc
;
2891 server
.sort_alpha
= alpha
;
2892 server
.sort_bypattern
= sortby
? 1 : 0;
2893 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
2896 /* Send command output to the output buffer, performing the specified
2897 * GET/DEL/INCR/DECR operations if any. */
2898 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
2899 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
2900 for (j
= start
; j
<= end
; j
++) {
2901 listNode
*ln
= operations
->head
;
2903 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
2904 sdslen(vector
[j
].obj
->ptr
)));
2905 addReply(c
,vector
[j
].obj
);
2906 addReply(c
,shared
.crlf
);
2909 redisSortOperation
*sop
= ln
->value
;
2910 robj
*val
= lookupKeyByPattern(c
->dict
,sop
->pattern
,
2913 if (sop
->type
== REDIS_SORT_GET
) {
2914 if (!val
|| val
->type
!= REDIS_STRING
) {
2915 addReply(c
,shared
.nullbulk
);
2917 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
2920 addReply(c
,shared
.crlf
);
2922 } else if (sop
->type
== REDIS_SORT_DEL
) {
2930 decrRefCount(sortval
);
2931 listRelease(operations
);
2932 for (j
= 0; j
< vectorlen
; j
++) {
2933 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
2934 decrRefCount(vector
[j
].u
.cmpobj
);
2939 static void infoCommand(redisClient
*c
) {
2941 time_t uptime
= time(NULL
)-server
.stat_starttime
;
2943 info
= sdscatprintf(sdsempty(),
2944 "redis_version:%s\r\n"
2945 "connected_clients:%d\r\n"
2946 "connected_slaves:%d\r\n"
2947 "used_memory:%d\r\n"
2948 "changes_since_last_save:%lld\r\n"
2949 "last_save_time:%d\r\n"
2950 "total_connections_received:%lld\r\n"
2951 "total_commands_processed:%lld\r\n"
2952 "uptime_in_seconds:%d\r\n"
2953 "uptime_in_days:%d\r\n"
2955 listLength(server
.clients
)-listLength(server
.slaves
),
2956 listLength(server
.slaves
),
2960 server
.stat_numconnections
,
2961 server
.stat_numcommands
,
2965 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(info
)));
2966 addReplySds(c
,info
);
2967 addReply(c
,shared
.crlf
);
2970 /* =============================== Replication ============================= */
2972 /* Send the whole output buffer syncronously to the slave. This a general operation in theory, but it is actually useful only for replication. */
2973 static int flushClientOutput(redisClient
*c
) {
2975 time_t start
= time(NULL
);
2977 while(listLength(c
->reply
)) {
2978 if (time(NULL
)-start
> 5) return REDIS_ERR
; /* 5 seconds timeout */
2979 retval
= aeWait(c
->fd
,AE_WRITABLE
,1000);
2982 } else if (retval
& AE_WRITABLE
) {
2983 sendReplyToClient(NULL
, c
->fd
, c
, AE_WRITABLE
);
2989 static int syncWrite(int fd
, void *ptr
, ssize_t size
, int timeout
) {
2990 ssize_t nwritten
, ret
= size
;
2991 time_t start
= time(NULL
);
2995 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
2996 nwritten
= write(fd
,ptr
,size
);
2997 if (nwritten
== -1) return -1;
3001 if ((time(NULL
)-start
) > timeout
) {
3009 static int syncRead(int fd
, void *ptr
, ssize_t size
, int timeout
) {
3010 ssize_t nread
, totread
= 0;
3011 time_t start
= time(NULL
);
3015 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
3016 nread
= read(fd
,ptr
,size
);
3017 if (nread
== -1) return -1;
3022 if ((time(NULL
)-start
) > timeout
) {
3030 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
3037 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
3040 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
3051 static void syncCommand(redisClient
*c
) {
3054 time_t start
= time(NULL
);
3057 /* ignore SYNC if aleady slave or in monitor mode */
3058 if (c
->flags
& REDIS_SLAVE
) return;
3060 redisLog(REDIS_NOTICE
,"Slave ask for syncronization");
3061 if (flushClientOutput(c
) == REDIS_ERR
||
3062 rdbSave(server
.dbfilename
) != REDIS_OK
)
3065 fd
= open(server
.dbfilename
, O_RDONLY
);
3066 if (fd
== -1 || fstat(fd
,&sb
) == -1) goto closeconn
;
3069 snprintf(sizebuf
,32,"$%d\r\n",len
);
3070 if (syncWrite(c
->fd
,sizebuf
,strlen(sizebuf
),5) == -1) goto closeconn
;
3075 if (time(NULL
)-start
> REDIS_MAX_SYNC_TIME
) goto closeconn
;
3076 nread
= read(fd
,buf
,1024);
3077 if (nread
== -1) goto closeconn
;
3079 if (syncWrite(c
->fd
,buf
,nread
,5) == -1) goto closeconn
;
3081 if (syncWrite(c
->fd
,"\r\n",2,5) == -1) goto closeconn
;
3083 c
->flags
|= REDIS_SLAVE
;
3085 if (!listAddNodeTail(server
.slaves
,c
)) oom("listAddNodeTail");
3086 redisLog(REDIS_NOTICE
,"Syncronization with slave succeeded");
3090 if (fd
!= -1) close(fd
);
3091 c
->flags
|= REDIS_CLOSE
;
3092 redisLog(REDIS_WARNING
,"Syncronization with slave failed");
3096 static int syncWithMaster(void) {
3097 char buf
[1024], tmpfile
[256];
3099 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
3103 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
3107 /* Issue the SYNC command */
3108 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
3110 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
3114 /* Read the bulk write count */
3115 if (syncReadLine(fd
,buf
,1024,5) == -1) {
3117 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
3121 dumpsize
= atoi(buf
+1);
3122 redisLog(REDIS_NOTICE
,"Receiving %d bytes data dump from MASTER",dumpsize
);
3123 /* Read the bulk write data on a temp file */
3124 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
3125 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644);
3128 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
3132 int nread
, nwritten
;
3134 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
3136 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
3142 nwritten
= write(dfd
,buf
,nread
);
3143 if (nwritten
== -1) {
3144 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
3152 if (rename(tmpfile
,server
.dbfilename
) == -1) {
3153 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
3159 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
3160 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
3164 server
.master
= createClient(fd
);
3165 server
.master
->flags
|= REDIS_MASTER
;
3166 server
.replstate
= REDIS_REPL_CONNECTED
;
3170 static void monitorCommand(redisClient
*c
) {
3171 /* ignore MONITOR if aleady slave or in monitor mode */
3172 if (c
->flags
& REDIS_SLAVE
) return;
3174 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
3176 if (!listAddNodeTail(server
.monitors
,c
)) oom("listAddNodeTail");
3177 addReply(c
,shared
.ok
);
3180 /* =================================== Main! ================================ */
3182 static void daemonize(void) {
3186 if (fork() != 0) exit(0); /* parent exits */
3187 setsid(); /* create a new session */
3189 /* Every output goes to /dev/null. If Redis is daemonized but
3190 * the 'logfile' is set to 'stdout' in the configuration file
3191 * it will not log at all. */
3192 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
3193 dup2(fd
, STDIN_FILENO
);
3194 dup2(fd
, STDOUT_FILENO
);
3195 dup2(fd
, STDERR_FILENO
);
3196 if (fd
> STDERR_FILENO
) close(fd
);
3198 /* Try to write the pid file */
3199 fp
= fopen(server
.pidfile
,"w");
3201 fprintf(fp
,"%d\n",getpid());
3206 int main(int argc
, char **argv
) {
3209 ResetServerSaveParams();
3210 loadServerConfig(argv
[1]);
3211 } else if (argc
> 2) {
3212 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
3216 if (server
.daemonize
) daemonize();
3217 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
3218 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
3219 redisLog(REDIS_NOTICE
,"DB loaded from disk");
3220 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
3221 acceptHandler
, NULL
, NULL
) == AE_ERR
) oom("creating file event");
3222 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
3224 aeDeleteEventLoop(server
.el
);