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 (server
.requirepass
&& !c
->authenticated
&& strcmp(c
->argv
[0]->ptr
,"auth")) {
1103 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
1106 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
1107 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
1109 decrRefCount(c
->argv
[c
->argc
-1]);
1110 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1112 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1117 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1118 /* It is possible that the bulk read is already in the
1119 * buffer. Check this condition and handle it accordingly */
1120 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
1121 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
1123 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
1128 /* Let's try to share objects on the command arguments vector */
1129 if (server
.shareobjects
) {
1131 for(j
= 1; j
< c
->argc
; j
++)
1132 c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]);
1134 /* Exec the command */
1135 dirty
= server
.dirty
;
1137 if (server
.dirty
-dirty
!= 0 && listLength(server
.slaves
))
1138 replicationFeedSlaves(server
.slaves
,cmd
,c
->dictid
,c
->argv
,c
->argc
);
1139 if (listLength(server
.monitors
))
1140 replicationFeedSlaves(server
.monitors
,cmd
,c
->dictid
,c
->argv
,c
->argc
);
1141 server
.stat_numcommands
++;
1143 /* Prepare the client for the next command */
1144 if (c
->flags
& REDIS_CLOSE
) {
1152 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
1153 listNode
*ln
= slaves
->head
;
1154 robj
*outv
[REDIS_MAX_ARGS
*4]; /* enough room for args, spaces, newlines */
1157 for (j
= 0; j
< argc
; j
++) {
1158 if (j
!= 0) outv
[outc
++] = shared
.space
;
1159 if ((cmd
->flags
& REDIS_CMD_BULK
) && j
== argc
-1) {
1162 lenobj
= createObject(REDIS_STRING
,
1163 sdscatprintf(sdsempty(),"%d\r\n",sdslen(argv
[j
]->ptr
)));
1164 lenobj
->refcount
= 0;
1165 outv
[outc
++] = lenobj
;
1167 outv
[outc
++] = argv
[j
];
1169 outv
[outc
++] = shared
.crlf
;
1172 redisClient
*slave
= ln
->value
;
1173 if (slave
->slaveseldb
!= dictid
) {
1177 case 0: selectcmd
= shared
.select0
; break;
1178 case 1: selectcmd
= shared
.select1
; break;
1179 case 2: selectcmd
= shared
.select2
; break;
1180 case 3: selectcmd
= shared
.select3
; break;
1181 case 4: selectcmd
= shared
.select4
; break;
1182 case 5: selectcmd
= shared
.select5
; break;
1183 case 6: selectcmd
= shared
.select6
; break;
1184 case 7: selectcmd
= shared
.select7
; break;
1185 case 8: selectcmd
= shared
.select8
; break;
1186 case 9: selectcmd
= shared
.select9
; break;
1188 selectcmd
= createObject(REDIS_STRING
,
1189 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
1190 selectcmd
->refcount
= 0;
1193 addReply(slave
,selectcmd
);
1194 slave
->slaveseldb
= dictid
;
1196 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
1201 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1202 redisClient
*c
= (redisClient
*) privdata
;
1203 char buf
[REDIS_QUERYBUF_LEN
];
1206 REDIS_NOTUSED(mask
);
1208 nread
= read(fd
, buf
, REDIS_QUERYBUF_LEN
);
1210 if (errno
== EAGAIN
) {
1213 redisLog(REDIS_DEBUG
, "Reading from client: %s",strerror(errno
));
1217 } else if (nread
== 0) {
1218 redisLog(REDIS_DEBUG
, "Client closed connection");
1223 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
1224 c
->lastinteraction
= time(NULL
);
1230 if (c
->bulklen
== -1) {
1231 /* Read the first line of the query */
1232 char *p
= strchr(c
->querybuf
,'\n');
1238 query
= c
->querybuf
;
1239 c
->querybuf
= sdsempty();
1240 querylen
= 1+(p
-(query
));
1241 if (sdslen(query
) > querylen
) {
1242 /* leave data after the first line of the query in the buffer */
1243 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
1245 *p
= '\0'; /* remove "\n" */
1246 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
1247 sdsupdatelen(query
);
1249 /* Now we can split the query in arguments */
1250 if (sdslen(query
) == 0) {
1251 /* Ignore empty query */
1255 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
1257 if (argv
== NULL
) oom("sdssplitlen");
1258 for (j
= 0; j
< argc
&& j
< REDIS_MAX_ARGS
; j
++) {
1259 if (sdslen(argv
[j
])) {
1260 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
1267 /* Execute the command. If the client is still valid
1268 * after processCommand() return and there is something
1269 * on the query buffer try to process the next command. */
1270 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
1272 } else if (sdslen(c
->querybuf
) >= 1024) {
1273 redisLog(REDIS_DEBUG
, "Client protocol error");
1278 /* Bulk read handling. Note that if we are at this point
1279 the client already sent a command terminated with a newline,
1280 we are reading the bulk data that is actually the last
1281 argument of the command. */
1282 int qbl
= sdslen(c
->querybuf
);
1284 if (c
->bulklen
<= qbl
) {
1285 /* Copy everything but the final CRLF as final argument */
1286 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
1288 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
1295 static int selectDb(redisClient
*c
, int id
) {
1296 if (id
< 0 || id
>= server
.dbnum
)
1298 c
->dict
= server
.dict
[id
];
1303 static redisClient
*createClient(int fd
) {
1304 redisClient
*c
= zmalloc(sizeof(*c
));
1306 anetNonBlock(NULL
,fd
);
1307 anetTcpNoDelay(NULL
,fd
);
1308 if (!c
) return NULL
;
1311 c
->querybuf
= sdsempty();
1316 c
->lastinteraction
= time(NULL
);
1317 c
->authenticated
= 0;
1318 if ((c
->reply
= listCreate()) == NULL
) oom("listCreate");
1319 listSetFreeMethod(c
->reply
,decrRefCount
);
1320 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
1321 readQueryFromClient
, c
, NULL
) == AE_ERR
) {
1325 if (!listAddNodeTail(server
.clients
,c
)) oom("listAddNodeTail");
1329 static void addReply(redisClient
*c
, robj
*obj
) {
1330 if (listLength(c
->reply
) == 0 &&
1331 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
1332 sendReplyToClient
, c
, NULL
) == AE_ERR
) return;
1333 if (!listAddNodeTail(c
->reply
,obj
)) oom("listAddNodeTail");
1337 static void addReplySds(redisClient
*c
, sds s
) {
1338 robj
*o
= createObject(REDIS_STRING
,s
);
1343 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1347 REDIS_NOTUSED(mask
);
1348 REDIS_NOTUSED(privdata
);
1350 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
1351 if (cfd
== AE_ERR
) {
1352 redisLog(REDIS_DEBUG
,"Accepting client connection: %s", server
.neterr
);
1355 redisLog(REDIS_DEBUG
,"Accepted %s:%d", cip
, cport
);
1356 if (createClient(cfd
) == NULL
) {
1357 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
1358 close(cfd
); /* May be already closed, just ingore errors */
1361 server
.stat_numconnections
++;
1364 /* ======================= Redis objects implementation ===================== */
1366 static robj
*createObject(int type
, void *ptr
) {
1369 if (listLength(server
.objfreelist
)) {
1370 listNode
*head
= listFirst(server
.objfreelist
);
1371 o
= listNodeValue(head
);
1372 listDelNode(server
.objfreelist
,head
);
1374 o
= zmalloc(sizeof(*o
));
1376 if (!o
) oom("createObject");
1383 static robj
*createStringObject(char *ptr
, size_t len
) {
1384 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
1387 static robj
*createListObject(void) {
1388 list
*l
= listCreate();
1390 if (!l
) oom("listCreate");
1391 listSetFreeMethod(l
,decrRefCount
);
1392 return createObject(REDIS_LIST
,l
);
1395 static robj
*createSetObject(void) {
1396 dict
*d
= dictCreate(&setDictType
,NULL
);
1397 if (!d
) oom("dictCreate");
1398 return createObject(REDIS_SET
,d
);
1402 static robj
*createHashObject(void) {
1403 dict
*d
= dictCreate(&hashDictType
,NULL
);
1404 if (!d
) oom("dictCreate");
1405 return createObject(REDIS_SET
,d
);
1409 static void freeStringObject(robj
*o
) {
1413 static void freeListObject(robj
*o
) {
1414 listRelease((list
*) o
->ptr
);
1417 static void freeSetObject(robj
*o
) {
1418 dictRelease((dict
*) o
->ptr
);
1421 static void freeHashObject(robj
*o
) {
1422 dictRelease((dict
*) o
->ptr
);
1425 static void incrRefCount(robj
*o
) {
1429 static void decrRefCount(void *obj
) {
1431 if (--(o
->refcount
) == 0) {
1433 case REDIS_STRING
: freeStringObject(o
); break;
1434 case REDIS_LIST
: freeListObject(o
); break;
1435 case REDIS_SET
: freeSetObject(o
); break;
1436 case REDIS_HASH
: freeHashObject(o
); break;
1437 default: assert(0 != 0); break;
1439 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
1440 !listAddNodeHead(server
.objfreelist
,o
))
1445 /* Try to share an object against the shared objects pool */
1446 static robj
*tryObjectSharing(robj
*o
) {
1447 struct dictEntry
*de
;
1450 if (server
.shareobjects
== 0) return o
;
1452 assert(o
->type
== REDIS_STRING
);
1453 de
= dictFind(server
.sharingpool
,o
);
1455 robj
*shared
= dictGetEntryKey(de
);
1457 c
= ((unsigned long) dictGetEntryVal(de
))+1;
1458 dictGetEntryVal(de
) = (void*) c
;
1459 incrRefCount(shared
);
1463 /* Here we are using a stream algorihtm: Every time an object is
1464 * shared we increment its count, everytime there is a miss we
1465 * recrement the counter of a random object. If this object reaches
1466 * zero we remove the object and put the current object instead. */
1467 if (dictGetHashTableUsed(server
.sharingpool
) >=
1468 server
.sharingpoolsize
) {
1469 de
= dictGetRandomKey(server
.sharingpool
);
1471 c
= ((unsigned long) dictGetEntryVal(de
))-1;
1472 dictGetEntryVal(de
) = (void*) c
;
1474 dictDelete(server
.sharingpool
,de
->key
);
1477 c
= 0; /* If the pool is empty we want to add this object */
1482 retval
= dictAdd(server
.sharingpool
,o
,(void*)1);
1483 assert(retval
== DICT_OK
);
1490 /*============================ DB saving/loading ============================ */
1492 static int rdbSaveType(FILE *fp
, unsigned char type
) {
1493 if (fwrite(&type
,1,1,fp
) == 0) return -1;
1497 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
1498 unsigned char buf
[2];
1501 /* Save a 6 bit len */
1502 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
1503 if (fwrite(buf
,1,1,fp
) == 0) return -1;
1504 } else if (len
< (1<<14)) {
1505 /* Save a 14 bit len */
1506 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
1508 if (fwrite(buf
,4,1,fp
) == 0) return -1;
1510 /* Save a 32 bit len */
1511 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
1512 if (fwrite(buf
,1,1,fp
) == 0) return -1;
1514 if (fwrite(&len
,4,1,fp
) == 0) return -1;
1519 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
1520 size_t len
= sdslen(obj
->ptr
);
1522 if (rdbSaveLen(fp
,len
) == -1) return -1;
1523 if (len
&& fwrite(obj
->ptr
,len
,1,fp
) == 0) return -1;
1527 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
1528 static int rdbSave(char *filename
) {
1529 dictIterator
*di
= NULL
;
1535 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
1536 fp
= fopen(tmpfile
,"w");
1538 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
1541 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
1542 for (j
= 0; j
< server
.dbnum
; j
++) {
1543 dict
*d
= server
.dict
[j
];
1544 if (dictGetHashTableUsed(d
) == 0) continue;
1545 di
= dictGetIterator(d
);
1551 /* Write the SELECT DB opcode */
1552 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
1553 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
1555 /* Iterate this DB writing every entry */
1556 while((de
= dictNext(di
)) != NULL
) {
1557 robj
*key
= dictGetEntryKey(de
);
1558 robj
*o
= dictGetEntryVal(de
);
1560 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
1561 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
1562 if (o
->type
== REDIS_STRING
) {
1563 /* Save a string value */
1564 if (rdbSaveStringObject(fp
,o
) == -1) goto werr
;
1565 } else if (o
->type
== REDIS_LIST
) {
1566 /* Save a list value */
1567 list
*list
= o
->ptr
;
1568 listNode
*ln
= list
->head
;
1570 if (rdbSaveLen(fp
,listLength(list
)) == -1) goto werr
;
1572 robj
*eleobj
= listNodeValue(ln
);
1574 if (rdbSaveStringObject(fp
,eleobj
) == -1) goto werr
;
1577 } else if (o
->type
== REDIS_SET
) {
1578 /* Save a set value */
1580 dictIterator
*di
= dictGetIterator(set
);
1583 if (!set
) oom("dictGetIteraotr");
1584 if (rdbSaveLen(fp
,dictGetHashTableUsed(set
)) == -1) goto werr
;
1585 while((de
= dictNext(di
)) != NULL
) {
1586 robj
*eleobj
= dictGetEntryKey(de
);
1588 if (rdbSaveStringObject(fp
,eleobj
) == -1) goto werr
;
1590 dictReleaseIterator(di
);
1595 dictReleaseIterator(di
);
1598 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
1600 /* Make sure data will not remain on the OS's output buffers */
1605 /* Use RENAME to make sure the DB file is changed atomically only
1606 * if the generate DB file is ok. */
1607 if (rename(tmpfile
,filename
) == -1) {
1608 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destionation: %s", strerror(errno
));
1612 redisLog(REDIS_NOTICE
,"DB saved on disk");
1614 server
.lastsave
= time(NULL
);
1620 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
1621 if (di
) dictReleaseIterator(di
);
1625 static int rdbSaveBackground(char *filename
) {
1628 if (server
.bgsaveinprogress
) return REDIS_ERR
;
1629 if ((childpid
= fork()) == 0) {
1632 if (rdbSave(filename
) == REDIS_OK
) {
1639 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
1640 server
.bgsaveinprogress
= 1;
1643 return REDIS_OK
; /* unreached */
1646 static int rdbLoadType(FILE *fp
) {
1648 if (fread(&type
,1,1,fp
) == 0) return -1;
1652 static uint32_t rdbLoadLen(FILE *fp
, int rdbver
) {
1653 unsigned char buf
[2];
1657 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
1660 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
1661 if ((buf
[0]&0xC0) == REDIS_RDB_6BITLEN
) {
1662 /* Read a 6 bit len */
1664 } else if ((buf
[0]&0xC0) == REDIS_RDB_14BITLEN
) {
1665 /* Read a 14 bit len */
1666 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
1667 return ((buf
[0]&0x3F)<<8)|buf
[1];
1669 /* Read a 32 bit len */
1670 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
1676 static robj
*rdbLoadStringObject(FILE*fp
,int rdbver
) {
1677 uint32_t len
= rdbLoadLen(fp
,rdbver
);
1680 if (len
== REDIS_RDB_LENERR
) return NULL
;
1681 val
= sdsnewlen(NULL
,len
);
1682 if (len
&& fread(val
,len
,1,fp
) == 0) {
1686 return tryObjectSharing(createObject(REDIS_STRING
,val
));
1689 static int rdbLoad(char *filename
) {
1691 robj
*keyobj
= NULL
;
1695 dict
*d
= server
.dict
[0];
1698 fp
= fopen(filename
,"r");
1699 if (!fp
) return REDIS_ERR
;
1700 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
1702 if (memcmp(buf
,"REDIS",5) != 0) {
1704 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
1707 rdbver
= atoi(buf
+5);
1710 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
1717 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
1718 if (type
== REDIS_EOF
) break;
1719 /* Handle SELECT DB opcode as a special case */
1720 if (type
== REDIS_SELECTDB
) {
1721 if ((dbid
= rdbLoadLen(fp
,rdbver
)) == REDIS_RDB_LENERR
) goto eoferr
;
1722 if (dbid
>= (unsigned)server
.dbnum
) {
1723 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
1726 d
= server
.dict
[dbid
];
1730 if ((keyobj
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1732 if (type
== REDIS_STRING
) {
1733 /* Read string value */
1734 if ((o
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1735 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
1736 /* Read list/set value */
1739 if ((listlen
= rdbLoadLen(fp
,rdbver
)) == REDIS_RDB_LENERR
)
1741 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
1742 /* Load every single element of the list/set */
1746 if ((ele
= rdbLoadStringObject(fp
,rdbver
)) == NULL
) goto eoferr
;
1747 if (type
== REDIS_LIST
) {
1748 if (!listAddNodeTail((list
*)o
->ptr
,ele
))
1749 oom("listAddNodeTail");
1751 if (dictAdd((dict
*)o
->ptr
,ele
,NULL
) == DICT_ERR
)
1758 /* Add the new object in the hash table */
1759 retval
= dictAdd(d
,keyobj
,o
);
1760 if (retval
== DICT_ERR
) {
1761 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
1769 eoferr
: /* unexpected end of file is handled here with a fatal exit */
1770 decrRefCount(keyobj
);
1771 redisLog(REDIS_WARNING
,"Short read loading DB. Unrecoverable error, exiting now.");
1773 return REDIS_ERR
; /* Just to avoid warning */
1776 /*================================== Commands =============================== */
1778 static void authCommand(redisClient
*c
) {
1779 if (!strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
1780 c
->authenticated
= 1;
1781 addReply(c
,shared
.ok
);
1783 c
->authenticated
= 0;
1784 addReply(c
,shared
.err
);
1788 static void pingCommand(redisClient
*c
) {
1789 addReply(c
,shared
.pong
);
1792 static void echoCommand(redisClient
*c
) {
1793 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
1794 (int)sdslen(c
->argv
[1]->ptr
)));
1795 addReply(c
,c
->argv
[1]);
1796 addReply(c
,shared
.crlf
);
1799 /*=================================== Strings =============================== */
1801 static void setGenericCommand(redisClient
*c
, int nx
) {
1804 retval
= dictAdd(c
->dict
,c
->argv
[1],c
->argv
[2]);
1805 if (retval
== DICT_ERR
) {
1807 dictReplace(c
->dict
,c
->argv
[1],c
->argv
[2]);
1808 incrRefCount(c
->argv
[2]);
1810 addReply(c
,shared
.czero
);
1814 incrRefCount(c
->argv
[1]);
1815 incrRefCount(c
->argv
[2]);
1818 addReply(c
, nx
? shared
.cone
: shared
.ok
);
1821 static void setCommand(redisClient
*c
) {
1822 return setGenericCommand(c
,0);
1825 static void setnxCommand(redisClient
*c
) {
1826 return setGenericCommand(c
,1);
1829 static void getCommand(redisClient
*c
) {
1832 de
= dictFind(c
->dict
,c
->argv
[1]);
1834 addReply(c
,shared
.nullbulk
);
1836 robj
*o
= dictGetEntryVal(de
);
1838 if (o
->type
!= REDIS_STRING
) {
1839 addReply(c
,shared
.wrongtypeerr
);
1841 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o
->ptr
)));
1843 addReply(c
,shared
.crlf
);
1848 static void mgetCommand(redisClient
*c
) {
1852 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
1853 for (j
= 1; j
< c
->argc
; j
++) {
1854 de
= dictFind(c
->dict
,c
->argv
[j
]);
1856 addReply(c
,shared
.nullbulk
);
1858 robj
*o
= dictGetEntryVal(de
);
1860 if (o
->type
!= REDIS_STRING
) {
1861 addReply(c
,shared
.nullbulk
);
1863 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(o
->ptr
)));
1865 addReply(c
,shared
.crlf
);
1871 static void incrDecrCommand(redisClient
*c
, int incr
) {
1877 de
= dictFind(c
->dict
,c
->argv
[1]);
1881 robj
*o
= dictGetEntryVal(de
);
1883 if (o
->type
!= REDIS_STRING
) {
1888 value
= strtoll(o
->ptr
, &eptr
, 10);
1893 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
1894 retval
= dictAdd(c
->dict
,c
->argv
[1],o
);
1895 if (retval
== DICT_ERR
) {
1896 dictReplace(c
->dict
,c
->argv
[1],o
);
1898 incrRefCount(c
->argv
[1]);
1901 addReply(c
,shared
.colon
);
1903 addReply(c
,shared
.crlf
);
1906 static void incrCommand(redisClient
*c
) {
1907 return incrDecrCommand(c
,1);
1910 static void decrCommand(redisClient
*c
) {
1911 return incrDecrCommand(c
,-1);
1914 static void incrbyCommand(redisClient
*c
) {
1915 int incr
= atoi(c
->argv
[2]->ptr
);
1916 return incrDecrCommand(c
,incr
);
1919 static void decrbyCommand(redisClient
*c
) {
1920 int incr
= atoi(c
->argv
[2]->ptr
);
1921 return incrDecrCommand(c
,-incr
);
1924 /* ========================= Type agnostic commands ========================= */
1926 static void delCommand(redisClient
*c
) {
1927 if (dictDelete(c
->dict
,c
->argv
[1]) == DICT_OK
) {
1929 addReply(c
,shared
.cone
);
1931 addReply(c
,shared
.czero
);
1935 static void existsCommand(redisClient
*c
) {
1938 de
= dictFind(c
->dict
,c
->argv
[1]);
1940 addReply(c
,shared
.czero
);
1942 addReply(c
,shared
.cone
);
1945 static void selectCommand(redisClient
*c
) {
1946 int id
= atoi(c
->argv
[1]->ptr
);
1948 if (selectDb(c
,id
) == REDIS_ERR
) {
1949 addReplySds(c
,"-ERR invalid DB index\r\n");
1951 addReply(c
,shared
.ok
);
1955 static void randomkeyCommand(redisClient
*c
) {
1958 de
= dictGetRandomKey(c
->dict
);
1960 addReply(c
,shared
.crlf
);
1962 addReply(c
,shared
.plus
);
1963 addReply(c
,dictGetEntryKey(de
));
1964 addReply(c
,shared
.crlf
);
1968 static void keysCommand(redisClient
*c
) {
1971 sds pattern
= c
->argv
[1]->ptr
;
1972 int plen
= sdslen(pattern
);
1973 int numkeys
= 0, keyslen
= 0;
1974 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
1976 di
= dictGetIterator(c
->dict
);
1977 if (!di
) oom("dictGetIterator");
1979 decrRefCount(lenobj
);
1980 while((de
= dictNext(di
)) != NULL
) {
1981 robj
*keyobj
= dictGetEntryKey(de
);
1982 sds key
= keyobj
->ptr
;
1983 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
1984 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
1986 addReply(c
,shared
.space
);
1989 keyslen
+= sdslen(key
);
1992 dictReleaseIterator(di
);
1993 lenobj
->ptr
= sdscatprintf(sdsempty(),"$%lu\r\n",keyslen
+(numkeys
? (numkeys
-1) : 0));
1994 addReply(c
,shared
.crlf
);
1997 static void dbsizeCommand(redisClient
*c
) {
1999 sdscatprintf(sdsempty(),":%lu\r\n",dictGetHashTableUsed(c
->dict
)));
2002 static void lastsaveCommand(redisClient
*c
) {
2004 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
2007 static void typeCommand(redisClient
*c
) {
2011 de
= dictFind(c
->dict
,c
->argv
[1]);
2015 robj
*o
= dictGetEntryVal(de
);
2018 case REDIS_STRING
: type
= "+string"; break;
2019 case REDIS_LIST
: type
= "+list"; break;
2020 case REDIS_SET
: type
= "+set"; break;
2021 default: type
= "unknown"; break;
2024 addReplySds(c
,sdsnew(type
));
2025 addReply(c
,shared
.crlf
);
2028 static void saveCommand(redisClient
*c
) {
2029 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
2030 addReply(c
,shared
.ok
);
2032 addReply(c
,shared
.err
);
2036 static void bgsaveCommand(redisClient
*c
) {
2037 if (server
.bgsaveinprogress
) {
2038 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
2041 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
2042 addReply(c
,shared
.ok
);
2044 addReply(c
,shared
.err
);
2048 static void shutdownCommand(redisClient
*c
) {
2049 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
2050 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
2051 if (server
.daemonize
) {
2052 unlink(server
.pidfile
);
2054 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
2057 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
2058 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
2062 static void renameGenericCommand(redisClient
*c
, int nx
) {
2066 /* To use the same key as src and dst is probably an error */
2067 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
2068 addReply(c
,shared
.sameobjecterr
);
2072 de
= dictFind(c
->dict
,c
->argv
[1]);
2074 addReply(c
,shared
.nokeyerr
);
2077 o
= dictGetEntryVal(de
);
2079 if (dictAdd(c
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
2082 addReply(c
,shared
.czero
);
2085 dictReplace(c
->dict
,c
->argv
[2],o
);
2087 incrRefCount(c
->argv
[2]);
2089 dictDelete(c
->dict
,c
->argv
[1]);
2091 addReply(c
,nx
? shared
.cone
: shared
.ok
);
2094 static void renameCommand(redisClient
*c
) {
2095 renameGenericCommand(c
,0);
2098 static void renamenxCommand(redisClient
*c
) {
2099 renameGenericCommand(c
,1);
2102 static void moveCommand(redisClient
*c
) {
2108 /* Obtain source and target DB pointers */
2111 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
2112 addReply(c
,shared
.outofrangeerr
);
2119 /* If the user is moving using as target the same
2120 * DB as the source DB it is probably an error. */
2122 addReply(c
,shared
.sameobjecterr
);
2126 /* Check if the element exists and get a reference */
2127 de
= dictFind(c
->dict
,c
->argv
[1]);
2129 addReply(c
,shared
.czero
);
2133 /* Try to add the element to the target DB */
2134 key
= dictGetEntryKey(de
);
2135 o
= dictGetEntryVal(de
);
2136 if (dictAdd(dst
,key
,o
) == DICT_ERR
) {
2137 addReply(c
,shared
.czero
);
2143 /* OK! key moved, free the entry in the source DB */
2144 dictDelete(src
,c
->argv
[1]);
2146 addReply(c
,shared
.cone
);
2149 /* =================================== Lists ================================ */
2150 static void pushGenericCommand(redisClient
*c
, int where
) {
2155 de
= dictFind(c
->dict
,c
->argv
[1]);
2157 lobj
= createListObject();
2159 if (where
== REDIS_HEAD
) {
2160 if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead");
2162 if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail");
2164 dictAdd(c
->dict
,c
->argv
[1],lobj
);
2165 incrRefCount(c
->argv
[1]);
2166 incrRefCount(c
->argv
[2]);
2168 lobj
= dictGetEntryVal(de
);
2169 if (lobj
->type
!= REDIS_LIST
) {
2170 addReply(c
,shared
.wrongtypeerr
);
2174 if (where
== REDIS_HEAD
) {
2175 if (!listAddNodeHead(list
,c
->argv
[2])) oom("listAddNodeHead");
2177 if (!listAddNodeTail(list
,c
->argv
[2])) oom("listAddNodeTail");
2179 incrRefCount(c
->argv
[2]);
2182 addReply(c
,shared
.ok
);
2185 static void lpushCommand(redisClient
*c
) {
2186 pushGenericCommand(c
,REDIS_HEAD
);
2189 static void rpushCommand(redisClient
*c
) {
2190 pushGenericCommand(c
,REDIS_TAIL
);
2193 static void llenCommand(redisClient
*c
) {
2197 de
= dictFind(c
->dict
,c
->argv
[1]);
2199 addReply(c
,shared
.czero
);
2202 robj
*o
= dictGetEntryVal(de
);
2203 if (o
->type
!= REDIS_LIST
) {
2204 addReply(c
,shared
.wrongtypeerr
);
2207 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
)));
2212 static void lindexCommand(redisClient
*c
) {
2214 int index
= atoi(c
->argv
[2]->ptr
);
2216 de
= dictFind(c
->dict
,c
->argv
[1]);
2218 addReply(c
,shared
.nullbulk
);
2220 robj
*o
= dictGetEntryVal(de
);
2222 if (o
->type
!= REDIS_LIST
) {
2223 addReply(c
,shared
.wrongtypeerr
);
2225 list
*list
= o
->ptr
;
2228 ln
= listIndex(list
, index
);
2230 addReply(c
,shared
.nullbulk
);
2232 robj
*ele
= listNodeValue(ln
);
2233 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2235 addReply(c
,shared
.crlf
);
2241 static void lsetCommand(redisClient
*c
) {
2243 int index
= atoi(c
->argv
[2]->ptr
);
2245 de
= dictFind(c
->dict
,c
->argv
[1]);
2247 addReply(c
,shared
.nokeyerr
);
2249 robj
*o
= dictGetEntryVal(de
);
2251 if (o
->type
!= REDIS_LIST
) {
2252 addReply(c
,shared
.wrongtypeerr
);
2254 list
*list
= o
->ptr
;
2257 ln
= listIndex(list
, index
);
2259 addReply(c
,shared
.outofrangeerr
);
2261 robj
*ele
= listNodeValue(ln
);
2264 listNodeValue(ln
) = c
->argv
[3];
2265 incrRefCount(c
->argv
[3]);
2266 addReply(c
,shared
.ok
);
2273 static void popGenericCommand(redisClient
*c
, int where
) {
2276 de
= dictFind(c
->dict
,c
->argv
[1]);
2278 addReply(c
,shared
.nullbulk
);
2280 robj
*o
= dictGetEntryVal(de
);
2282 if (o
->type
!= REDIS_LIST
) {
2283 addReply(c
,shared
.wrongtypeerr
);
2285 list
*list
= o
->ptr
;
2288 if (where
== REDIS_HEAD
)
2289 ln
= listFirst(list
);
2291 ln
= listLast(list
);
2294 addReply(c
,shared
.nullbulk
);
2296 robj
*ele
= listNodeValue(ln
);
2297 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2299 addReply(c
,shared
.crlf
);
2300 listDelNode(list
,ln
);
2307 static void lpopCommand(redisClient
*c
) {
2308 popGenericCommand(c
,REDIS_HEAD
);
2311 static void rpopCommand(redisClient
*c
) {
2312 popGenericCommand(c
,REDIS_TAIL
);
2315 static void lrangeCommand(redisClient
*c
) {
2317 int start
= atoi(c
->argv
[2]->ptr
);
2318 int end
= atoi(c
->argv
[3]->ptr
);
2320 de
= dictFind(c
->dict
,c
->argv
[1]);
2322 addReply(c
,shared
.nullmultibulk
);
2324 robj
*o
= dictGetEntryVal(de
);
2326 if (o
->type
!= REDIS_LIST
) {
2327 addReply(c
,shared
.wrongtypeerr
);
2329 list
*list
= o
->ptr
;
2331 int llen
= listLength(list
);
2335 /* convert negative indexes */
2336 if (start
< 0) start
= llen
+start
;
2337 if (end
< 0) end
= llen
+end
;
2338 if (start
< 0) start
= 0;
2339 if (end
< 0) end
= 0;
2341 /* indexes sanity checks */
2342 if (start
> end
|| start
>= llen
) {
2343 /* Out of range start or start > end result in empty list */
2344 addReply(c
,shared
.emptymultibulk
);
2347 if (end
>= llen
) end
= llen
-1;
2348 rangelen
= (end
-start
)+1;
2350 /* Return the result in form of a multi-bulk reply */
2351 ln
= listIndex(list
, start
);
2352 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
2353 for (j
= 0; j
< rangelen
; j
++) {
2354 ele
= listNodeValue(ln
);
2355 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",(int)sdslen(ele
->ptr
)));
2357 addReply(c
,shared
.crlf
);
2364 static void ltrimCommand(redisClient
*c
) {
2366 int start
= atoi(c
->argv
[2]->ptr
);
2367 int end
= atoi(c
->argv
[3]->ptr
);
2369 de
= dictFind(c
->dict
,c
->argv
[1]);
2371 addReply(c
,shared
.nokeyerr
);
2373 robj
*o
= dictGetEntryVal(de
);
2375 if (o
->type
!= REDIS_LIST
) {
2376 addReply(c
,shared
.wrongtypeerr
);
2378 list
*list
= o
->ptr
;
2380 int llen
= listLength(list
);
2381 int j
, ltrim
, rtrim
;
2383 /* convert negative indexes */
2384 if (start
< 0) start
= llen
+start
;
2385 if (end
< 0) end
= llen
+end
;
2386 if (start
< 0) start
= 0;
2387 if (end
< 0) end
= 0;
2389 /* indexes sanity checks */
2390 if (start
> end
|| start
>= llen
) {
2391 /* Out of range start or start > end result in empty list */
2395 if (end
>= llen
) end
= llen
-1;
2400 /* Remove list elements to perform the trim */
2401 for (j
= 0; j
< ltrim
; j
++) {
2402 ln
= listFirst(list
);
2403 listDelNode(list
,ln
);
2405 for (j
= 0; j
< rtrim
; j
++) {
2406 ln
= listLast(list
);
2407 listDelNode(list
,ln
);
2409 addReply(c
,shared
.ok
);
2415 static void lremCommand(redisClient
*c
) {
2418 de
= dictFind(c
->dict
,c
->argv
[1]);
2420 addReply(c
,shared
.nokeyerr
);
2422 robj
*o
= dictGetEntryVal(de
);
2424 if (o
->type
!= REDIS_LIST
) {
2425 addReply(c
,shared
.wrongtypeerr
);
2427 list
*list
= o
->ptr
;
2428 listNode
*ln
, *next
;
2429 int toremove
= atoi(c
->argv
[2]->ptr
);
2434 toremove
= -toremove
;
2437 ln
= fromtail
? list
->tail
: list
->head
;
2439 next
= fromtail
? ln
->prev
: ln
->next
;
2440 robj
*ele
= listNodeValue(ln
);
2441 if (sdscmp(ele
->ptr
,c
->argv
[3]->ptr
) == 0) {
2442 listDelNode(list
,ln
);
2445 if (toremove
&& removed
== toremove
) break;
2449 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
2454 /* ==================================== Sets ================================ */
2456 static void saddCommand(redisClient
*c
) {
2460 de
= dictFind(c
->dict
,c
->argv
[1]);
2462 set
= createSetObject();
2463 dictAdd(c
->dict
,c
->argv
[1],set
);
2464 incrRefCount(c
->argv
[1]);
2466 set
= dictGetEntryVal(de
);
2467 if (set
->type
!= REDIS_SET
) {
2468 addReply(c
,shared
.wrongtypeerr
);
2472 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
2473 incrRefCount(c
->argv
[2]);
2475 addReply(c
,shared
.cone
);
2477 addReply(c
,shared
.czero
);
2481 static void sremCommand(redisClient
*c
) {
2484 de
= dictFind(c
->dict
,c
->argv
[1]);
2486 addReply(c
,shared
.czero
);
2490 set
= dictGetEntryVal(de
);
2491 if (set
->type
!= REDIS_SET
) {
2492 addReply(c
,shared
.wrongtypeerr
);
2495 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
2497 addReply(c
,shared
.cone
);
2499 addReply(c
,shared
.czero
);
2504 static void sismemberCommand(redisClient
*c
) {
2507 de
= dictFind(c
->dict
,c
->argv
[1]);
2509 addReply(c
,shared
.czero
);
2513 set
= dictGetEntryVal(de
);
2514 if (set
->type
!= REDIS_SET
) {
2515 addReply(c
,shared
.wrongtypeerr
);
2518 if (dictFind(set
->ptr
,c
->argv
[2]))
2519 addReply(c
,shared
.cone
);
2521 addReply(c
,shared
.czero
);
2525 static void scardCommand(redisClient
*c
) {
2529 de
= dictFind(c
->dict
,c
->argv
[1]);
2531 addReply(c
,shared
.czero
);
2534 robj
*o
= dictGetEntryVal(de
);
2535 if (o
->type
!= REDIS_SET
) {
2536 addReply(c
,shared
.wrongtypeerr
);
2539 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",
2540 dictGetHashTableUsed(s
)));
2545 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
2546 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
2548 return dictGetHashTableUsed(*d1
)-dictGetHashTableUsed(*d2
);
2551 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
) {
2552 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
2555 robj
*lenobj
= NULL
, *dstset
= NULL
;
2556 int j
, cardinality
= 0;
2558 if (!dv
) oom("sinterCommand");
2559 for (j
= 0; j
< setsnum
; j
++) {
2563 de
= dictFind(c
->dict
,setskeys
[j
]);
2566 addReply(c
,shared
.nokeyerr
);
2569 setobj
= dictGetEntryVal(de
);
2570 if (setobj
->type
!= REDIS_SET
) {
2572 addReply(c
,shared
.wrongtypeerr
);
2575 dv
[j
] = setobj
->ptr
;
2577 /* Sort sets from the smallest to largest, this will improve our
2578 * algorithm's performace */
2579 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
2581 /* The first thing we should output is the total number of elements...
2582 * since this is a multi-bulk write, but at this stage we don't know
2583 * the intersection set size, so we use a trick, append an empty object
2584 * to the output list and save the pointer to later modify it with the
2587 lenobj
= createObject(REDIS_STRING
,NULL
);
2589 decrRefCount(lenobj
);
2591 /* If we have a target key where to store the resulting set
2592 * create this key with an empty set inside */
2593 dstset
= createSetObject();
2594 dictDelete(c
->dict
,dstkey
);
2595 dictAdd(c
->dict
,dstkey
,dstset
);
2596 incrRefCount(dstkey
);
2599 /* Iterate all the elements of the first (smallest) set, and test
2600 * the element against all the other sets, if at least one set does
2601 * not include the element it is discarded */
2602 di
= dictGetIterator(dv
[0]);
2603 if (!di
) oom("dictGetIterator");
2605 while((de
= dictNext(di
)) != NULL
) {
2608 for (j
= 1; j
< setsnum
; j
++)
2609 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
2611 continue; /* at least one set does not contain the member */
2612 ele
= dictGetEntryKey(de
);
2614 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(ele
->ptr
)));
2616 addReply(c
,shared
.crlf
);
2619 dictAdd(dstset
->ptr
,ele
,NULL
);
2623 dictReleaseIterator(di
);
2626 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",cardinality
);
2628 addReply(c
,shared
.ok
);
2632 static void sinterCommand(redisClient
*c
) {
2633 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
2636 static void sinterstoreCommand(redisClient
*c
) {
2637 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
2640 static void flushdbCommand(redisClient
*c
) {
2642 addReply(c
,shared
.ok
);
2643 rdbSave(server
.dbfilename
);
2646 static void flushallCommand(redisClient
*c
) {
2648 addReply(c
,shared
.ok
);
2649 rdbSave(server
.dbfilename
);
2652 redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
2653 redisSortOperation
*so
= zmalloc(sizeof(*so
));
2654 if (!so
) oom("createSortOperation");
2656 so
->pattern
= pattern
;
2660 /* Return the value associated to the key with a name obtained
2661 * substituting the first occurence of '*' in 'pattern' with 'subst' */
2662 robj
*lookupKeyByPattern(dict
*dict
, robj
*pattern
, robj
*subst
) {
2666 int prefixlen
, sublen
, postfixlen
;
2668 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
2672 char buf
[REDIS_SORTKEY_MAX
+1];
2676 spat
= pattern
->ptr
;
2678 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
2679 p
= strchr(spat
,'*');
2680 if (!p
) return NULL
;
2683 sublen
= sdslen(ssub
);
2684 postfixlen
= sdslen(spat
)-(prefixlen
+1);
2685 memcpy(keyname
.buf
,spat
,prefixlen
);
2686 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
2687 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
2688 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
2689 keyname
.len
= prefixlen
+sublen
+postfixlen
;
2691 keyobj
.refcount
= 1;
2692 keyobj
.type
= REDIS_STRING
;
2693 keyobj
.ptr
= ((char*)&keyname
)+(sizeof(long)*2);
2695 de
= dictFind(dict
,&keyobj
);
2696 // printf("lookup '%s' => %p\n", keyname.buf,de);
2697 if (!de
) return NULL
;
2698 return dictGetEntryVal(de
);
2701 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
2702 * the additional parameter is not standard but a BSD-specific we have to
2703 * pass sorting parameters via the global 'server' structure */
2704 static int sortCompare(const void *s1
, const void *s2
) {
2705 const redisSortObject
*so1
= s1
, *so2
= s2
;
2708 if (!server
.sort_alpha
) {
2709 /* Numeric sorting. Here it's trivial as we precomputed scores */
2710 if (so1
->u
.score
> so2
->u
.score
) {
2712 } else if (so1
->u
.score
< so2
->u
.score
) {
2718 /* Alphanumeric sorting */
2719 if (server
.sort_bypattern
) {
2720 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
2721 /* At least one compare object is NULL */
2722 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
2724 else if (so1
->u
.cmpobj
== NULL
)
2729 /* We have both the objects, use strcoll */
2730 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
2733 /* Compare elements directly */
2734 cmp
= strcoll(so1
->obj
->ptr
,so2
->obj
->ptr
);
2737 return server
.sort_desc
? -cmp
: cmp
;
2740 /* The SORT command is the most complex command in Redis. Warning: this code
2741 * is optimized for speed and a bit less for readability */
2742 static void sortCommand(redisClient
*c
) {
2746 int desc
= 0, alpha
= 0;
2747 int limit_start
= 0, limit_count
= -1, start
, end
;
2748 int j
, dontsort
= 0, vectorlen
;
2749 int getop
= 0; /* GET operation counter */
2750 robj
*sortval
, *sortby
= NULL
;
2751 redisSortObject
*vector
; /* Resulting vector to sort */
2753 /* Lookup the key to sort. It must be of the right types */
2754 de
= dictFind(c
->dict
,c
->argv
[1]);
2756 addReply(c
,shared
.nokeyerr
);
2759 sortval
= dictGetEntryVal(de
);
2760 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
) {
2761 addReply(c
,shared
.wrongtypeerr
);
2765 /* Create a list of operations to perform for every sorted element.
2766 * Operations can be GET/DEL/INCR/DECR */
2767 operations
= listCreate();
2768 listSetFreeMethod(operations
,zfree
);
2771 /* Now we need to protect sortval incrementing its count, in the future
2772 * SORT may have options able to overwrite/delete keys during the sorting
2773 * and the sorted key itself may get destroied */
2774 incrRefCount(sortval
);
2776 /* The SORT command has an SQL-alike syntax, parse it */
2777 while(j
< c
->argc
) {
2778 int leftargs
= c
->argc
-j
-1;
2779 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
2781 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
2783 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
2785 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
2786 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
2787 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
2789 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
2790 sortby
= c
->argv
[j
+1];
2791 /* If the BY pattern does not contain '*', i.e. it is constant,
2792 * we don't need to sort nor to lookup the weight keys. */
2793 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
2795 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
2796 listAddNodeTail(operations
,createSortOperation(
2797 REDIS_SORT_GET
,c
->argv
[j
+1]));
2800 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"del") && leftargs
>= 1) {
2801 listAddNodeTail(operations
,createSortOperation(
2802 REDIS_SORT_DEL
,c
->argv
[j
+1]));
2804 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"incr") && leftargs
>= 1) {
2805 listAddNodeTail(operations
,createSortOperation(
2806 REDIS_SORT_INCR
,c
->argv
[j
+1]));
2808 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
2809 listAddNodeTail(operations
,createSortOperation(
2810 REDIS_SORT_DECR
,c
->argv
[j
+1]));
2813 decrRefCount(sortval
);
2814 listRelease(operations
);
2815 addReply(c
,shared
.syntaxerr
);
2821 /* Load the sorting vector with all the objects to sort */
2822 vectorlen
= (sortval
->type
== REDIS_LIST
) ?
2823 listLength((list
*)sortval
->ptr
) :
2824 dictGetHashTableUsed((dict
*)sortval
->ptr
);
2825 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
2826 if (!vector
) oom("allocating objects vector for SORT");
2828 if (sortval
->type
== REDIS_LIST
) {
2829 list
*list
= sortval
->ptr
;
2830 listNode
*ln
= list
->head
;
2832 robj
*ele
= ln
->value
;
2833 vector
[j
].obj
= ele
;
2834 vector
[j
].u
.score
= 0;
2835 vector
[j
].u
.cmpobj
= NULL
;
2840 dict
*set
= sortval
->ptr
;
2844 di
= dictGetIterator(set
);
2845 if (!di
) oom("dictGetIterator");
2846 while((setele
= dictNext(di
)) != NULL
) {
2847 vector
[j
].obj
= dictGetEntryKey(setele
);
2848 vector
[j
].u
.score
= 0;
2849 vector
[j
].u
.cmpobj
= NULL
;
2852 dictReleaseIterator(di
);
2854 assert(j
== vectorlen
);
2856 /* Now it's time to load the right scores in the sorting vector */
2857 if (dontsort
== 0) {
2858 for (j
= 0; j
< vectorlen
; j
++) {
2862 byval
= lookupKeyByPattern(c
->dict
,sortby
,vector
[j
].obj
);
2863 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
2865 vector
[j
].u
.cmpobj
= byval
;
2866 incrRefCount(byval
);
2868 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
2871 if (!alpha
) vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
2876 /* We are ready to sort the vector... perform a bit of sanity check
2877 * on the LIMIT option too. We'll use a partial version of quicksort. */
2878 start
= (limit_start
< 0) ? 0 : limit_start
;
2879 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
2880 if (start
>= vectorlen
) {
2881 start
= vectorlen
-1;
2884 if (end
>= vectorlen
) end
= vectorlen
-1;
2886 if (dontsort
== 0) {
2887 server
.sort_desc
= desc
;
2888 server
.sort_alpha
= alpha
;
2889 server
.sort_bypattern
= sortby
? 1 : 0;
2890 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
2893 /* Send command output to the output buffer, performing the specified
2894 * GET/DEL/INCR/DECR operations if any. */
2895 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
2896 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
2897 for (j
= start
; j
<= end
; j
++) {
2898 listNode
*ln
= operations
->head
;
2900 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
2901 sdslen(vector
[j
].obj
->ptr
)));
2902 addReply(c
,vector
[j
].obj
);
2903 addReply(c
,shared
.crlf
);
2906 redisSortOperation
*sop
= ln
->value
;
2907 robj
*val
= lookupKeyByPattern(c
->dict
,sop
->pattern
,
2910 if (sop
->type
== REDIS_SORT_GET
) {
2911 if (!val
|| val
->type
!= REDIS_STRING
) {
2912 addReply(c
,shared
.nullbulk
);
2914 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",
2917 addReply(c
,shared
.crlf
);
2919 } else if (sop
->type
== REDIS_SORT_DEL
) {
2927 decrRefCount(sortval
);
2928 listRelease(operations
);
2929 for (j
= 0; j
< vectorlen
; j
++) {
2930 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
2931 decrRefCount(vector
[j
].u
.cmpobj
);
2936 static void infoCommand(redisClient
*c
) {
2938 time_t uptime
= time(NULL
)-server
.stat_starttime
;
2940 info
= sdscatprintf(sdsempty(),
2941 "redis_version:%s\r\n"
2942 "connected_clients:%d\r\n"
2943 "connected_slaves:%d\r\n"
2944 "used_memory:%d\r\n"
2945 "changes_since_last_save:%lld\r\n"
2946 "last_save_time:%d\r\n"
2947 "total_connections_received:%lld\r\n"
2948 "total_commands_processed:%lld\r\n"
2949 "uptime_in_seconds:%d\r\n"
2950 "uptime_in_days:%d\r\n"
2952 listLength(server
.clients
)-listLength(server
.slaves
),
2953 listLength(server
.slaves
),
2957 server
.stat_numconnections
,
2958 server
.stat_numcommands
,
2962 addReplySds(c
,sdscatprintf(sdsempty(),"$%d\r\n",sdslen(info
)));
2963 addReplySds(c
,info
);
2964 addReply(c
,shared
.crlf
);
2967 /* =============================== Replication ============================= */
2969 /* Send the whole output buffer syncronously to the slave. This a general operation in theory, but it is actually useful only for replication. */
2970 static int flushClientOutput(redisClient
*c
) {
2972 time_t start
= time(NULL
);
2974 while(listLength(c
->reply
)) {
2975 if (time(NULL
)-start
> 5) return REDIS_ERR
; /* 5 seconds timeout */
2976 retval
= aeWait(c
->fd
,AE_WRITABLE
,1000);
2979 } else if (retval
& AE_WRITABLE
) {
2980 sendReplyToClient(NULL
, c
->fd
, c
, AE_WRITABLE
);
2986 static int syncWrite(int fd
, void *ptr
, ssize_t size
, int timeout
) {
2987 ssize_t nwritten
, ret
= size
;
2988 time_t start
= time(NULL
);
2992 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
2993 nwritten
= write(fd
,ptr
,size
);
2994 if (nwritten
== -1) return -1;
2998 if ((time(NULL
)-start
) > timeout
) {
3006 static int syncRead(int fd
, void *ptr
, ssize_t size
, int timeout
) {
3007 ssize_t nread
, totread
= 0;
3008 time_t start
= time(NULL
);
3012 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
3013 nread
= read(fd
,ptr
,size
);
3014 if (nread
== -1) return -1;
3019 if ((time(NULL
)-start
) > timeout
) {
3027 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
3034 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
3037 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
3048 static void syncCommand(redisClient
*c
) {
3051 time_t start
= time(NULL
);
3054 /* ignore SYNC if aleady slave or in monitor mode */
3055 if (c
->flags
& REDIS_SLAVE
) return;
3057 redisLog(REDIS_NOTICE
,"Slave ask for syncronization");
3058 if (flushClientOutput(c
) == REDIS_ERR
||
3059 rdbSave(server
.dbfilename
) != REDIS_OK
)
3062 fd
= open(server
.dbfilename
, O_RDONLY
);
3063 if (fd
== -1 || fstat(fd
,&sb
) == -1) goto closeconn
;
3066 snprintf(sizebuf
,32,"$%d\r\n",len
);
3067 if (syncWrite(c
->fd
,sizebuf
,strlen(sizebuf
),5) == -1) goto closeconn
;
3072 if (time(NULL
)-start
> REDIS_MAX_SYNC_TIME
) goto closeconn
;
3073 nread
= read(fd
,buf
,1024);
3074 if (nread
== -1) goto closeconn
;
3076 if (syncWrite(c
->fd
,buf
,nread
,5) == -1) goto closeconn
;
3078 if (syncWrite(c
->fd
,"\r\n",2,5) == -1) goto closeconn
;
3080 c
->flags
|= REDIS_SLAVE
;
3082 if (!listAddNodeTail(server
.slaves
,c
)) oom("listAddNodeTail");
3083 redisLog(REDIS_NOTICE
,"Syncronization with slave succeeded");
3087 if (fd
!= -1) close(fd
);
3088 c
->flags
|= REDIS_CLOSE
;
3089 redisLog(REDIS_WARNING
,"Syncronization with slave failed");
3093 static int syncWithMaster(void) {
3094 char buf
[1024], tmpfile
[256];
3096 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
3100 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
3104 /* Issue the SYNC command */
3105 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
3107 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
3111 /* Read the bulk write count */
3112 if (syncReadLine(fd
,buf
,1024,5) == -1) {
3114 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
3118 dumpsize
= atoi(buf
+1);
3119 redisLog(REDIS_NOTICE
,"Receiving %d bytes data dump from MASTER",dumpsize
);
3120 /* Read the bulk write data on a temp file */
3121 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
3122 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644);
3125 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
3129 int nread
, nwritten
;
3131 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
3133 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
3139 nwritten
= write(dfd
,buf
,nread
);
3140 if (nwritten
== -1) {
3141 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
3149 if (rename(tmpfile
,server
.dbfilename
) == -1) {
3150 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
3156 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
3157 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
3161 server
.master
= createClient(fd
);
3162 server
.master
->flags
|= REDIS_MASTER
;
3163 server
.replstate
= REDIS_REPL_CONNECTED
;
3167 static void monitorCommand(redisClient
*c
) {
3168 /* ignore MONITOR if aleady slave or in monitor mode */
3169 if (c
->flags
& REDIS_SLAVE
) return;
3171 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
3173 if (!listAddNodeTail(server
.monitors
,c
)) oom("listAddNodeTail");
3174 addReply(c
,shared
.ok
);
3177 /* =================================== Main! ================================ */
3179 static void daemonize(void) {
3183 if (fork() != 0) exit(0); /* parent exits */
3184 setsid(); /* create a new session */
3186 /* Every output goes to /dev/null. If Redis is daemonized but
3187 * the 'logfile' is set to 'stdout' in the configuration file
3188 * it will not log at all. */
3189 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
3190 dup2(fd
, STDIN_FILENO
);
3191 dup2(fd
, STDOUT_FILENO
);
3192 dup2(fd
, STDERR_FILENO
);
3193 if (fd
> STDERR_FILENO
) close(fd
);
3195 /* Try to write the pid file */
3196 fp
= fopen(server
.pidfile
,"w");
3198 fprintf(fp
,"%d\n",getpid());
3203 int main(int argc
, char **argv
) {
3206 ResetServerSaveParams();
3207 loadServerConfig(argv
[1]);
3208 } else if (argc
> 2) {
3209 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
3213 if (server
.daemonize
) daemonize();
3214 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
3215 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
3216 redisLog(REDIS_NOTICE
,"DB loaded from disk");
3217 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
3218 acceptHandler
, NULL
, NULL
) == AE_ERR
) oom("creating file event");
3219 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
3221 aeDeleteEventLoop(server
.el
);